我有一个用Swing库编写的Java表单,其中包含几个JTextField对象和一个JButton对象。
当用户单击按钮时,我需要的是一个要调用的方法,它读取JTextField对象的所有值并将它们作为另一个方法的参数传递。
在HTML / JavaScript中,这类似于:
<input type="button" onClick="myMethod()">
myFunction()将查看表单中的所有文本字段并读取值,然后返回这些值的数组。
想法? :)
由于
的Dario
答案 0 :(得分:2)
选中此http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
b = new Button("Click me");
b.addActionListener(this);
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
答案 1 :(得分:2)
public class Test extends JFrame {
JTextField jtf1 = new JTextField(10);
JTextField jtf2 = new JTextField(10);
JTextField jtf3 = new JTextField(10);
JTextField jtf4 = new JTextField(10);
JButton button = new JButton("Button");
public Test() {
JPanel panel = new JPanel(new GridLayout(4, 1));
panel.add(jtf1);
panel.add(jtf2);
panel.add(jtf3);
panel.add(jtf4);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener(){ // add a listener to the button
public void actionPerformed(ActionEvent e){ // perform the action when clicked
String str1 = jtf1.getText(); // get input from text field 1
String str2 = jtf2.getText(); // get input from text field 2
String str3 = jtf3.getText(); // get input from text field 3
String str4 = jtf4.getText(); // get input from text field 4
// do something with strings
someMethod(str1, str2, str3, str4); // pass to someMethod
}
});
}
private void someMethod(String s1, String s2, String s3, String s4){
// dumb example
System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
Test test = new Test();
test.setDefaultCloseOperation(EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
});
}
}
注意:如果您想要文本字段中的数值,则应解析文本