我对 java Window Builder 应用程序有疑问。我需要让这个应用程序将名称(textField)保存到另一个类的数组变量中。
因此,当您按下 New Name 按钮时,应该从 textField 中传递 Name,并让您引入另一个名称并将这个新名称传递到数组中的下一个位置,依此类推。之后,数组中的名称必须显示到 textArea
问题是当我按下按钮时,而不是将 textField 文本传递到数组中,我得到了很多摆动错误。如果我将“n”变量从 String[] 更改为 String,它不会给我任何错误,但它只会保存一个名称。
数据类
public class data {
String[] n;
public void saveData(String na, int counter){
n[counter]=na;
}
public void showData(int counter){
for (int i = 0; i < counter; i++) {
System.out.println(n[counter]);
}
}
}
窗口类
import java.awt.EventQueue;
public class dataWindow {
// Data OBJECT
data d = new data();
private JFrame frame;
private JTextField textName;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dataWindow window = new dataWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public dataWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblName = new JLabel("Name");
textName = new JTextField();
textName.setColumns(10);
JButton btnNewName = new JButton("New Name");
btnNewName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String n;
int c=0;
// HERE I GET THE TEXT AND PASS IT TO THE ARRAY IN DATA CLASS
// here I think that I get the error when I press the "New Name" button
n=textName.getText();
d.saveData(n, c);
textName.setText("");
c++;
}
});
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(44)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewName)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblName)
.addGap(18)
.addComponent(textName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(259, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(72)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblName)
.addComponent(textName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 114, Short.MAX_VALUE)
.addComponent(btnNewName)
.addGap(33))
);
frame.getContentPane().setLayout(groupLayout);
}
}
有人可以帮帮我吗?提前致谢。