我正致力于为今年早些时候负责的程序创建基本GUI。我的目标是让程序执行时,显示的第一个屏幕是用户输入其名称的字段。按下回车键或提交按钮,然后将它们引导到另一个窗口,该窗口将播放器的名称嵌入为图层。
现在我不确定我是以最有效的方式做到这一点,但是通过阅读多个答案,创建单独的框架似乎是最好的方法,但如果我错了就纠正我。
执行
时出现以下错误"线程中的异常" AWT-EventQueue-0" 显示java.lang.NullPointerException"
所以我首先运行loginpanel 代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class loginPanel extends JFrame {
public static void main(String[] args) {
loginPanel loginFrame = new loginPanel();
}
private JButton submit;
private JLabel playerName;
private JTextField nameInput;
public String name;
JPanel panel = new JPanel();
loginPanel() {
setTitle("Game Data");
setSize(300, 400);
setLocationRelativeTo(null);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (nameInput.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid Input, please try again");
}
else {
name = nameInput.getText();
gameDataPanel mainFrame = new gameDataPanel();
mainFrame.setVisible(true);
dispose();
}
}
});
playerName = new JLabel("Enter Player Name");
nameInput = new JTextField(30);
nameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (nameInput.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid Input, please try again");
}
else {
name = nameInput.getText();
gameDataPanel mainFrame = new gameDataPanel();
mainFrame.setVisible(true);
dispose();
}
}
});
panel.add(playerName);
panel.add(nameInput);
panel.add(submit);
getContentPane().add(panel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public String grabName() {
return nameInput.getText();
}
}
然后它应该在按下提交时运行:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class gameDataPanel extends JFrame {
private JLabel playerName, gameName, gameScore, timePlayed;
private JTextField gameNameField, gameScoreField, timePlayedField;
private loginPanel login;
private String name2;
public static void main(String[] args) {
gameDataPanel mainFrame = new gameDataPanel();
}
JPanel panel = new JPanel();
gameDataPanel() {
setTitle("Game Data Entry Program");
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
name2 = login.name;
playerName.setText(name2);
panel.add(playerName);
getContentPane().add(panel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
问题是它永远不会超过第一个屏幕,任何帮助都表示赞赏。谢谢!