用户在文本字段中输入数字并单击按钮后,我想在另一个文本字段中返回该值,我不确定我需要哪个类,有什么提示吗?非常感谢你,这是我的代码:
private void newNumber(Container container){
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraint = new GridBagConstraints();
//add the new number
labelname = new JLabel("Enter the number: ");
constraint.gridx = 0;
constraint.gridy = 0;
panel.add(labelname, constraint);
number= new JTextField(10);
constraint.gridx = 1;
constraint.gridy = 0;
panel.add(number, constraint);
addnumber = new JButton("Add number");
constraint.gridx = 0;
constraint.gridy = 3;
panel.add(addnumber, constraint);
container.add(panel,"North");
}
我知道它应该有一个关于ActionListener的方法,但我仍在弄清楚它:)
答案 0 :(得分:2)
基本上,您为按钮分配一个ActionListener,以便对click事件做出反应。在此侦听器中,您将获得文本字段的值并将其分配给其他字段。
JButton yourButton= new JButton("Click me");
JTextField textField = new JTextField("Some initial value Textfield 1");
JTextField textField2 = new JTextField("Some initial value Textfield 2");
yourButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Get value of textfield 1
String currValue = textField.getText();
// Set value for textfield 2
textField2.setText(currValue);
}
});
答案 1 :(得分:0)
public class FramTest extends JFrame{
public static void main(String[] args){
FramTest framTest = new FramTest();
JPanel panel = new JPanel(new GridBagLayout());
//add the new number
JLabel labelname = new JLabel("Enter the number: ");
panel.add(labelname);
final JTextField number= new JTextField(10);
panel.add(number);
JButton addnumber = new JButton("Add number");
panel.add(addnumber);
final JTextField numberright= new JTextField(10);
addnumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numberright.setText(number.getText());
}
});
panel.add(numberright);
framTest.add(panel);
framTest.show();
}
}
答案 2 :(得分:0)
您必须向按钮添加ActionListener,并且在侦听器中,您可以添加对新方法的调用以执行所需的操作。我假设您想从文本字段“number”获取文本,并且您希望在名为“secondTextfield”的第二个文本字段中写入该值。
// Add the lister to the button
addnumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// Call a function to perform the action
setTheText(evt);
}
});
// Function to set the text
private void setTheText(java.awt.event.ActionEvent evt) {
secondTextfield.set(number.getText());
}