英文:
How do I access the panel1 which is non static in the main()
问题
public class task1 extends JFrame{
private JTextField firstnameTextField;
private JTextField surnameTextField;
private JTextField emailTextField;
private JButton submitButton;
private JPanel panel1;
// 这一部分是用来处理用户输入并显示提交信息的代码
public task1() {
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(panel1,
String.format(
"您的表单已提交,以下是提交的数据: \n" +
"名字: %s \n" +
"姓氏: %s \n" +
"电子邮件: %s",
firstnameTextField.getText(), surnameTextField.getText(), emailTextField.getText()));
}
});
}
// panel1 在这里未被识别,这是因为它是非静态变量在静态方法中使用,但我不确定如何更正这个问题
public static void main(String[] args) {
task1 frame = new task1();
frame.add(frame.panel1); // 添加 panel1 到窗口中
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
}
}
英文:
public class task1 extends JFrame{
private JTextField firstnameTextField;
private JTextField surnameTextField;
private JTextField emailTextField;
private JButton submitButton;
private JPanel panel1;
this section is mean't to have a message come up with the users inputs saying submitted but only blank window pops up
public task1() {
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(panel1,
String.format(
"You form has been submitted with the following data: \n" +
"First name: %0$s \n" +
"Surname: %1$s \n" +
"Email: %2$s",
firstnameTextField.getText(), surnameTextField.getText(), emailTextField.getText()));
}
});
}
>panel1 is not recognised and I know it is because of it being non static variable in static method but unsure how to correct this
public static void main(String[] args) {
task1 frame = new task1();
frame.add(panel1);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
}
}
答案1
得分: 1
将GUI构建逻辑移到你的构造函数中,它不应该放在 main
中:
public task1() {
panel1 = new JPanel();
add(panel1);
submitButton.addActionListener(new ActionListener() { … });
}
然而,仍然缺少组件的有意义的初始化。
英文:
Move the GUI building logic to your constructor, it doesn’t belong in main
anyway:
public task1() {
panel1 = new JPanel();
add(panel1);
submitButton.addActionListener(new ActionListener() { … });
}
However, this is still missing a meaningful initialisation of the components.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论