我想将我的JButton
调用输入函数作为我的JTextField
的输入。因此,如果我按下输入按钮,它会将我在JTextField
中记下的内容放在JLabel
中。
这是我的代码:
package Main_Config;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class SET_UP extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel consol;
public static Dimension size = new Dimension(800, 700);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SET_UP frame = new SET_UP();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SET_UP() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(370, 70, 0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setSize(size);
setLocationRelativeTo(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
});
textField.setBounds(10, 452, 243, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {}
});
enter.setBounds(253, 452, 89, 20);
contentPane.add(enter);
JLabel consol = new JLabel("");
consol.setBounds(0, 483, 335, 189);
contentPane.add(consol);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(352, 451, 200, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(584, 451, 200, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(0, 0, 89, 23);
contentPane.add(btnNewButton_2);
}
}
答案 0 :(得分:1)
我想让我的JButton调用enter函数作为我的JTextField的输入。
您在文本字段中添加了ActionListener
,但现在您需要共享ActionListener
使用文本字段和按钮。
所以你的代码应该是这样的:
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
};
...
textField.addActionListener(al);
enter.addActionListener(al);
现在,如果焦点在测试字段上,并且您使用Enter键,则会调用ActionListener
。或者,如果单击“Enter”按钮,则会调用相同的ActionListener
。