我已经设置了JButton,除了它什么都没有。有人能告诉我如何将命令如system.out.println或某些Scanner命令添加到JButton中吗?
这是我的代码行。这很简单,我只是测试JButton将它添加到我的其他程序
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
答案 0 :(得分:2)
请参阅How to Write an Action Listener。
我建议您阅读整个教程(或保留一个链接以供参考),因为它包含所有Swing基础知识。
答案 1 :(得分:0)
希望这有帮助
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});