问题
My task is to retrieve a value of text field and display it in a alert box when clicking on the button. how to generate the on click event for button in java swing ?
回答1:
For that, you need to use ActionListener, for example:
JButton b = new JButton("push me");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
}
});
For generating click event programmatically, you can use doClick() method of JButton: b.doClick();
回答2:
First, use a button, assign an ActionListener to it, in which you use JOptionPane to show the message.
class MyWindow extends JFrame {
public static void main(String[] args) {
final JTextBox textBox = new JTextBox("some text here");
JButton button = new JButton("Click!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, textBox.getText());
}
});
}
}
来源:https://stackoverflow.com/questions/21879243/how-to-create-on-click-event-for-buttons-in-swing