此问题已在此处有答案:
What is a NullPointerException, and how do I fix it?(12个回答)
2天前关闭。
当我尝试从文本字段中获取输入时,它会给我一条错误消息:
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot invoke "javax.swing.JTextField.getText()" because
"this.textField2" is null"
我已经尝试了我所知道的一切,我希望使用以下命令设置整数的值:
x = textField1.getText();
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.*;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener
{
JTextField textField1;
JTextField textField2;
JTextField textField3;
JButton button;
int[] newArr = new int[2];
int num1, num2, num3;
//we need to declare button and text field outside constructor so they become global
Frame()
{
//Text box
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setPreferredSize(new Dimension(500,100));
//Text field 1
JTextField textField1 = new JTextField();
textField1.setPreferredSize(new Dimension(40,40));
this.add(textField1);
//Text field 2
JTextField textField2 = new JTextField();
textField2.setPreferredSize(new Dimension(40,40));
this.add(textField2);
//Text field 3
JTextField textField3 = new JTextField();
textField3.setPreferredSize(new Dimension(40,40));
this.add(textField3);
//Button 1
button = new JButton("Submit Guess");
button.addActionListener(this);
this.add(button);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e .getSource() == button)//if source of event comes from button...
{
newArr[0] = Integer.parseInt(textField1.getText());
newArr[1] = Integer.parseInt(textField2.getText());
newArr[2] = Integer.parseInt(textField3.getText());
System.out.println(newArr[0] + newArr[1] + newArr[2]);
}
}
}
1条答案
按热度按时间fdbelqdn1#
Oracle有一个有用的教程Creating a GUI With Swing。跳过使用NetBeans IDE学习Swing部分。
下面是修改后的GUI:
创建一个
JPanel
放在JFrame
中有助于分离您的关注点,并一次专注于GUI的一个部分。使用
JFrame
比扩展JFrame
更好。不应该扩展任何Java类,除非您打算重写一个或多个类方法。Java数组必须足够长,以容纳数组的所有元素。
下面是完整的可运行代码。