问题
I want to make my JButton
called enter function as enter for my JTextField
. So like if I wear to press on the enter button it would put what I wrote down in JTextField
in the the JLabel
.
Here's my code:
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);
}
}
回答1:
I want to make my JButton called enter function as enter for my JTextField.
You added an ActionListener
to the text field, but now you need to share the ActionListener
with the text field and the button.
So your code would be something like:
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
};
...
textField.addActionListener(al);
enter.addActionListener(al);
Now if focus is on the test field and you use the Enter key the ActionListener
is invoked. Or if you click on the "Enter" button, the same ActionListener
is invoked.
来源:https://stackoverflow.com/questions/20169052/press-on-button-equals-print-what-ever-is-on-jtextfield-on-the-label