[英]How to: get input from JTextField after button is pressed
I am fairly new to Java and just wanted to ask about ActionListener method.我对 Java 还很陌生,只是想问一下 ActionListener 方法。 I've created a GUI and in one panel I want to ask the user to input values of x and press submit.
我创建了一个 GUI,在一个面板中我想要求用户输入 x 的值并按提交。 It looks like this: f(x)= [input field] - [input field] ^2 (submit button) I am lost and don't know what to put in ActionPerformed method to get the values that user inputs (also the method in which I created the panel, text fields etc is private if that's relevant )
它看起来像这样: f(x)= [input field] - [input field] ^2(提交按钮)我迷路了,不知道在 ActionPerformed 方法中放入什么来获取用户输入的值(也是方法我在其中创建面板、文本字段等是私有的(如果相关)
I have already tried x1.getText(), but it seems like it can't access the variable as the JPanel method is private, and ActionPerformed is public我已经尝试过 x1.getText(),但它似乎无法访问变量,因为 JPanel 方法是私有的,而 ActionPerformed 是公共的
private JPanel panel2()
{
inputPanel.setLayout(new FlowLayout());
JTextField x1 = new JTextField();
JTextField x2 = new JTextField();
JLabel f = new JLabel ("F(x)= ");
JLabel f2= new JLabel (" - ");
JLabel f3 = new JLabel (" ^2 ");
JButton submit1 = new JButton("Submit values");
submit1.addActionListener(this);
inputPanel.add(f);
inputPanel.add(x1);
inputPanel.add(f2);
inputPanel.add(x2);
inputPanel.add(f3);
inputPanel.add(submit1);
}
{
if("submit1".equals(e.getActionCommand()))
{
// and that's where I get lost
}
}
I am inferring by your discription that panel2 is a method and both JTextfields x1 and x2 are local variables of method panel2 which won't be accessible outside it.我根据您的描述推断 panel2 是一种方法,JTextfields x1 和 x2 都是方法 panel2 的局部变量,无法在其外部访问。
You will need to declare the x1 and x2 globally and if you want them to be private, associate getters and setters with them and use it in the actionperformed method.您需要全局声明 x1 和 x2,如果您希望它们是私有的,请将 getter 和 setter 与它们相关联并在 actionperformed 方法中使用它。
If you not gonna change No.1, you can define an inline function inside of the method, as you can see below:如果你不打算更改 No.1,你可以在方法内部定义一个内联 function,如下所示:
submit1.addActionListener(e -> {
System.err.println("x1 : " + x1.getText());
System.err.println("x2 : " + x2.getText());
});
Requires Java 1.8+需要 Java 1.8+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.