Java Window Builder アプリケーションに問題があります。名前 (textField) を別のクラスの配列変数に保存するには、このアプリケーションを作成する必要があります。
そのため、[新しい名前] ボタンを押すと、textField から名前を渡す必要があり、別の名前を導入して、この新しい名前を配列の次の位置などに渡すことができます。その後、配列の名前を textArea に表示する必要があります
問題は、ボタンを押すと、textField テキストを配列に渡す代わりに、多くのスイングエラーが発生することです。"n" 変数を String[] から String に変更すると、エラーは発生しませんが、保存される名前は 1 つだけです。
データクラス
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);
}
}
誰か助けてくれませんか?前もって感謝します。