java怎么实现对另一个类中的按钮监听?

2024-12-30 23:02:26
推荐回答(5个)
回答1:

你只有一个窗体,

你想要的就是在一个“窗体类”中,监听一个“监听事件类”的意思吗

只要把监听事件类写在窗体类中,不就行了吗?

class GameState_Begin extends Frame
{
//构造器
public GameState_Begin()
{
Button btn1=new Button("开始游戏");
super.add(btn1);

btn1.addActionListener(new ButtonListen());
}

//●●●●●内部类:按钮事件监听
class ButtonListen implements ActionListener
{
public void actionPerformed(ActionEvent arg0) {

//改变panel布局的代码

}

}
}

回答2:

A的卡片布局换成另一个卡片panel,用卡片布局里的cardl.show(panel,"b");语句就可以了,我给你个例子,你看看。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Guess {
private JFrame frame = new JFrame("不说?!");
private Container container = frame.getContentPane();
private JPanel panel = new JPanel();
private JPanel pane1 = new JPanel();
private JPanel pane2 = new JPanel();
private JButton button1 = new JButton("Kiss Me");
private JButton button2 = new JButton("Back,and...");
private JLabel label = new JLabel("Yes, you are sussesed!");
private CardLayout cardl = new CardLayout();

Guess() {
container.setLayout(new BorderLayout());
panel.setLayout(cardl);
container.add(panel,BorderLayout.CENTER);
pane1.setLayout(new FlowLayout(FlowLayout.LEFT));
pane2.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(pane1,"a");
panel.add(pane2,"b");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardl.show(panel,"b");
frame.setTitle("oh! Yes.");
}
});
pane1.add(button1);
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cardl.show(panel,"a");
frame.setTitle("还是不说?");
}
});
pane2.add(label);
pane2.add(button2);
frame.setSize(300,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {
Guess g = new Guess();
}
}

回答3:

在另一个类中,实现Get方法,或者将按钮设为public。
然后,在本类中实现监听接口,将另一个类中的按钮的监听接口设为本类
然后设置发送的ActionCommand

回答4:

写回调函数,即那个按钮的事件回调你的想调的方法,或者弄一个共享变量,当按钮事触发就改变该值,然后弄一个线程一直监视该变量。

回答5:

调用而已