JScrollPane not working as intended, why? - java

Edit the action listener by adding 6 more branches to the else-if logic. Each
branch will compare the actionCommand to the 6 submenu items: Metal, Motif,
Window, Never, Always, and As Needed.
a. Each Look and Feel submenu item will use a try-catch statement to set
the look and feel to the appropriate one, displaying an error message if this
was not accomplished.
b. Each Scroll Bars submenu item will set the horizontal and vertical scroll
bar policy to the appropriate values.
c. Any components that have already been created need to be updated. This
can be accomplished by calling the SwingUtilities.updateComponentTreeUI method, passing a reference to the component that you want to update as an argument. Specifically you will need to add the line
SwingUtilities.updateComponentTreeUIgetContentPane());
to each branch that you just added to the logic structure.
My code is this..and it is crashing and I am completely stuck on why. Any help is appreciated.
package src.javaapplication5;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NoteTaker extends JFrame {
//constants for set up of note taking area
public static final int WIDTH = 600;
public static final int HEIGHT = 300;
public static final int LINES = 13;
public static final int CHAR_PER_LINE = 45;
//objects in GUI
private JTextArea theText; //area to take notes
private JMenuBar mBar; //horizontal menu bar
private JPanel textPanel; //panel to hold scrolling text area
private JMenu notesMenu; //vertical menu with choices for notes
//****THESE ITEMS ARE NOT YET USED. YOU WILL BE CREATING THEM IN THIS LAB
private JMenu viewMenu; //vertical menu with choices for views
private JMenu lafMenu; //vertical menu with look and feel
private JMenu sbMenu; //vertical menu with scroll bar option
private JScrollPane scrolledText; //scroll bars
//default notes
private String note1 = "No Note 1.";
private String note2 = "No Note 2.";
/**
* constructor
*/
public NoteTaker() {
//create a closeable JFrame with a specific size
super("Note Taker");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//get contentPane and set layout of the window
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//creates the vertical menus
createNotes();
createViews();
//creates horizontal menu bar and
//adds vertical menus to it
mBar = new JMenuBar();
mBar.add(notesMenu);
mBar.add(viewMenu);
//****ADD THE viewMenu TO THE MENU BAR HERE
setJMenuBar(mBar);
//creates a panel to take notes on
textPanel = new JPanel();
textPanel.setBackground(Color.blue);
JTextArea theText = new JTextArea(LINES, CHAR_PER_LINE);
theText.setBackground(Color.white);
JScrollPane scrolledText = new JScrollPane(theText);
//****CREATE A JScrollPane OBJECT HERE CALLED scrolledText
//****AND PASS IN theText, THEN
//****CHANGE THE LINE BELOW BY PASSING IN scrolledText
textPanel.add(scrolledText);
contentPane.add(textPanel, BorderLayout.CENTER);
}
/**
* creates vertical menu associated with Notes menu item on menu bar
*/
public void createNotes() {
notesMenu = new JMenu("Notes");
JMenuItem item;
item = new JMenuItem("Save Note 1");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Save Note 2");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Open Note 1");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Open Note 2");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Clear");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Exit");
item.addActionListener(new MenuListener());
notesMenu.add(item);
}
/**
* creates vertical menu associated with Views menu item on the menu bar
*/
public void createViews() {
viewMenu = new JMenu("Views");
viewMenu.setMnemonic(KeyEvent.VK_V);
createLookAndFeel();
createScrollBars();
lafMenu.addActionListener(new MenuListener());
sbMenu.addActionListener(new MenuListener());
viewMenu.add(lafMenu);
viewMenu.add(sbMenu);
}
/**
* creates the look and feel submenu
*/
public void createLookAndFeel() {
lafMenu = new JMenu("Look and Feel");
lafMenu.setMnemonic(KeyEvent.VK_L);
JMenuItem metalItem;
JMenuItem motifItem;
JMenuItem windowsItem;
metalItem = new JMenuItem("Metal");
metalItem.addActionListener(new MenuListener());
motifItem = new JMenuItem("Motif");
motifItem.addActionListener(new MenuListener());
windowsItem = new JMenuItem("Windows");
windowsItem.addActionListener(new MenuListener());
lafMenu.add(metalItem);
lafMenu.add(motifItem);
lafMenu.add(windowsItem);
}
/**
* creates the scroll bars submenu
*/
public void createScrollBars() {
sbMenu = new JMenu("Scroll Bars");
sbMenu.setMnemonic(KeyEvent.VK_S);
JMenuItem neverItem;
JMenuItem alwaysItem;
JMenuItem asneededItem;
neverItem = new JMenuItem("Never");
neverItem.addActionListener(new MenuListener());
alwaysItem = new JMenuItem("Always");
alwaysItem.addActionListener(new MenuListener());
asneededItem = new JMenuItem("As Needed");
asneededItem.addActionListener(new MenuListener());
sbMenu.add(neverItem);
sbMenu.add(alwaysItem);
sbMenu.add(asneededItem);
}
private class MenuListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Save Note 1")) {
note1 = theText.getText();
} else if (actionCommand.equals("Save Note 2")) {
note2 = theText.getText();
} else if (actionCommand.equals("Clear")) {
theText.setText("");
} else if (actionCommand.equals("Open Note 1")) {
theText.setText(note1);
} else if (actionCommand.equals("Open Note 2")) {
theText.setText(note2);
} else if (actionCommand.equals("Exit")) {
System.exit(0);
} else if (actionCommand.equals("Metal")) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
SwingUtilities.updateComponentTreeUI(getContentPane());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Motif")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI(getContentPane());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Windows")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(getContentPane());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Never")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
} else if (actionCommand.equals("Always")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
} else if (actionCommand.equals("As Needed")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
} //****ADD 6 BRANCHES TO THE ELSE-IF STRUCTURE
//****TO ALLOW ACTION TO BE PERFORMED FOR EACH
//****MENU ITEM YOU HAVE CREATED
else {
theText.setText("Error in memo interface");
}
}
}
public static void main(String[] args) {
NoteTaker gui = new NoteTaker();
gui.setVisible(true);
}
}

lots of issues, please to compare your code with
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class NoteTaker {
//constants for set up of note taking area
public static final int WIDTH = 600;
public static final int HEIGHT = 300;
public static final int LINES = 13;
public static final int CHAR_PER_LINE = 45;
//
private JFrame frame = new JFrame("Note Taker");
//objects in GUI
private JTextArea theText; //area to take notes
private JMenuBar mBar; //horizontal menu bar
private JPanel textPanel; //panel to hold scrolling text area
private JMenu notesMenu; //vertical menu with choices for notes
//****THESE ITEMS ARE NOT YET USED. YOU WILL BE CREATING THEM IN THIS LAB
private JMenu viewMenu; //vertical menu with choices for views
private JMenu lafMenu; //vertical menu with look and feel
private JMenu sbMenu; //vertical menu with scroll bar option
private JScrollPane scrolledText; //scroll bars
//default notes
private String note1 = "No Note 1.";
private String note2 = "No Note 2.";
/**
* constructor
*/
public NoteTaker() {
//create a closeable JFrame with a specific size
//setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//get contentPane and set layout of the window
//Container contentPane = frame;
//contentPane.setLayout(new BorderLayout());
//creates the vertical menus
createNotes();
createViews();
//creates horizontal menu bar and
//adds vertical menus to it
mBar = new JMenuBar();
mBar.add(notesMenu);
mBar.add(viewMenu);
//****ADD THE viewMenu TO THE MENU BAR HERE
frame.setJMenuBar(mBar);
//creates a panel to take notes on
textPanel = new JPanel(new BorderLayout());
textPanel.setBackground(Color.blue);
textPanel.setBorder(new EmptyBorder(5,5,5,5));
/*JTextArea*/ theText = new JTextArea(LINES, CHAR_PER_LINE);
theText.setBackground(Color.white);
/*JScrollPane*/ scrolledText = new JScrollPane(theText);
//****CREATE A JScrollPane OBJECT HERE CALLED scrolledText
//****AND PASS IN theText, THEN
//****CHANGE THE LINE BELOW BY PASSING IN scrolledText
textPanel.add(scrolledText);
frame.add(textPanel/*, BorderLayout.CENTER*/);
frame.pack();
frame.setVisible(true);
}
/**
* creates vertical menu associated with Notes menu item on menu bar
*/
public void createNotes() {
notesMenu = new JMenu("Notes");
JMenuItem item;
item = new JMenuItem("Save Note 1");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Save Note 2");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Open Note 1");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Open Note 2");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Clear");
item.addActionListener(new MenuListener());
notesMenu.add(item);
item = new JMenuItem("Exit");
item.addActionListener(new MenuListener());
notesMenu.add(item);
}
/**
* creates vertical menu associated with Views menu item on the menu bar
*/
public void createViews() {
viewMenu = new JMenu("Views");
viewMenu.setMnemonic(KeyEvent.VK_V);
createLookAndFeel();
createScrollBars();
lafMenu.addActionListener(new MenuListener());
sbMenu.addActionListener(new MenuListener());
viewMenu.add(lafMenu);
viewMenu.add(sbMenu);
}
/**
* creates the look and feel submenu
*/
public void createLookAndFeel() {
lafMenu = new JMenu("Look and Feel");
lafMenu.setMnemonic(KeyEvent.VK_L);
JMenuItem metalItem;
JMenuItem motifItem;
JMenuItem windowsItem;
metalItem = new JMenuItem("Metal");
metalItem.addActionListener(new MenuListener());
motifItem = new JMenuItem("Motif");
motifItem.addActionListener(new MenuListener());
windowsItem = new JMenuItem("Windows");
windowsItem.addActionListener(new MenuListener());
lafMenu.add(metalItem);
lafMenu.add(motifItem);
lafMenu.add(windowsItem);
}
/**
* creates the scroll bars submenu
*/
public void createScrollBars() {
sbMenu = new JMenu("Scroll Bars");
sbMenu.setMnemonic(KeyEvent.VK_S);
JMenuItem neverItem;
JMenuItem alwaysItem;
JMenuItem asneededItem;
neverItem = new JMenuItem("Never");
neverItem.addActionListener(new MenuListener());
alwaysItem = new JMenuItem("Always");
alwaysItem.addActionListener(new MenuListener());
asneededItem = new JMenuItem("As Needed");
asneededItem.addActionListener(new MenuListener());
sbMenu.add(neverItem);
sbMenu.add(alwaysItem);
sbMenu.add(asneededItem);
}
private class MenuListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Save Note 1")) {
note1 = theText.getText();
} else if (actionCommand.equals("Save Note 2")) {
note2 = theText.getText();
} else if (actionCommand.equals("Clear")) {
theText.setText("");
} else if (actionCommand.equals("Open Note 1")) {
theText.setText(note1);
} else if (actionCommand.equals("Open Note 2")) {
theText.setText(note2);
} else if (actionCommand.equals("Exit")) {
System.exit(0);
} else if (actionCommand.equals("Metal")) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Motif")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Windows")) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error setting "
+ "the look and feel");
System.exit(0);
}
} else if (actionCommand.equals("Never")) {
//SwingUtilities.updateComponentTreeUI(frame);
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
//SwingUtilities.updateComponentTreeUI(frame);
} else if (actionCommand.equals("Always")) {
//SwingUtilities.updateComponentTreeUI(frame);
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//SwingUtilities.updateComponentTreeUI(frame);
} else if (actionCommand.equals("As Needed")) {
//SwingUtilities.updateComponentTreeUI(frame);
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
//SwingUtilities.updateComponentTreeUI(frame);
} //****ADD 6 BRANCHES TO THE ELSE-IF STRUCTURE
//****TO ALLOW ACTION TO BE PERFORMED FOR EACH
//****MENU ITEM YOU HAVE CREATED
else {
theText.setText("Error in memo interface");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NoteTaker gui = new NoteTaker();
}
});
}
}

You are getting an exception because scrollText is null.
When creating scrollText, it is created as a local variable in the constructor.
JScrollPane scrolledText = new JScrollPane(theText);
It is also declared as a field, but since it is also declared as a local variable in the constructor, the field is never initialized.
Instead, just do:
scrolledText = new JScrollPane(theText);

Your code:
else if (actionCommand.equals("Never")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
} else if (actionCommand.equals("Always")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
} else if (actionCommand.equals("As Needed")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
}
My code :
else if (actionCommand.equals("Never")) {
scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
SwingUtilities.updateComponentTreeUI(getContentPane());
}
else if (actionCommand.equals("Always")) {
scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
SwingUtilities.updateComponentTreeUI(getContentPane());
}
else if (actionCommand.equals("As Needed")) {
scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
SwingUtilities.updateComponentTreeUI(getContentPane());
}

Related

Java - Select all item in the menu

I'm using the javax.swing library, and I try to solve this problem:
I have a MenuBar in which I created JMenu, this menu has JCheckBoxMenuItem items. Like this:
//creating objects:
jMenuBar = new javax.swing.JMenuBar();
jMenuAlgorithms = new javax.swing.JMenu();
jCheckBoxSPEA = new javax.swing.JCheckBoxMenuItem();
jCheckBoxNSGAII = new javax.swing.JCheckBoxMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jCheckBoxMenuEnableAll = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuDisableAll = new javax.swing.JCheckBoxMenuItem();
//settings and putting them together:
jCheckBoxSPEA.setSelected(true);
jCheckBoxSPEA.setText("SPEA");
jMenuAlgorithms.add(jCheckBoxSPEA);
jCheckBoxNSGAII.setSelected(true);
jCheckBoxNSGAII.setText("NSGAII");
jMenuAlgorithms.add(jCheckBoxNSGAII);
jMenuAlgorithms.add(jSeparator1);
jCheckBoxMenuEnableAll.setSelected(true);
jCheckBoxMenuEnableAll.setText("Enable all");
jCheckBoxMenuEnableAll.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jCheckBoxMenuEnableAllMouseClicked(evt);
}
});
jMenuAlgorithms.add(jCheckBoxMenuEnableAll);
jCheckBoxMenuDisableAll.setText("Disable all");
jMenuAlgorithms.add(jCheckBoxMenuDisableAll);
jMenuBar.add(jMenuAlgorithms);
If the user selects jCheckBoxMenuEnableAll item, I would like to select all the items above the separator. If he selects jCheckBoxMenuDisableAll, I would like to deselect all the items above the separator.
As you can see, I've added mouseClicked action to the jCheckBoxMenuEnableAll item. Now, I would like to do something like this:
private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {
for(JCheckBoxMenuItem item : jMenuAlgorithms){
item.setSelected(true);
}
//deselect then jCheckBoxMenuDisableAll, it's not essential for instance
}
But apparently, I can't do the for loop like this, as the menu item isn't an array or Iterable.
Well, just for testing, I had done something very stupid (code below) - I pass all the items in the menu, and if the item is a check box, I make its copy, set ist value to "true" (selected) and then replace the original item by its copy. Very stupid, I know and I absolutely don't want to do like this, however, I didn't find another way to do it. I just wanted to see if this would work. I supposed it should, but it stoll doesn't work. What am I doing wrong? Thank you very, very much for your time.
private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {
if(jCheckBoxMenuEnableAll.isSelected()){
for(int i =0; i< jMenuAlgorithms.getItemCount(); i++){ //for all items in the menu, separators included
if(jMenuAlgorithms.getItem(i) instanceof JCheckBoxMenuItem){
JCheckBoxMenuItem item = ((JCheckBoxMenuItem)jMenuAlgorithms.getItem(i));
item.setSelected(true);
jMenuAlgorithms.insert(item, i);
}
}
}
}
I think JPopupMenu#getSubElements() is what you are looking for.
see also: JMenu#getSubElements()
Returns an array of MenuElements containing the submenu for this menu
component. If popup menu is null returns an empty array. This method
is required to conform to the MenuElement interface. Note that since
JSeparators do not conform to the MenuElement interface, this array
will only contain JMenuItems.
import java.awt.*;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.swing.*;
public class MenuSubElementsTest {
public JComponent makeUI() {
JMenu jMenuAlgorithms = new JMenu("MenuAlgorithms");
JMenuItem jCheckBoxMenuEnableAll = new JMenuItem("Enable all");
jCheckBoxMenuEnableAll.addActionListener(e -> {
for (MenuElement me: jMenuAlgorithms.getPopupMenu().getSubElements()) {
System.out.println("debug1: " + me.getClass().getName());
if (me instanceof JCheckBoxMenuItem) {
((JCheckBoxMenuItem) me).setSelected(true);
}
}
//or: getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(true));
});
JMenuItem jCheckBoxMenuDisableAll = new JMenuItem("Disable all");
jCheckBoxMenuDisableAll.addActionListener(e -> {
getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(false));
});
jMenuAlgorithms.add(new JCheckBoxMenuItem("SPEA", true));
jMenuAlgorithms.add(new JCheckBoxMenuItem("NSGAII", true));
jMenuAlgorithms.addSeparator();
jMenuAlgorithms.add(jCheckBoxMenuEnableAll);
jMenuAlgorithms.add(jCheckBoxMenuDisableAll);
JMenuBar jMenuBar = new JMenuBar();
jMenuBar.add(jMenuAlgorithms);
JPanel p = new JPanel(new BorderLayout());
p.add(jMenuBar, BorderLayout.NORTH);
return p;
}
private static Stream<JCheckBoxMenuItem> getJCheckBoxMenuItem(MenuElement p) {
Class<JCheckBoxMenuItem> clz = JCheckBoxMenuItem.class;
return stream(p).filter(clz::isInstance).map(clz::cast);
}
// public static Stream<MenuElement> stream(MenuElement p) {
// return Arrays.stream(p.getSubElements())
// .map(MenuSubElementsTest::stream).reduce(Stream.of(p), Stream::concat);
// }
public static Stream<MenuElement> stream(MenuElement p) {
return Stream.concat(Stream.of(p), Arrays.stream(p.getSubElements())
.peek(me -> System.out.println("debug2: " + me.getClass().getName()))
.flatMap(MenuSubElementsTest::stream));
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new MenuSubElementsTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

How to create a new panel with radio buttons depending on menu item selected

I am trying to create a gui that when I select an item from the menuBar it creates a sort of form with radio buttons in the empty field below. I want the items in that field to change depending on what option is selected. How can I do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
/**
*
* #author Fireurza
*/
public class RSSGUIMenuBar extends JFrame implements MenuListener, KeyListener, ActionListener
{
JMenuBar menuBar;
JMenu shop, partOption, modelOption, orderOption, customerOption, employeeOption, reportOption, exit;
JMenuItem searchParts, browseParts, editParts, newParts;
JMenuItem searchModels, browseModels, editModels, newModels;
JMenuItem searchOrders, browseOrders, editOrders, newOrders;
JMenuItem searchCustomers, browseCustomers, editCustomer, newCustomer;
JMenuItem searchEmployees, browseEmployees, editEmployee, newEmployee;
JMenuItem openReport, searchReport;
public static void main(String[] args)
{
RSSGUIMenuBar fr = new RSSGUIMenuBar();
fr.setVisible(true);
}
public RSSGUIMenuBar()
{
setLayout(new FlowLayout());
setSize(900,700);
setTitle("Robbie Robot Shop");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// listens when key pressed
this.addKeyListener(this);
// Create menu bar
menuBar = new JMenuBar();
//build the first heading on menu bar
shop = new JMenu("Shop");
// shop.addMenuListener(new thisMenuListener());
menuBar.add(shop);
// creat exit menu item
exit = new JMenu("Exit");
exit.setMnemonic(KeyEvent.VK_X);
exit.addMenuListener(this);
menuBar.add(exit);
//sub menu partOption
partOption = new JMenu("Parts");
//partOption.addMenuListener(new thisMenuListener());
shop.add(partOption);
// sub menus of Parts
searchParts = new JMenuItem("Search Parts");
browseParts = new JMenuItem("Browse Parts");
editParts = new JMenuItem("Edit Part");
newParts = new JMenuItem("New Part");
//new JMenuItem("SearchParts", new ImageIcon("images/image.gif));
searchParts.addActionListener(this);
browseParts.addActionListener(this);
editParts.addActionListener(this);
newParts.addActionListener(this);
partOption.add(searchParts);
partOption.add(browseParts);
partOption.add(editParts);
partOption.add(newParts);
// sub menu modelOption
modelOption = new JMenu("Models");
// modelOption.addMenuListener(new thisMenuListener());
shop.add(modelOption);
// sub menus of Models
searchModels = new JMenuItem("Search Models");
browseModels = new JMenuItem("Browse Models");
editModels = new JMenuItem("Edit Model");
newModels = new JMenuItem("New Model");
//new JMenuItem("SearchModels", new ImageIcon("images/image.gif));
searchModels.addActionListener(this);
browseModels.addActionListener(this);
editModels.addActionListener(this);
newModels.addActionListener(this);
modelOption.add(searchModels);
modelOption.add(browseModels);
modelOption.add(editModels);
modelOption.add(newModels);
// sub menu orderOption
orderOption = new JMenu("Orders");
// orderOption.addMenuListener(new thisMenuListener());
shop.add(orderOption);
// sub menus of Orders
searchOrders = new JMenuItem("Search Orders");
browseOrders = new JMenuItem("Browse Orders");
editOrders = new JMenuItem("Edit Order");
newOrders = new JMenuItem("New Order");
//new JMenuItem("Search Orders", new ImageIcon("images/image.gif));
searchOrders.addActionListener(this);
browseOrders.addActionListener(this);
editOrders.addActionListener(this);
newOrders.addActionListener(this);
orderOption.add(searchOrders);
orderOption.add(browseOrders);
orderOption.add(editOrders);
orderOption.add(newOrders);
//sub menu customerOption
customerOption = new JMenu("Customers");
// customerOption.addMenuListener(new thisMenuListener());
shop.add(customerOption);
// sub menus of Customers
searchCustomers = new JMenuItem("Search Customers");
browseCustomers = new JMenuItem("Browse Customers");
editCustomer = new JMenuItem("Edit Customer");
newCustomer = new JMenuItem("New Customer");
//new JMenuItem("Search Customers", new ImageIcon("images/image.gif));
searchCustomers.addActionListener(this);
browseCustomers.addActionListener(this);
editCustomer.addActionListener(this);
newCustomer.addActionListener(this);
customerOption.add(searchCustomers);
customerOption.add(browseCustomers);
customerOption.add(editCustomer);
customerOption.add(newCustomer);
// sub menu employeeOption
employeeOption = new JMenu("Employees");
// employeeOption.addMenuListener(new thisMenuListener());
shop.add(employeeOption);
// sub menus of Employees
searchEmployees = new JMenuItem("Search Employees");
browseEmployees = new JMenuItem("Browse Employees");
editEmployee = new JMenuItem("Edit Employee");
newEmployee = new JMenuItem("New Employee");
//new JMenuItem("Search Employees", new ImageIcon("images/image.gif));
searchEmployees.addActionListener(this);
browseEmployees.addActionListener(this);
editEmployee.addActionListener(this);
newEmployee.addActionListener(this);
employeeOption.add(searchEmployees);
employeeOption.add(browseEmployees);
employeeOption.add(editEmployee);
employeeOption.add(newEmployee);
// sub menu reportOption
reportOption = new JMenu("Reports");
// reportOption.addMenuListener(new thisMenuListener());
shop.add(reportOption);
// sub menus of Reports
searchReport = new JMenuItem("Search Reports");
openReport = new JMenuItem("Open Report");
//new JMenuItem("Search Reports", new ImageIcon("images/image.gif));
searchReport.addActionListener(this);
openReport.addActionListener(this);
reportOption.add(searchReport);
reportOption.add(openReport);
// add menu bar to frame
this.setJMenuBar(menuBar);
}
// needed for implements
#Override
public void menuSelected(MenuEvent me)
{
if (me.getSource().equals(exit))
{
System.exit(0);
}
}
#Override
public void menuDeselected(MenuEvent me)
{
//not used but must exist
}
#Override
public void menuCanceled(MenuEvent me)
{
//not used but must exist
}
#Override
public void keyTyped(KeyEvent ke)
{
//not used but must exist
}
#Override
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyChar() == 'x')
{
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent ke)
{
//not used but must exist
}
// These are the action listeners
public void actionPerformed(ActionEvent e)
{
// search parts
if(e.getSource().equals(searchParts))
{
}
// browse parts
if(e.getSource().equals(browseParts))
{
}
// edit parts
if(e.getSource().equals(editParts))
{
}
// new parts
if(e.getSource().equals(newParts))
{
}
// search model
if(e.getSource().equals(searchModels))
{
}
// browse model
if(e.getSource().equals(browseModels))
{
}
// edit model
if(e.getSource().equals(editModels))
{
}
// new model
if(e.getSource().equals(newModels))
{
}
// search order
if(e.getSource().equals(searchOrders))
{
}
// browse order
if(e.getSource().equals(browseOrders))
{
}
// edit order
if(e.getSource().equals(editOrders))
{
}
// new order
if(e.getSource().equals(newOrders))
{
}
// search customer
if(e.getSource().equals(searchCustomers))
{
}
// browse customer
if(e.getSource().equals(browseCustomers))
{
}
// edit customer
if(e.getSource().equals(editCustomer))
{
}
// new customer
if(e.getSource().equals(newCustomer))
{
}
// search employee
if(e.getSource().equals(searchEmployees))
{
}
// browse employee
if(e.getSource().equals(browseEmployees))
{
}
// edit employee
if(e.getSource().equals(editEmployee))
{
}
// new employee
if(e.getSource().equals(newEmployee))
{
}
// open report
if(e.getSource().equals(openReport))
{
}
// search report
if(e.getSource().equals(searchReport))
{
}
}
}

JFrame Action Listener that listens to all menu items?

So I have a JFrame set up with a menu with the current structure that looks something along the lines of this:
File
Exit
Pages
Reviews
A
B
C
Help
About
I want to create a Action Listener that only listens to menu items under Reviews. Is this a possibility (and if so, how) or do I have to create a generic listener and check if it's one of those items?
Yes, it is possible:
Store your menu items as fields
Add the same ActionListener to each menu item.
In the listener check for the source to know which item was clicked.
Should look like:
public class YourFrame extends JFrame implements ActionListener {
private final JMenuItem menuA, menuB;
public YourFrame(){
super("Your app");
JMenuBar menuBar = new JMenuBar();
JMenu menuReviews = new JMenu("Reviews");
menuA = new JMenuItem("A");
menuB = new JMenuItem("B");
...
menuReviews.add(menuA);
menuReviews.add(menuB);
menuBar.add(menuReviews);
setJMenuBar(menuBar);
...
menuA.addActionListener(this);
menuB.addActionListener(this);
...
}
public void actionPerformed(ActionEvent event){
if(event.getSource()==menuA){
System.out.println("Menu A clicked");
...
}else if(event.getSource()==menuB){
System.out.println("Menu B clicked");
...
}
}
}
Note that here I let the JFrame implement ActionListener, but this is just for convenience. You could use a dedicated class, or an anonymous class created in the constructor:
ActionListener reviewsListener = new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getSource()==menuA){
System.out.println("Menu A clicked");
...
}else if(event.getSource()==menuB){
System.out.println("Menu B clicked");
...
}
}
};
menuA.addActionListener(reviewsListener);
menuB.addActionListener(reviewsListener);
If you want to integrate this process a little more, I could also suggest to extend JMenu, so that you can pass it your action listener and add it systematically to new menu items.
public class YourJMenu extends JMenu {
private ActionListener listener;
public YourJMenu(String name, ActionListener listener){
super(name);
this.listener = listener;
}
#Override
public JMenuItem add(JMenuItem item){
item.addActionListener(listener);
return super.add(item);
}
}
With this, you just need to write:
JMenu menuReviews = new YourJMenu("Reviews", this);
and drop the:
menuA.addActionListener(this);
menuB.addActionListener(this);
Using a common method we can add the action listener to all the menu items under a menu. Below is a example code.
public class MenuItemEvent {
JFrame objFrm = new JFrame("Menu event demo");
JMenuBar mBar;
JMenu mnu;
JMenuItem mnuItem1, mnuItem2, mnuItem3;
public void show() {
objFrm.setSize(300, 300);
mBar = new JMenuBar();
mnu = new JMenu("Reviews");
mBar.add(mnu);
mnuItem1 = new JMenuItem("A");
mnu.add(mnuItem1);
mnuItem2 = new JMenuItem("B");
mnu.add(mnuItem2);
mnuItem3 = new JMenuItem("C");
mnu.add(mnuItem3);
//method call
fnAddActionListener(mnu);
objFrm.setJMenuBar(mBar);
objFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
objFrm.setVisible(true);
}
//method to add action listener to all menu items under a menu
public void fnAddActionListener(JMenu mnu) {
if (mnu.getItemCount() != 0) {
for (int iCount = 0; iCount < mnu.getItemCount(); iCount++) {
(mnu.getItem(iCount)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fnMenuItemAction(e);
}
});
}
}
}
//menu item action event
public void fnMenuItemAction(ActionEvent e) {
if (e.getSource().equals(mnuItem1)) {
System.out.println("Menu Item 1");
} else if (e.getSource().equals(mnuItem2)) {
System.out.println("Menu Item 2");
} else if (e.getSource().equals(mnuItem3)) {
System.out.println("Menu Item 3");
}
}
public static void main(String[] args) {
new MenuItemEvent().show();
}
}
or with the below function
//fnMenuItemAdd(mnu,mnuItem1)
//etc.
public void fnMenuItemAdd(JMenu mnu, JMenuItem mni) {
mnu.add(mni);
mni.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fnMenuItemAction(e);
}
});
}

how to add a action listner to jmenuitem

My menuitem are being added thorugh database .
i have to perform action such as opening the new jframe , if a user select a particular menuitem.
Here the menu dimension is add to the Menubar , and under which various menuitem are being added such as Period , Entity, which are being fetch from database.
Now i want to open a new jframe on the click of Period menuitem .
public void MenuExp(){
JMenu DimensionMenu = new JMenu("Dimension");
JMenu editMenu = new JMenu("Help");
jMenuBar1.add(DimensionMenu);
jMenuBar1.add(editMenu);
//JMenuItem newAction = new JMenuItem("Account");
//fileMenu.add(newAction);
//JMenuItem newPeriod = new JMenuItem("Period");
//fileMenu.add(newPeriod);
try{
Class.forName("oracle.jdbc.OracleDriver");
Connection comm = (Connection)DriverManager.getConnection("jdbc:oracle:thin:#192.168.100.25:1521:orcl","SYSTEM","Admin123");
Statement st = comm.createStatement();
String Query = "select OBJECT_NAME from RAHUL_APP1.HSP_OBJECT where OBJECT_TYPE = 2 AND OBJECT_ID <> 30" ;
//and User_Name ='" + jTextField1.getText()+"'";
ResultSet rs = st.executeQuery(Query);
while(rs.next()){
JMenuItem newAction = new JMenuItem(rs.getString(1));
DimensionMenu.add(newAction);
rs.close();
st.close();
comm.close();
newAction.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
System.out.println("You have clicked on the Account");
}
});
}
} catch(Exception e){
JOptionPane.showMessageDialog(this,e);
}
}
You need to do some parametrization of the frame or have for example frame class stored also in DB and initialize it using reflexion...
Update:
Implementation can be like this:
package betlista.so.swing.menuitemdialogsfromdb;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MainFrame extends JFrame {
public MainFrame() {
super("Frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
add(createMenu());
pack();
}
private JMenuBar createMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Open");
menu.add(new DialogCreatingMenuItem("Dialog 1", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog1"));
menu.add(new DialogCreatingMenuItem("Dialog 2", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog2"));
menuBar.add(menu);
return menuBar;
}
class DialogCreatingMenuItem extends JMenuItem implements ActionListener {
String className;
public DialogCreatingMenuItem(String text, String className) throws HeadlessException {
super(text);
this.className = className;
addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae) {
try {
Class<JDialog> clazz = (Class<JDialog>)Class.forName(this.className);
JDialog dialog = clazz.newInstance();
dialog.setVisible(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static class MyDialog1 extends JDialog {
public MyDialog1() {
setTitle("Dialog 1");
add(new JLabel("Dialog 1"));
pack();
}
}
public static class MyDialog2 extends JDialog {
public MyDialog2() {
setTitle("Dialog 2");
add(new JLabel("Dialog 2"));
pack();
}
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
where Strings in
menu.add(new DialogCreatingMenuItem("Dialog 1", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog1"));
menu.add(new DialogCreatingMenuItem("Dialog 2", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog2"));
are retrieved from database...
Here is a sample code:
menuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
...
}
});
Remember the steps to creating a menu:
1. Create a MenuBar and add to the panel
2. Create a Menu and add to MenuBar
3. Create a MenuItem and add to Menu
Then add the listener to the MenuItem
Edit: if you use it outside the try statement it should work
Now i want to open a new jframe on the click of Period menuitem
Of course you have to add an ActionListener to your menu to do that, but the real question is How do you determine the right listener to each menu item? Since you fetch your menu items from database then it's not that easy as it looks like.
Note: see The Use of Multiple JFrames, Good/Bad Practice?
Option 1 (kind of dirty)
As I've said, you could store an action command and set it back to the menu item just like you set the menu's name:
while(rs.next()) {
String menuName = rs.getString("menuname");
String actionCommand = rs.getString("actioncommand");
JMenuItem newAction = new JMenuItem(menuName);
newAction.setActionCommand(actionCommand);
DimensionMenu.add(newAction);
...
}
Then you can have a listener that make use of ActionEvent#getActionCommand() to decide the right action to perform and attach this listener to all your menu items:
class MenuActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt) {
String actionCommand = evt.getActionCommand();
switch (actionCommand) {
case "OpenNewDialog": openNewDialog(); break;
...
}
}
private void openNewDialog() {
// implementation here
}
}
Then:
ActionListener listener = new MenuActionListener();
while(rs.next()) {
String menuName = rs.getString("menuname");
String actionCommand = rs.getString("actioncommand");
JMenuItem newAction = new JMenuItem(menuName);
newAction.setActionCommand(actionCommand);
newAction.addActionListener(listener);
DimensionMenu.add(newAction);
...
}
Option 2
Implement Factory method pattern to create a specific ActionListener or Action based on menu's action command:
class ActionListenerFactory {
public static Action createAction(final String actionCommand) {
switch (actionCommand) {
case "OpenNewDialog": return openNewDialogAction(); break;
...
}
}
private Action openNewDialogAction() {
Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent evt) {
// open new dialog here
}
};
return action;
}
}
Then:
while(rs.next()) {
String menuName = rs.getString("menuname");
String actionCommand = rs.getString("actioncommand");
JMenuItem newAction = new JMenuItem(menuName);
newAction.setActionCommand(actionCommand);
newAction.addActionListener(ActionListenerFactory.createAction(actionCommand));
DimensionMenu.add(newAction);
...
}
See also:
How to Use Actions tutorial.
Concurrency in Swing lesson.
Worker threads and SwingWorker to do database calls in a background thread and create/update Swing component in the Event Dispatch Thread

Create a save/save as dialog box in java that save a newly created file or an edited file

Java Beginner: Please help been working on this for days and my brain is dead.
I have created a java program (in eclipse) that has 3 menu: FILE, EDIT, HELP
once file is clicked it display 4menuBar: 'new, open,save,save as & exit.
On the HELP menu there is a menuBar that says "About javaEdit" All my menu bars work except save, save as and the "About javaEdit" I need some code or a clear step by step explanation for dummy on how to have my save and save as working.
Save should save newly created file or edited file & finally i could like the "About JavaEdit to display a message like "thank you, this is java" once clicked. I could like something like
private void doSave(){code here}
and
private void doSaveAs (){
because I have those item in the if else if statement.
How to create a save/save as dialog box in java that save a newly created file or an edited file?
Below is my entire code:
import java.awt.*;
import java.awt.event
import java.io.*;
public class JavaEdit extends Frame implements ActionListener {
String clipBoard;
String fileName;
TextArea text;
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem selectAllMI, cutMI, copyMI, deleteMI, pasteMI;
MenuItem aboutJavaEditMI;
/**
* Constructor
*/
public JavaEdit() {
super("JavaEdit"); // set frame title
setLayout(new BorderLayout()); // set layout
// create menu bar
MenuBar menubar = new MenuBar();
setMenuBar(menubar);
// create file menu
Menu fileMenu = new Menu("File");
menubar.add(fileMenu);
newMI = fileMenu.add(new MenuItem("New"));
newMI.addActionListener(this);
openMI = fileMenu.add(new MenuItem("Open"));
openMI.addActionListener(this);
fileMenu.addSeparator();
saveMI = fileMenu.add(new MenuItem("Save"));
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);
// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAllMI = editMenu.add(new MenuItem("Select all"));
selectAllMI.addActionListener(this);
cutMI = editMenu.add(new MenuItem("Cut"));
cutMI.addActionListener(this);
copyMI = editMenu.add(new MenuItem("Copy"));
copyMI.addActionListener(this);
pasteMI = editMenu.add(new MenuItem("Paste"));
pasteMI.addActionListener(this);
deleteMI = editMenu.add(new MenuItem("Delete"));
deleteMI.addActionListener(this);
// create help menu
Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
aboutJavaEditMI = helpMenu.add(new MenuItem("About JavaEdit"));
aboutJavaEditMI.addActionListener(this);
// create text editing area
text = new TextArea();
add(text, BorderLayout.CENTER);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI) {
clearText();
fileName = null;
setTitle("JavaEdit"); // reset frame title
}
else if(source == openMI) {
doOpen();
}
else if(source == saveMI) {
doSave();
}
else if(source == saveAsMI){
doSaveAs();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
}
/**
* method to specify and open a file
*/
private void doOpen() {
// display file selection dialog
FileDialog fDialog = new FileDialog(this, "Open ...", FileDialog.LOAD);
fDialog.setVisible(true);
// Get the file name chosen by the user
String name = fDialog.getFile();
// If user canceled file selection, return without doing anything.
if(name == null)
return;
fileName = fDialog.getDirectory() + name;
// Try to create a file reader from the chosen file.
FileReader reader=null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException ex) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"File Not Found: "+fileName);
dialog.setVisible(true);
return;
}
BufferedReader bReader = new BufferedReader(reader);
// Try to read from the file one line at a time.
StringBuffer textBuffer = new StringBuffer();
try {
String textLine = bReader.readLine();
while (textLine != null) {
textBuffer.append(textLine + '\n');
textLine = bReader.readLine();
}
bReader.close();
reader.close();
} catch (IOException ioe) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"Error reading file: "+ioe.toString());
dialog.setVisible(true);
return;
}
setTitle("JavaEdit: " +name); // reset frame title
text.setText(textBuffer.toString());
}
/**
* method to clear text editing area
*/
private void clearText() {
text.setText("");
}
/**
* method to copy selected text to the clipBoard
*/
private void doCopy() {
clipBoard = new String(text.getSelectedText());
}
/**
* method to delete selected text
*/
private void doDelete() {
text.replaceRange("", text.getSelectionStart(), text.getSelectionEnd());
}
/**
* method to replace current selection with the contents of the clipBoard
*/
private void doPaste() {
if(clipBoard != null) {
text.replaceRange(clipBoard, text.getSelectionStart(),
text.getSelectionEnd());
}
}
/**
* class for message dialog
*/
class MessageDialog extends Dialog implements ActionListener {
private Label message;
private Button okButton;
// Constructor
public MessageDialog(Frame parent, String title, String messageString) {
super(parent, title, true);
setSize(400, 100);
setLocation(150, 150);
setLayout(new BorderLayout());
message = new Label(messageString, Label.CENTER);
add(message, BorderLayout.CENTER);
Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
add(panel, BorderLayout.SOUTH);
okButton = new Button(" OK ");
okButton.addActionListener(this);
panel.add(okButton);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
}
}
/**
* the main method
*/
public static void main(String[] argv) {
// create frame
JavaEdit frame = new JavaEdit();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(size.width-80, size.height-80);
frame.setLocation(20, 20);
// add window closing listener
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show the frame
frame.setVisible(true);
}
}
Even an AWT program can use Action to encapsulate functionality and prevent (rather than suppress) leaking this in constructor. For example,
private static JavaEdit frame;
...
public JavaEdit() {
...
saveMI = fileMenu.add(new MenuItem("Save"));
saveMI.addActionListener(new SaveAction());
...
}
private static class SaveAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
FileDialog fDialog = new FileDialog(frame, "Save", FileDialog.SAVE);
fDialog.setVisible(true);
String path = fDialog.getDirectory() + fDialog.getFile();
File f = new File(path);
// f.createNewFile(); etc.
}
public static void main(String[] argv) {
// create frame
frame = new JavaEdit();
...
// show the frame
frame.pack();
frame.setVisible(true);
}
See HTMLDocumentEditor, cited here, for example implementations of related actions.

Categories