MTC*_*ter 4 java swing jframe actionlistener
我正在尝试创建自己的窗口类,扩展JFrame.但是,我遇到了动作监听器的问题fullScreenBtn.在编写ActionListener.actionPerformed函数时,我无法使用this它所引用的关键字new ActionListener.我如何参考实例MyWindow?
public class MyWindow extends JFrame {
private static GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
private static GraphicsDevice gDev = gEnv.getDefaultScreenDevice();
private static JPanel toolbar = new JPanel();
private static JButton fullScreenBtn = new JButton("Show Full Screen");
private static boolean isFullScreen = false;
public MyWindow() {
toolbar.setLayout(new FlowLayout());
this.getContentPane().add(toolbar, BorderLayout.PAGE_START);
fullScreenBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Toggle full screen window
this.setUndecorated(!isFullScreen);
this.setResizable(isFullScreen);
gDev.setFullScreenWindow(this);
isFullScreen = !isFullScreen;
if (isFullScreen) {
fullScreenBtn.setText("Show Windowed");
} else {
fullScreenBtn.setText("Show Full Screen");
}
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
this.dispose();
System.exit(0);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
在内部类中this,如果需要获取对外部类的引用,则需要在外部类的类名前面使用它:例如,使用
MyWindow.this.setUndecorated(...)`
// etc...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你真的不想在这里扩展JFrame,在大多数情况下.
此外,保存JButton的祖先窗口可以通过其他方式获得,例如via SwingUtilities.getWindowAncestor(theButton).即
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton button = (button) source;
Window ancestorWin = SwingUtilities.getAncestorWindow(button);
ancestorWin.setUndecorated(!isFullScreen);
ancestorWin.setResizable(isFullScreen);
// etc...
Run Code Online (Sandbox Code Playgroud)
或者,如果您最清楚地知道祖先窗口是JFrame:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton button = (button) source;
JFrame ancestorWin = (JFrame) SwingUtilities.getAncestorWindow(button);
ancestorWin.setUndecorated(!isFullScreen);
ancestorWin.setResizable(isFullScreen);
// etc...
Run Code Online (Sandbox Code Playgroud)