如果我正在创建一个类,并且将在我的JFrame中加载该类的对象(该类基本上是一个带有按钮和文本对象的面板,但这并不重要),直到我的public static void main(String[] args) {(位于类代码下面)才会被实例化,那么我如何将WindowListener和其他侦听器关联到该JFrame,因为它不是原始类的一部分?
通常,当我遇到这个问题时,Eclipse会告诉我将JFrame或其他对象设置为静态的,并对其进行通用调用,但我尝试过了,我认为它不适用于JFrame的实例。
我已经通读了http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html和其他教程,但我希望在我的应用程序中对这个特定问题有一个一般性的答案,因为我经常遇到这个问题。
感谢任何人谁可以帮助或任何人谁读了本文!
发布于 2011-09-03 05:45:20
向我们展示您的现有代码将使您更清楚地知道您正在尝试做什么,但听起来好像您有一个既表示面板又包含main方法的类。这是可能的,但我不推荐它,因为它模糊了应用程序的结构,尽管它是教程中的一种流行技术,因为它使所有内容都可以放在一个文件中。
监听器( WindowListener )表示需要响应窗口事件的任何对象,即当窗口被激活、图标化等时窗口(在这种情况下是JFrame )的状态改变。监听器也可以表示图形组件,但不需要这样做。
这里有一个非常简单的例子,我希望它能说明这些概念。让我们创建一个类来表示一种面板类型,其中包含一个JLabel,它将显示到目前为止发生的窗口事件的数量。它还将实现WindowListener,以便可以通知它这些事件,并在每次发生一个事件时递增一个计数器。
您应该能够按原样编译和运行此代码,然后在最小化/最大化窗口、单击其他窗口等情况下观察计数器的变化。
import java.awt.event.*;
import javax.swing.*;
public class TestPanel extends JPanel implements WindowListener {
private JLabel label = new JLabel("No window events yet");
private int numEvents = 0;
public TestPanel() {this.add(label);}
private void update() {
label.setText(String.format("%d events",numEvents));
}
public void windowOpened(WindowEvent e) {
numEvents++;
update();
}
// ... similar implementations of the other WindowListener methods ...
}然后,我们需要一个主程序来实例化我们的一个面板,并在JFrame中显示它。
import javax.swing.*;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
private static void createAndDisplayGui() {
JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestPanel panel = new TestPanel();
frame.add(panel); // add the panel as a component in the frame
frame.addWindowListener(panel); // add the panel as a listener to the frame
frame.pack(); // lay out and size the frame
frame.setVisible(true); // display the frame
}
}https://stackoverflow.com/questions/7289086
复制相似问题