我正在做我的java任务,我有一个GUI类,处理所有的图形用户界面组件,如按钮,我定义了GUI文件中的所有按钮,我想添加动作监听器按钮,但我想要动作侦听器动作在里面添加按钮动作侦听器类,这意味着当我单击按钮时它将调用动作侦听器的动作添加按钮动作侦听器类,下面是代码
public static void mainLayout(){
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
JToolBar toolbar = new JToolBar("Applications");
JButton addplayer = new JButton ("AddPlayer");
JButton placebet = new JButton("Place Bet");
buttonPane.add(addplayer);
buttonPane.add(placebet);
frame.add(buttonPane, BorderLayout.PAGE_START);
frame.setSize(500,200);
frame.setVisible(true);
}
和Action Listener类
public class addButtonActionListener {
public static void addPlayer() {
addplayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Add Success!!");
}
});
placebet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Place Bet Success!!");
}
});
}
答案 0 :(得分:0)
遵循命名约定,您的代码将更容易阅读。 其次:你的试验创建一个actionlistener是错误的。该类需要实现actionlistener,并在您提供的actionPerformed方法中具有业务逻辑。
您可以添加到按钮。