[英]How to store value from JTextField to a local variable?
I want to store the value from TextField to a local variable so I can get the value by reference it from other package 我想将TextField中的值存储到本地变量中,以便可以通过从其他包中引用它来获取该值
I have tried a few way to solve this myself, but I found the value null. 我已经尝试了几种方法自己解决此问题,但是我发现值null。
private JButton execute = new JButton("Execute");
public JTextField radius = new JTextField(5);
// Find the result.
gc.gridx = 2;
gc.gridy = 3;
gc.weightx = 1;
gc.weighty = 1;
add(execute, gc);
List<MainController> listeners = new ArrayList<MainController>();
execute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (MainController listener : listeners) {
listener.notify(radius.getText());
}
}
});
add(execute, gc);
and the one below is the class I want to get the value 下面的是我想要获得价值的课程
public class MainController extends JFrame {
private int radius;
private static final long serialVersionUID = 1L;
public void notify(String rad) {
radius = Integer.parseInt(rad);
System.out.println(radius);
}
} }
What should I do to store the value to a local variable so that I can get the value from other package 我应该怎么做才能将值存储到局部变量,以便可以从其他包中获取值
From the code you have, I understand that when you press the button you want to save the text inside radius oa local variable, strRad, so later on you can access it from another class. 从您拥有的代码中,我了解到,当您按下按钮时,您想将文本保存在本地变量strRad的半径内,以便以后可以从另一个类访问它。 If that is the case then you can maybe create a listener pattern yourself and then have something like:
如果是这种情况,那么您可以自己创建一个侦听器模式,然后执行以下操作:
private List<YourListener> listeners = new ArrayList<>();
.
.
.
execute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (YourListener listener : listeners) {
listener.notify(radius.getText());
}
}
});
You have to create the YourListener interface other class that wants to access the JTextField value would implement it. 您必须创建YourListener接口,其他想要访问JTextField值的类将实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.