我的任务是在单击按钮时检索文本字段的值并在警告框中显示它。我如何为Java Swing中的按钮生成单击事件?
为此,您需要使用ActionListener
,例如:
JButton b = new JButton("push me");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
}
});
要通过编程方式生成点击事件,可以使用JButton
的doClick()
方法:b.doClick();
首先,使用一个按钮,为其分配一个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());
}
});
}
}
JTextBox
是一个真正的类。这个不起作用... - data princessJButton button = new JButton("click me");
button.addActionListener(e ->
{
// your code here
});
然而,如果你指的是 Qt 中的信号和槽机制,则 Swing 不支持此特性。但是你可以使用“观察者”模式(链接)自己实现。
public GUI() {
JButton btn1 = new JButton("点击我!");
add(btn1);
btn1.addActionListener(new ActionListener()) {
@Override
public void actionPerformed(ActionEvent e) {
//action for the button
}
}
}
JButton jEightButton=new JButton();
jEightButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jframe.getContentPane().setBackground(Color.blue);
}
actionPerformed
方法通常在按钮被点击时使用。如果您想要对按钮进行一些花哨的交互,您也可以使用 其他事件,例如mousePressed
在 MouseListener 中。 - SebastianH