Sur*_*esh 4 java swing jbutton
我的任务是检索文本字段的值,并在单击按钮时将其显示在警告框中.如何在java swing中为按钮生成on click事件?
ale*_*410 16
为此,您需要使用ActionListener,例如:
JButton b = new JButton("push me");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
}
});
Run Code Online (Sandbox Code Playgroud)
要以编程方式生成click事件,您可以使用以下doClick()方法JButton:b.doClick();
您还可以使用 lambda 函数:
JButton button = new JButton("click me");
button.addActionListener(e ->
{
// your code here
});
Run Code Online (Sandbox Code Playgroud)
但是,如果您指的是 Qt 中的信号和槽,则 Swing 不支持这一点。但您始终可以使用“观察者”模式(链接)自己实现这一点。
首先,使用一个按钮,为其分配一个 ActionListener,在其中使用 JOptionPane 来显示消息。
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());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)