I am trying to create my own window class which extends JFrame
. However, I am having a problem with the action listener for fullScreenBtn
. When writing the ActionListener.actionPerformed
funcion, I am unable to use the this
keyword as it refers to new ActionListener
. How do I refer to the instance of MyWindow
instead?
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);
}
});
}
}
In inner classes you will need to prepend your use of this
with the class name of the outer class if you need to obtain a reference to the outer class: For example, use
MyWindow.this.setUndecorated(...)`
// etc...
As an aside, you really don't want to extend JFrame here, and in most situations.
Also, the ancestor Window that holds the JButton can be obtained in other ways such as via SwingUtilities.getWindowAncestor(theButton)
. i.e.,
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...
Or if you know most definitely that the ancestor window is a 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...
This is the syntax of accessing the enclosing-class's instance from an inner-class or an anonymous-class:
OuterClass.this.foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With