我试图学习如何在另一个类中使用1个类的变量。第一个类的作用是将int testInt设置为0,一旦在textField中插入一个值,然后按下按钮就会将值更改为该数字。但问题是,当我尝试在另一个类中使用该变量时,我打印出一个0而不是我输入的数字。
创建变量的第一个类,也应该更改它。
public class RouletteGui extends JPanel {
private JTextField tfInput = new JTextField();
private JPanel center = new JPanel(new BorderLayout());
private JPanel South = new JPanel(new BorderLayout());
private JButton btnSearch = new JButton("Change int value");
private int testInt = 0;
public RouletteGui() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 400));
center.add(tfInput, BorderLayout.CENTER);
add(South, BorderLayout.SOUTH);
add(center, BorderLayout.CENTER);
South.add(btnSearch, BorderLayout.SOUTH);
center.add(tfInput, BorderLayout.CENTER);
createListeners();
}
public void createListeners() {
button b = new button();
btnSearch.addActionListener(b);
}
private class button implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSearch) {
testInt = Integer.parseInt(tfInput.getText());
System.out.println(testInt);
}else{}
}
}
public int getTestInt(){
return testInt;
}
public static void main(String[] a) {
JFrame frame = new JFrame("Kalkylator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RouletteGui());
frame.pack();
frame.setVisible(true);
}
}
将写出int的第二个类。
public class WritingInt {
private RouletteGui rg = new RouletteGui();
public WritingInt(){
System.out.println(rg.getTestInt());
}
public static void main (String args[]){
WritingInt wi = new WritingInt();
}
}