所以我試圖創建一個登錄屏幕,提示用戶一個文本框和2個按鈕(登錄和取消)。當用戶登錄時,我想將JTextField
的值存儲在一個變量中,或者至少可以使用。當我嘗試使用playerNameTxt.getText()
方法進行任何操作時,出現錯誤,好像playerNameTxt
不存在。JTextField保存用戶輸入爲一個字符串
public class GUI extends JPanel implements ActionListener {
protected JTextField playerNameTxt;
public GUI() {
JTextField playerNameTxt = new JTextField(20);
JLabel playerNameLbl = new JLabel("Enter Player Name");
JButton loginBtn = new JButton("Login");
loginBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
loginBtn.setHorizontalTextPosition(AbstractButton.LEFT);
loginBtn.setMnemonic(KeyEvent.VK_D);
loginBtn.setActionCommand("login");
loginBtn.addActionListener(this);
loginBtn.setToolTipText("Click this to Login");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
cancelBtn.setHorizontalTextPosition(AbstractButton.RIGHT);
cancelBtn.setMnemonic(KeyEvent.VK_M);
cancelBtn.setActionCommand("cancel");
cancelBtn.addActionListener(this);
cancelBtn.setToolTipText("Click this to Cancel");
add(playerNameLbl);
add(playerNameTxt);
add(loginBtn);
add(cancelBtn);
}
public void actionPerformed(ActionEvent e) {
if ("login".equals(e.getActionCommand())) {
System.out.println(playerNameTxt);
} else {
System.exit(0);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("-- Munitions Login --");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(400, 200);
GUI newContentPane = new GUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我需要改變我的JLabel和Jbutton將被宣佈以同樣的方式? – 2014-10-09 16:21:05
@ThomasSteinholz我總是將它們聲明爲全局變量,而不是局部變量,但在你的情況下,不需要它(因此在你的情況下它並不重要) – msrd0 2014-10-09 16:21:57