Implementing WindowListener Error - java

Hello I'm having a problem with adding a WindowListener to my JFrame... It's saying "windowClosing can't be resolved to a type" and I don't know how to fix the error.
public Editor() {
//Create JFrame For Editor
JFrame SimplyHTMLJFrame = new JFrame();
SimplyHTMLJFrame.setTitle("Simply HTML - Editor");
SimplyHTMLJFrame.setSize(800, 600);
SimplyHTMLJFrame.setResizable(true);
SimplyHTMLJFrame.setLocationRelativeTo(null);
SimplyHTMLJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
SimplyHTMLJFrame.addWindowListener(new windowClosing()); //The error is here it underlines windowClosing in red
SimplyHTMLJFrame.setVisible(true);
System.out.println("Editor - JFrame 'SimplyHTMLJFrame' - Created");
//Program Closing Alert
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n"
+ "All unsaved changes will be lost!","Confirm", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
//Do nothing
}
}
}

You have to implement an inner class for the WindowListener callback.
public class Editor {
public Editor() {
// Create JFrame For Editor
JFrame SimplyHTMLJFrame = new JFrame();
SimplyHTMLJFrame.setTitle("Simply HTML - Editor");
SimplyHTMLJFrame.setSize(800, 600);
SimplyHTMLJFrame.setResizable(true);
SimplyHTMLJFrame.setLocationRelativeTo(null);
SimplyHTMLJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
SimplyHTMLJFrame.addWindowListener(new WindowAdapter() {
// Program Closing Alert
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n" + "All unsaved changes will be lost!", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
// Do nothing
}
}
}); // The error is here it underlines windowClosing in red
SimplyHTMLJFrame.setVisible(true);
System.out.println("Editor - JFrame 'SimplyHTMLJFrame' - Created");
}

new windowClosing() is not a class, so you can't instantiate it. You have two options.
Make the class implements WindowListener and use .addWindowListener(this).
Or, create an annonymous class
SimplyHTMLJFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e) {
....
});
Note, if you choose method one, you will need to implements all the window listener methods below You can leave the ones you don't need, empty methods, but they still all need to be overridden. If you choose the second method, you can just use a WindowAdapter and just override the methods you need.
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosing(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
As a side note, it's good practice to use the #Override annotation for method that is being overriden, so you know that you are correctly overriding a method.

The mistake you have done is, you are instantiating a method instead of a type
SimplyHTMLJFrame.addWindowListener(new windowClosing());
here windowClosing is a method in your JFrame class
You need to create our own WindowAdapter/WindowListener and add it as listener to your JFrame
Create a separate class in same/other package
class MyWindowAdapter extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n"
+ "All unsaved changes will be lost!","Confirm", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
//Do nothing
}
}
}
add it to your JFrame Editor
SimplyHTMLJFrame.addWindowListener(new MyWindowAdapter());

windowClosing() is the name of a method and not a class that can be instantiated.
You need to pass an instance of a WindowListener to SimplyHTMLJFrame.addWindowListener. Assuming that your Editor class either implements WindowListener or extends WindowAdapter, an assumption I'm making based on the presence of the windowClosing method, this line would be valid.
SimplyHTMLJFrame.addWindowListener(this);

Related

Problem with creating a new KeyListener inside a class

I'm having serious issues with adding a keylistener to my Java program.
I would like to avoid the addKeyListener() method, so I tried the following solutions:
public class game implements KeyListener{
#Override
public void keyTyped(KeyEvent e) {
return;
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("test");
return;
}
#Override
public void keyReleased(KeyEvent e) {
return;
}
}
And:
public class game{
KeyListener listener = new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
return;
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("test");
return;
}
#Override
public void keyReleased(KeyEvent e) {
return;
}
}
}
None of them worked for me.
Do I really have to use the addKeyListener() in a graphics class? I'm trying to avoid that.
Thanks in advance.
Is there a particular reason you want to avoid using addKeyListener()?
It's an essential part of KeyListener so you won't be able to avoid using it.
Should be relatively easy to implement though. If you're using JFrame, the following code within your constructor should work:
public class Game implements KeyListener{
public Game(){
JFrame jframe = new JFrame();
jframe.addKeyListener(this);
}
//implement other KeyListener methods
}
This way, the Game class itself acts as the listener and can implement all of the necessary methods.
Hope this helps!

How to trap Java windowIconified() and windowIDeconified() before updateUiChanged() event?

My Java Swing application uses updateUiChanged() to resize fonts after its jFrame has been resized by the user. But updateUiChanged() is getting triggered when the jFrame is minimized and then maximized which is causing problem
I tried to trap the minimize and maximize events with the following, but they do not execute at all or they execute after the updateUiChanged() which is too late.
How can I trap the minimize and maximize before the updateUiChanged()
See below for the updateUiChanged implementation.
Thanks
private WindowListener wndMinMax;
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
return;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
return;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
updateUiChanged((int) e.getComponent().getWidth(),
(int) e.getComponent().getHeight());
}
}
});
You can use EventQueue.invokeLater to make sure your updateUiChanged call takes place after the WindowEvent. You can track the occurrence of a WindowEvent in a private instance field, so your delayed ComponentListener code can know if the resize was paired with a WindowEvent:
private boolean iconifyStateChanged;
// ...
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
iconifyStateChanged = true;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
iconifyStateChanged = true;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
// This will run after any pending WindowEvents.
EventQueue.invokeLater(() -> {
if (!iconifyStateChanged)
{
updateUiChanged(e.getComponent().getWidth(),
e.getComponent().getHeight()));
}
iconifyStateChanged = false;
});
}
}
});
(getWidth() and getHeight() already return int values, so a cast to int is not necessary.)

how do I make this window close in java?

I've already this project, but I'm having more problems. The dialog for SetMusicDialog opens, but it won't close when I try to exit out. I have a System.exit, but I'm not sure why the window won't close.
import java.awt.*;
import java.io.*;
public class SetMusicDialog extends Dialog
{
public static String sng;
public SetMusicDialog()
{
super ((Dialog)null, "Set Music");
Panel mpanel;
Font l = new Font("Helvetica", Font.ITALIC, 12);
setFont(l);//sets font
setBackground(Color.cyan);
Panel f = new Panel();
f.add("West", new Button("Death Grips"));
f.add("East", new Button("Siren"));
add("South",f);
pack(); // make it just fit
resize(preferredSize());
move(200,200);
}
public boolean handleEvent1 (Event evt)
{
switch (evt.id)
{
case Event.WINDOW_DESTROY:
System.exit(0);
dispose();
return true;
case Event.ACTION_EVENT:
if("Death Grips".equals(evt.arg))
{
sng= "breakmirrors.wav";
}
else if("Siren".equals(evt.arg))
{
sng= "bip.wav";
}
dispose();
}
return false;
}
}
You can add this:
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
windowClosed won't detect if the user tries to close the window. It will only run if the window has been closed. So use windowClosing.
Also, by using WindowAdapter you do not need to write all the methods of WindowListener.
I added this code in your constructor, and it works properly.
If you are using AWT, you should create a WindowListener as MadProgrammer stated. Basically, a WindowListener is a class that has methods that are run when certain window-related actions occur. To write code that will run when a Dialog (which extends Window) is closed:
//d is a dialog
d.addWindowListener(new WindowListener() {
//You'll need to implement all the abstract methods. leave them empty.
#Override
public void windowClosed(WindowEvent e) {
//Your code
}
});
Basically, you're anonymously implementing the abstract class WindowEvent. Make sure you implement all the other methods too, or you will get compiler errors. Your IDE should automatically implement all the methods.

MessageBox when closing

I looking for create mechanism for messaging when exiting and changes has been made.
I want it to display a messagebox asking the user :
( Are you sure you don't want to save the changes - yes / no)
Upon closing the form by clicking on the button named 'Exit' or when use close button, ''X". Don't know the syntax for it, can someone help me please?
Here's some basic code on how to do it:
public class ClosingFrame extends JFrame {
public ClosingFrame() {
super("Shutdown hook");
setSize(400, 400);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* important */
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
int showConfirmDialog = JOptionPane.
showConfirmDialog(ClosingFrame.this, "Do you want to save?");
if (showConfirmDialog == JOptionPane.YES_OPTION) {
System.out.println("saved");
System.exit(0);
} else if (showConfirmDialog == JOptionPane.NO_OPTION) {
System.out.println("not saved");
System.exit(0);
} else {
System.out.println("aborted");
// do nothing
}
}
});
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ClosingFrame());
}
}

Why isn't componentHidden called for my JPopupMenu?

I want to be notified when my JPopupMenu is hidden — whether because an item was selected, the menu was dismissed, or setVisible(false) was called on it. Here is my test code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class A extends ComponentAdapter implements Runnable, ActionListener {
private JButton b;
public static void main(String[] args) {
EventQueue.invokeLater(new A());
}
public void run() {
JFrame f = new JFrame("Test");
b = new JButton("Click me");
b.addActionListener(this);
f.add(b);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JPopupMenu pm = new JPopupMenu();
pm.addComponentListener(this);
pm.add("Popup...");
pm.add("...menu!");
pm.show(b, 10, 10);
}
public void componentShown(ComponentEvent e) { System.out.println("componentShown"); }
public void componentHidden(ComponentEvent e) { System.out.println("componentHidden"); }
}
Regardless of how I interact with the menu, neither of the two ComponentListener methods are being called. Why is that? Is there different/better/correct way of finding out when my JPopupMenu is hidden?
Thanks,
Cameron
JPopupMenu has a special listener for visibility change events:
pm.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
System.out.println("cancelled");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
System.out.println("vanishing");
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
System.out.println("appearing");
}
});
Note, however, as method names hint, they are called before visibility changes, so if you're calling isVisible() somewhere in the event handlers, you should be aware of that, for example:
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
updateMenu();
}
private void updateMenu() {
if (!menu.isVisible()) { // this won't work!
// perform some updates
}
}
With regards to why ComponentListener isn't sending you events on the menu disappearing, this might explain:
The component-hidden and component-shown events occur only as the result of calls to a Component 's setVisible method. For example, a window might be miniaturized into an icon (iconified) without a component-hidden event being fired.
Source: ComponentListener tutorial (non-canonical perhaps, but from the horse's mouth.)
Consider that in conjunction with JPopupMenu's implementation of setVisible:
public void setVisible(boolean b) {
// Not supported for MenuComponents
}
And you might know how it so happens, but not why it happens (what is the justification and where is that properly documented?)

Categories