我得到了下面的代码来获取文本,但我有一个问题。它给我一个错误,说它无法解决。我是java gui
的新手。希望可以有人帮帮我。我尝试使用nameP.getText();
,但没有用。我不确定为什么会出错?
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
JTextField nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
JTextField passwd = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
JTextField chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(passwd);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String name = nameP.getText();
}
}
答案 0 :(得分:2)
nameP
变量为local
,因此您无法在actionPerformed
之外引用它,在该范围之外nameP
不存在。如果您希望在其他地方使用它,可以将其声明为class member变量。
JTextField nameP;
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
nameP = new JTextField();
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String name = nameP.getText();
}