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

2017/2/7

GridBagConstraints.BOTH

Nosson1459 Nosson1459

2017/2/7

#
Why doesn't the editorPane resize when it has extra room to, it should according to the Java API. If I'm doing something wrong then tell me how to fix it, if I can't use this for what I want (have a frame that is re-sizable but the editor pane keeps the same size as the frame) then what can I do to make this work? (The line in question is line 207) Here is my coding:
/*
 * 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();
	
	public static void main(String args[])
	{
		try
		{
            // Set System L&F
        	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    	} 
  	    catch (UnsupportedLookAndFeelException e)
  	   	{
  	   		// handle exception
  	    }
  	    catch (ClassNotFoundException e)
    	{
    		// handle exception
        }
    	catch (InstantiationException e)
    	{
       		// handle exception
       	}
    	catch (IllegalAccessException e)
    	{
       		// handle exception
    	}
    	
		// construct frame
		new NoteEditor().show();
	}
	
	public NoteEditor()
	{
		// frame constructor
		setTitle("Note Editor");
		setIconImage(new ImageIcon("notepad.gif").getImage());
		setResizable(true);
		addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				exitForm(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('T', 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;
		gridConstraints.fill = GridBagConstraints.BOTH;
		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);
			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)==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);
			}
		}
	}
	
	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);
				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);
			}
		}
	}
	
	private void exitMenuItemActionPerformed(ActionEvent e)
	{
		exitForm(null);
		setVisible(true);
	}
	
	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);
	}
	
	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);
		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);
		}
		finally
		{
			System.exit(0);
		}
	}
}
danpost danpost

2017/2/7

#
You may need to give 'weightx' or 'weighty' a value (just a guess after looking at the 'GridBagConstraints' and 'GridBagLayout' classes briefly). Another possibility is that line 200 is limiting the expansion of the pane (try using larger values for the preferred dimensions).
Nosson1459 Nosson1459

2017/2/8

#
danpost wrote...
You may need to give 'weightx' or 'weighty' a value (just a guess after looking at the 'GridBagConstraints' and 'GridBagLayout' classes briefly). Another possibility is that line 200 is limiting the expansion of the pane (try using larger values for the preferred dimensions).
That doesn't help me because I want the user to be able to change the size of the frame and the editorPane will change along with it. I think the way the fill works with GridBagConstraints.BOTH is that it fills the extra space it has when the program is started but if I change the size in middle nothing will or did happen.
Nosson1459 Nosson1459

2017/2/9

#
What is the difference between the following (in the way they act, and they way they get used):
public void setSize(int width,
                    int height)
Resizes this component so that it has width width and height height. This method changes layout-related information, and therefore, invalidates the component hierarchy. Parameters: width - the new width of this component in pixels height - the new height of this component in pixels
public void setSize(Dimension d)
Resizes this component so that it has width d.width and height d.height. This method changes layout-related information, and therefore, invalidates the component hierarchy. Parameters: d - the dimension specifying the new size of this component Throws: NullPointerException - if d is null
public void setPreferredSize(Dimension preferredSize)
Sets the preferred size of this component. If preferredSize is null, the UI will be asked for the preferred size. Overrides: setPreferredSize in class Component Parameters: preferredSize - The new preferred size, or null
MrBradley MrBradley

2017/2/9

#
Dimension is just a wrapper on width and height. Only difference is handling a null reference for a Dimension object.
Nosson1459 Nosson1459

2017/2/9

#
I still don't know the answer to my question even though you answered it. What's the difference if I use '(new Dimension(width, height))' or just plane'(width, height)'? Now, what's the difference between doing: 'setSize(Dimension d)' and 'setPreferredSize(Dimension preferredSize)'? There are three separate methods, and I want to know why each one is different from the other two (still the same question).
danpost danpost

2017/2/9

#
The is no difference in the implementation of 'setSize(new Dimension(width, height))' and 'setSize(width, height)'. They are just two ways to set the size of the component. However, because Dimension is an Object type, its value could be passed as 'null', which will produce a NullPointerException, as MrBradley mentioned. The 'setPreferedSize(Dimension)' method has a different implementation. If possible, the dimensions given to it will be used for the size of the component; however, the component may not end up that size when the frame is packed. Using that method is like saying you would like the dimensions to be such and such, but, they do not necessarily have to be (there is some degree of latitude given to the dimensions given). When using 'setSize', the dimensions are absolute.
Nosson1459 Nosson1459

2017/2/9

#
danpost wrote...
The is no difference in the implementation of 'setSize(new Dimension(width, height))' and 'setSize(width, height)'. They are just two ways to set the size of the component. However, because Dimension is an Object type, its value could be passed as 'null', which will produce a NullPointerException, as MrBradley mentioned.
So how does getting a NullPointerException help anybody? The method was created by Java just so that I can have fun getting NullPointerExceptions?
The 'setPreferedSize(Dimension)' method has a different implementation. If possible, the dimensions given to it will be used for the size of the component; however, the component may not end up that size when the frame is packed. Using that method is like saying you would like the dimensions to be such and such, but, they do not necessarily have to be (there is some degree of latitude given to the dimensions given). When using 'setSize', the dimensions are absolute.
What do you mean "would like the dimensions to be such and such, but, they do not necessarily have to be"? I guess those dimensions are preferred, but when is it decided to not use the preferred dimensions that I put in?
Nosson1459 wrote...
I want the user to be able to change the size of the frame and the editorPane will change along with it.
...and work all the same way just in a different size.
danpost danpost

2017/2/9

#
Nosson1459 wrote...
So how does getting a NullPointerException help anybody? The method was created by Java just so that I can have fun getting NullPointerExceptions?
I think you know that is not the point. It allows you, if you had a Dimension object, to use it instead of extracting the values from it to set the size of a component. I suspect that the implementation of other methods within the 'awt' package utilize the 'setSize(Dimension)' method as well (like in 'pack' when there is a preferred size given by a Dimension object).
when is it decided to not use the preferred dimensions that I put in?
I think it might have something to do with reducing the amount of unused space within the frame (just guessing).
I want the user to be able to change the size of the frame and the editorPane will change along with it ... and work all the same way just in a different size.
You may have to re-pack the frame anytime its size is altered (another guess).
You need to login to post a reply.