This site requires JavaScript, please enable it in your browser!
Greenfoot back
Nosson1459
Nosson1459 wrote ...

2017/1/3

stateChanged

Nosson1459 Nosson1459

2017/1/3

#
(How can I make)/(is there)/(how will/can I use) a method that will get called automatically when the size of my JFrame is changed (a window event method type of thing)? I tried this, I put this (below) in the "public ClassName()" method (in this method "public static void main(String args)" is "new ClassName().show();"):
addWindowListener(new WindowAdapter()
{
    public void windowStateChanged(WindowEvent e)
    {
        windowStateChanged(e);
    }
});
and I put this method right at the bottom of my code (inside the class method):
private void windowStateChanged(WindowEvent e)
{
    // code to do each time the size is changed on the window
}
But I have no idea if this is the way the windowStateChanged method is used. I was poking around here and here.
danpost danpost

2017/1/3

#
I believe that in your JFrame which implements WindowStateListener, you need to 'addWindowStateListener(this);' in the constructor. Then, your last code bit should work. Your first code bit should be trashed (you do not want to call a method from within itself there, anyway -- infinite calling of the method will cause a StackOverflow error). I noticed you had this in the method:
// code to do each time the size is changed on the window
Be aware that changing the size does not trigger the event unless going between maximized, minimized and iconified. Changing the width or height of the frame, otherwise, does not trigger the event.
Nosson1459 Nosson1459

2017/1/4

#
danpost wrote...
I believe that in your JFrame which implements WindowStateListener, you need to 'addWindowStateListener(this);' in the constructor.
I think you misunderstood me because the code you suggested gave me an error while my code didn't give me an error but it still didn't work (I have a feeling the problem lies somewhere else in my code).
Your first code bit should be trashed (you do not want to call a method from within itself there, anyway -- infinite calling of the method will cause a StackOverflow error).
I have the same setup somewhere else as shown above just instead of windowStateChanged I used windowClosing. It works perfectly and I don't get any errors (not this "StackOverflow error" either). Here is my class code so you can better understand what I mean (I'm leaving out the ExampleFileFilter class which gets used in my code):
/*
 * NoteEditor.java
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.text.*;

public class NoteEditor extends JFrame
{
	
	JMenuBar editorMenuBar = new JMenuBar();
	
	JMenu fileMenu = new JMenu("File");
	JMenuItem newMenuItem = new JMenuItem("New");
	JMenuItem openMenuItem = new JMenuItem("Open");
	JMenuItem saveMenuItem = new JMenuItem("Save");
	JMenuItem exitMenuItem = new JMenuItem("Exit");
	
	JMenu formatMenu = new JMenu("Format");
	JCheckBoxMenuItem boldMenuItem = new JCheckBoxMenuItem("Bold", false);
	JCheckBoxMenuItem italicMenuItem = new JCheckBoxMenuItem("Italic", false);
	JMenu sizeMenu = new JMenu("Size");
	ButtonGroup sizeGroup = new ButtonGroup();
	JRadioButtonMenuItem smallMenuItem = new JRadioButtonMenuItem("Small", true);
	JRadioButtonMenuItem mediumMenuItem = new JRadioButtonMenuItem("Medium", false);
	JRadioButtonMenuItem largeMenuItem = new JRadioButtonMenuItem("Large", false);
	
	JMenu helpMenu = new JMenu("Help");
	JMenuItem aboutMenuItem = new JMenuItem("About Note Editor");
	
	JScrollPane editorPane = new JScrollPane();
	JTextArea editorTextArea = new JTextArea();
	
	JFileChooser myChooser = new JFileChooser();
	
	Icon errorIcon = new ImageIcon("windows-error.png");
	Icon infoIcon = new ImageIcon("windows-info.png");
	Icon questionIcon = new ImageIcon("windows-question.png");
	Icon warningIcon = new ImageIcon("windows-warning.png");
	
	public static void main(String args[])
	{
		// construct frame
		new NoteEditor().show();
	}
	
	public NoteEditor()
	{
		// frame constructor
		setTitle("Note Editor");
		setIconImage(new ImageIcon("notepad.gif").getImage());
		setResizable(false);
		addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				exitForm(e);
			}
		});
		addWindowListener(new WindowAdapter()
		{
			public void windowStateChanged(WindowEvent e)
			{
				windowStateChanged(e);
			}
		});
		
		// build menu
		setJMenuBar(editorMenuBar);
				
		fileMenu.setMnemonic('F');
		formatMenu.setMnemonic('O');
		helpMenu.setMnemonic('H');
		
		newMenuItem.setAccelerator(KeyStroke.getKeyStroke('N', Event.CTRL_MASK));
		openMenuItem.setAccelerator(KeyStroke.getKeyStroke('O', Event.CTRL_MASK));
		saveMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK));
		boldMenuItem.setAccelerator(KeyStroke.getKeyStroke('B', Event.CTRL_MASK));
		italicMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', Event.CTRL_MASK));
		smallMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK));
		mediumMenuItem.setAccelerator(KeyStroke.getKeyStroke('M', Event.CTRL_MASK));
		largeMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', Event.CTRL_MASK));
		
		editorMenuBar.add(fileMenu);
		fileMenu.add(newMenuItem);
		fileMenu.add(openMenuItem);
		fileMenu.add(saveMenuItem);
		fileMenu.addSeparator();
		fileMenu.add(exitMenuItem);
		
		editorMenuBar.add(formatMenu);
		formatMenu.add(boldMenuItem);
		formatMenu.add(italicMenuItem);
		formatMenu.add(sizeMenu);
		sizeMenu.add(smallMenuItem);
		sizeMenu.add(mediumMenuItem);
		sizeMenu.add(largeMenuItem);
		sizeGroup.add(smallMenuItem);
		sizeGroup.add(mediumMenuItem);
		sizeGroup.add(largeMenuItem);
		
		editorMenuBar.add(helpMenu);
		helpMenu.add(aboutMenuItem);
		
		newMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				newMenuItemActionPerformed(e);
			}
		});
		
		openMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				openMenuItemActionPerformed(e);
			}
		});
		
		saveMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				saveMenuItemActionPerformed(e);
			}
		});
		
		exitMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				exitMenuItemActionPerformed(e);
			}
		});
		
		boldMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				formatMenuItemActionPerformed(e);
			}
		});
		
		italicMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				formatMenuItemActionPerformed(e);
			}
		});
		
		smallMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				formatMenuItemActionPerformed(e);
			}
		});
		
		mediumMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				formatMenuItemActionPerformed(e);
			}
		});
		
		largeMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				formatMenuItemActionPerformed(e);
			}
		});
		aboutMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				aboutMenuItemActionPerformed(e);
			}
		});
		
		getContentPane().setLayout(new GridBagLayout());
		
		// position scroll pane and text box
		GridBagConstraints gridConstraints=new GridBagConstraints();
		editorPane.setPreferredSize(new Dimension(300, 150));
		editorPane.setViewportView(editorTextArea);
		editorTextArea.setFont(new Font("Arial", Font.PLAIN, 12));
		editorTextArea.setLineWrap(false);
		editorTextArea.setWrapStyleWord(true);
		gridConstraints.gridx = 0;
		gridConstraints.gridy = 0;
		getContentPane().add(editorPane, gridConstraints);
		
		pack();
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setBounds((int) (0.5*(screenSize.width-getWidth())), (int) (0.5*(screenSize.height-getHeight())), getWidth(), getHeight());
		
		int fontSize;
		try
		{
			// open configuration file and set font values
			BufferedReader inputFile=new BufferedReader(new FileReader("note.ini"));
			
			boldMenuItem.setSelected(Boolean.valueOf(inputFile.readLine()).booleanValue());
			
			italicMenuItem.setSelected(Boolean.valueOf(inputFile.readLine()).booleanValue());
			fontSize=Integer.valueOf(inputFile.readLine()).intValue();
			inputFile.close();
		}
		catch (IOException ex)
		{
			JOptionPane.showConfirmDialog(null, ex.getMessage(), "Error Reading Configuration File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, errorIcon);
			boldMenuItem.setSelected(false);
			italicMenuItem.setSelected(false);
			fontSize=1;
		}
		
		switch (fontSize)
		{
			case 1:
				smallMenuItem.doClick();
				break;
			case 2:
				mediumMenuItem.doClick();
				break;
			case 3:
				largeMenuItem.doClick();
				break;
		}
        
	}
	
	private void newMenuItemActionPerformed(ActionEvent e)
	{
		// if user wants new file clear out text
		if (JOptionPane.showConfirmDialog(null, "Are you sure you want to start a new file?", "New File", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, questionIcon)==JOptionPane.YES_OPTION)
		{
			editorTextArea.setText("");
		}
	}
	
	private void openMenuItemActionPerformed(ActionEvent e)
	{
		String myLine;
		myChooser.setDialogType(JFileChooser.OPEN_DIALOG);
		myChooser.setDialogTitle("Open Text File");
		String[] ext=new String[] {"txt"};
		myChooser.addChoosableFileFilter(new ExampleFileFilter(ext, "Text Files"));
		if (myChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
		{
			try
			{
				// open input file
				BufferedReader inputFile = new BufferedReader(new FileReader(myChooser.getSelectedFile().toString()));
				editorTextArea.setText("");
				while((myLine = inputFile.readLine()) != null)
				{
					editorTextArea.append(myLine + "\n");
				}
				inputFile.close();
				editorPane.setPreferredSize(new Dimension(getWidth(), getHeight()));
			}
			catch (IOException ex)
			{
				JOptionPane.showConfirmDialog(null, ex.getMessage(), "Error Opening File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, errorIcon);
			}
		}
	}
	
	private void saveMenuItemActionPerformed(ActionEvent e)
	{
		myChooser.setDialogType(JFileChooser.SAVE_DIALOG);
		myChooser.setDialogTitle("Save Text File");
		String[] ext=new String[] {"txt"};
		myChooser.addChoosableFileFilter(new ExampleFileFilter(ext, "Text Files"));
		int fp, lp;
		if (myChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
		{
			// see if file already exists
			if (myChooser.getSelectedFile().exists())
			{
				int response;
				response = JOptionPane.showConfirmDialog(null, myChooser.getSelectedFile().toString() + " already exists.\nDo you want to replace it?", "Confirm Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, questionIcon);
				if (response == JOptionPane.NO_OPTION)
				{
					return;
				}
			}
			// make sure file has txt extension
			// strip off any extension that might be there
			// then tack on txt
			String fileName = myChooser.getSelectedFile().toString();
			int dotlocation = fileName.indexOf(".");
			if (dotlocation == -1)
			{
				// no extension
				fileName += ".txt";
			}
			else
			{
				// make sure extension is txt
				fileName = fileName.substring(0, dotlocation)+".txt";
			}
			try
			{
				// open output file and write
				PrintWriter outputFile = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
				for (int i = 0; i < editorTextArea.getLineCount(); i++)
				{
					fp=editorTextArea.getLineStartOffset(i);
					lp=editorTextArea.getLineEndOffset(i);
					
					outputFile.print(editorTextArea.getText().substring(fp, lp));
				}
				outputFile.flush();
				outputFile.close();
			}
			catch (BadLocationException ex)
			{
			}
			catch (IOException ex)
			{
				JOptionPane.showConfirmDialog(null, ex.getMessage(), "Error Writing File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, errorIcon);
			}
		}
	}
	
	private void exitMenuItemActionPerformed(ActionEvent e)
	{
		exitForm(null);
	}
	
	private void formatMenuItemActionPerformed(ActionEvent e)
	{
		// put together font based on menu selections
		int newFont = Font.PLAIN;
		int fontSize = 12;
		if (boldMenuItem.isSelected())
		{
			newFont += Font.BOLD;
		}
		if (italicMenuItem.isSelected())
		{
			newFont += Font.ITALIC;
		}
		if (smallMenuItem.isSelected())
		{
			fontSize = 12;
		}
		else if (mediumMenuItem.isSelected())
		{
			fontSize = 18;
		}
		else
		{
			fontSize = 24;
		}
		editorTextArea.setFont(new Font("Arial", newFont, fontSize));
	}
	
	private void aboutMenuItemActionPerformed(ActionEvent e)
	{
		JOptionPane.showConfirmDialog(null, "About Note Editor\nCopyright 2010", "Note Editor", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, infoIcon);
	}
	
	private void exitForm(WindowEvent e)
	{
		int response;
		response = JOptionPane.showConfirmDialog(null, "Do you want to save file before closing?", "Note Editor", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, warningIcon);
		if (response == JOptionPane.CANCEL_OPTION)
		{
			return;
		}
		else if (response == JOptionPane.YES_OPTION)
		{
			saveMenuItemActionPerformed(null);
		}
		try
		{
        // open configuration file and write
	    PrintWriter outputFile = new PrintWriter(new BufferedWriter(new FileWriter("note.ini")));
	    outputFile.println(boldMenuItem.isSelected());
	    outputFile.println(italicMenuItem.isSelected());
		if (smallMenuItem.isSelected())
		{
			outputFile.println("1");
		}
		else if (mediumMenuItem.isSelected())
		{
			outputFile.println("2");
		}
		else if (largeMenuItem.isSelected())
		{
			outputFile.println("3");
		}
		outputFile.flush();
		outputFile.close();
		}
		catch (IOException ex)
		{
			JOptionPane.showConfirmDialog(null, ex.getMessage(), "Error Writing Configuration File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, errorIcon);
		}
		finally
		{
			System.exit(0);
		}
	}
	
	private void windowStateChanged(WindowEvent e)
	{
		editorPane.setPreferredSize(new Dimension(getWidth(), getHeight()));
	}
}
I have a separate problem than asked above. If someone clicks on the Exit button in the File menu then everything works fine but if you click on the 'x' in the upper-right corner of the window then when running the exitForm method If you press "Cancel" (response==JOptionPane.CANCEL_OPTION) it does "return;" so it leaves the method BUT I already pressed 'x' which closes the window so now my window is closed but it's supposed to be open and the program is still running I have to use the "Stop Tool" that's what the whole method was originally created for, the "System.exit(0);" (which is now purposely being skipped). Basically, I want resizable(true) and when the person resizes the window by any means the editorPane along with the editorTextArea should be the same size as the window so the window will always be one big text area (besides for the JMenu at the top of the screen).
danpost danpost

2017/1/4

#
Nosson1459 wrote...
I think you misunderstood me because the code you suggested gave me an error while my code didn't give me an error but it still didn't work (I have a feeling the problem lies somewhere else in my code).
I had tested it out and I know that it works as I suggested. Where did you "learn" to create a method within the statement that adds a listener? I would like to see that documentation.
danpost danpost

2017/1/4

#
Try it again. First, change line 10 to this:
public class NoteEditor extends JFrame implements WindowStateListener
then, replace lines 62 through 68 with this:
addWindowStateListener(this);
resizes the window by any means
I am not sure how you are going to detect that. The listener does not look for size changes -- just major changes where either Maximized or Iconified are involved as the starting or ending state of the change.
danpost danpost

2017/1/4

#
Nosson1459 wrote...
If someone clicks on the Exit button in the File menu then everything works fine but if you click on the 'x' in the upper-right corner of the window then when running the exitForm method If you press "Cancel" (response==JOptionPane.CANCEL_OPTION) it does "return;" so it leaves the method BUT I already pressed 'x' which closes the window so now my window is closed but it's supposed to be open and the program is still running
You should be able to call 'setVisible(true)' on the frame again if 'CANCEL' is clickd on.
Nosson1459 Nosson1459

2017/1/5

#
I got the following error when trying your code: error: windowStateChanged(WindowEvent) in NoteEditor cannot implement windowStateChanged(WindowEvent) in WindowStateListener line 414 (in code above, that's not what it said by me since I changed things around)
danpost danpost

2017/1/5

#
Nosson1459 wrote...
I got the following error when trying your code: error: windowStateChanged(WindowEvent) in NoteEditor cannot implement windowStateChanged(WindowEvent) in WindowStateListener line 414 (in code above, that's not what it said by me since I changed things around)
Please refer to this page of the java tutorials.
davmac davmac

2017/1/5

#
Nosson1459 wrote...
error: windowStateChanged(WindowEvent) in NoteEditor cannot implement windowStateChanged(WindowEvent) in WindowStateListener
I suspect this is because your windowStateChanged method is declared private. You cannot implement an interface method with a non-public method.
danpost danpost

2017/1/5

#
davmac wrote...
I suspect this is because your windowStateChanged method is declared private. You cannot implement an interface method with a non-public method.
Thanks, davmac. I was wondering why a StackOverflow was not encountered and that explains it. I totally overlooked the 'private' access modifier given to that method.
Nosson1459 Nosson1459

2017/1/6

#
davmac wrote...
I suspect this is because your windowStateChanged method is declared private. You cannot implement an interface method with a non-public method.
Now there is no syntax errors, BUT the reason for this discussion (and a side question) is still not resolved).
danpost wrote...
Nosson1459 wrote...
If someone clicks on the Exit button in the File menu then everything works fine but if you click on the 'x' in the upper-right corner of the window then when running the exitForm method If you press "Cancel" (response==JOptionPane.CANCEL_OPTION) it does "return;" so it leaves the method BUT I already pressed 'x' which closes the window so now my window is closed but it's supposed to be open and the program is still running
You should be able to call 'setVisible(true)' on the frame again if 'CANCEL' is clickd on.
Where in my code should I put the "setVisible(true);"? I tried right before line 377 and right after line 335 but the window still disappeared.
Nosson1459 wrote...
Basically, I want resizable(true) and when the person resizes the window by any means the editorPane along with the editorTextArea should be the same size as the window so the window will always be one big text area (besides for the JMenu at the top of the screen).
danpost wrote...
resizes the window by any means
I am not sure how you are going to detect that. The listener does not look for size changes -- just major changes where either Maximized or Iconified are involved as the starting or ending state of the change.
Above are questions that are still not answered (the main question is the latter). As a side point, even though I don't have Syntax errors now I still have the problem that the size of my editorPane/editorTextArea isn't keeping the size of my window (when I press maximize/minimize).
danpost danpost

2017/1/6

#
Nosson1459 wrote...
If you press "Cancel" (response==JOptionPane.CANCEL_OPTION) it does "return;" so it leaves the method BUT I already pressed 'x' which closes the window so now my window is closed but it's supposed to be open and the program is still running
In the block that executes when (response==JOptionPane.CANCEL_OPTION). Oh, I see you tried there with no luck.
Nosson1459 Nosson1459

2017/1/6

#
danpost wrote...
Oh, I see you tried there with no luck.
So what about the answers?
davmac davmac

2017/1/6

#
A web search turned up something helpful: During initialisation, set the default close operation to "do nothing":
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
(On line 12 for example).
You need to login to post a reply.