嗨,我希望一个类能够监听其组件之一的 JButton。 这里我有一个 Window 类,它有一个 MyPanel 组件,该组件本身有 JButtons。我希望在按下 MyPanel 的 JButton 时通知 Window。我怎样才能做到这一点?
这是一段代码,仅用于说明我的需求,尚未经过测试。
感谢您的帮助!
class Window extends JFrame {
private MyPanel myPane;
public static void main(String [] args) {
Window mainWindow = new Window();
}
public Window() {
this.myPane = new MyPanel();
getContentPane().add(myPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 600);
this.setVisible(true);
}
public computations() {
// Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed.
}
}
class MyPanel extends JPanel {
String s;
JButton b1;
JButton b2;
public MyPanel() {
s = new String("");
b1 = new JButton("say hello");
b2 = new JButton("Close");
this.add(b1);
this.add(b2);
ButtonHandler phandler = new ButtonHandler();
b1.addActionListener(phandler);
b2.addActionListener( actionPerformed(ActionEvent e) {
this.s = "Hello world";
});
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Tells Window class something happened.
}
}
}
最佳答案
我给你准备了一个促销 Activity ,你可以尝试一下是否有效。由于我刚刚设置了计算机,尚未安装 java 环境或 IDE,因此很抱歉无法测试我的解决方案。
要点是您可以将 Window 实例传递给 MyPanel,如下面的代码:
class Window extends JFrame {
public String myStr = "";
private MyPanel myPane;
public static void main(String [] args) {
Window mainWindow = new Window();
}
public Window() {
this.myPane = new MyPanel();
getContentPane().add(myPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 600);
this.setVisible(true);
}
public computations() {
// Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed.
System.out.println(this.myStr);
}
}
class MyPanel extends JPanel {
Window win = null;
String s;
JButton b1;
JButton b2;
public MyPanel(Window window) {
this.win = window;
s = new String("");
b1 = new JButton("say hello");
b2 = new JButton("Close");
this.add(b1);
this.add(b2);
ButtonHandler phandler = new ButtonHandler();
b1.addActionListener(phandler);
b2.addActionListener( actionPerformed(ActionEvent e) {
this.s = "Hello world";
});
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Tells Window class something happened.
this.win.myStr = s;
}
}
}
关于java - 如何监听其组件之一的JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22508993/