JMenu as a submenu???

Hi all
I have a JMenu which is a submenu of another
What my problem is is I cannot change the background color of the submenu
here is the code
menuBar = new JMenuBar();
menuBar.setBackground(Color.blue);
menu = new JMenu("Menu");
menu.setBackground(Color.blue);
submenu = new JMenuItem("submenu");
submenu.setBackground(Color.blue);
item1 = new JMenuItem("item1");
item1.setBackground(Color.blue);
submenu.add(item1);
menu.add(submenu);
menuBar.add(menu);Although I change their background color to blue, the submenu is still grey, which I can't construe.
what is wrong with this simple code?
thanks

Here is the whole code
import javax.swing.*;
import java.awt.*;
public class Deneme extends JFrame {
     JMenuBar menuBar;
     JMenu menu, submenu;
     JMenuItem item1, item2;
     public Deneme() {
          menuBar = new JMenuBar();
          menuBar.setBackground(Color.blue);
          menu = new JMenu("Menu");
          menu.setBackground(Color.blue);
          submenu = new JMenu("submenu");
          submenu.setBackground(Color.blue);
          item1 = new JMenuItem("item1");
          item1.setBackground(Color.blue);
          submenu.add(item1);
          menu.add(submenu);
          menuBar.add(menu);
          setJMenuBar(menuBar);
          setVisible(true);
          setSize(200, 100);
     public static void main(String[]args){
          new Deneme();
}thanks
Message was edited by:
voywoda

Similar Messages

  • JMenu pop-up SubMenu problem

    Hi,
    I'm having a problem displaying a submenu on a JMenu. My app has a tree with various nodes. After clicking on one of the nodes, you can either view the menu in pop-up form by right clicking on the node, or from a regular menu at the top of the screen. These menu's are identical and are generated by the same functions except one if pop-up and the other is not.
    Everything works fine, EXCEPT, when opening the pop-up menu, the submenu's do not appear - the "Select Files" item does not even have the submenu arrow next to it. I know this methos is entered and run without failure as I have debugged it but the submenus just do not appear.
    Here is the source:
    JMenuItem[] m_actions m_actions = new JMenuItem[actionNames.length];     // items for display in the popup menu for this object
    JMenu m_selectFiles = new JMenu("Select Files");                    // sub menu for select files option
    public void setMenu(JMenu aMenu, boolean aMultipleSelection) {          
         aMenu.removeAll();
         for(int i=0; i<m_actions.length; i++) {
              if (m_actions[i] instanceof JMenu) {
                   if (!m_actions.getText().equals("Select Files"))
                        aMenu.add((JMenu)m_actions[i]);
                   else                         
                        addSelectMenu (aMenu);                                             
              } else     {
                   aMenu.add(m_actions[i]);
                   if(aMultipleSelection & !m_multipleActions[i])
                        m_actions[i].setEnabled(false);
                        if(!aMultipleSelection & m_permittedActions[i])
                        m_actions[i].setEnabled(true);
    private void addSelectMenu (JMenu aMenu) {
         if (m_selectFiles.getItemCount() > 0) {
              m_selectFiles.removeAll();
         templateSubMenus = new JMenu("Output Templates");          
         if (templateNames == null)
              templateNames = getTemplates();
         else {
              templateNames.removeAllElements();
              templateNames = getTemplates();
         if (templateSubMenus.getItemCount() > 0) {
              templateSubMenus.removeAll();
         JMenu[] templateSubOptions = new JMenu[templateNames.size()];          
         for(int j=0; j<templateNames.size(); j++) {               
              templateSubOptions[j] = new JMenu((String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Modify"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempModify:"+(String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Copy"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempCopy:"+(String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Delete"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempDelete:"+(String)templateNames.elementAt(j));
              templateSubMenus.add((JMenu)templateSubOptions[j]);               
         templateSubMenus.addSeparator();
         templateSubMenus.add(new JMenuItem("New Template"));          
         templateSubMenus.getItem(templateSubMenus.getItemCount()-1).addActionListener(monListener);          
         m_selectFiles.add(templateSubMenus);
         aMenu.add((JMenu)m_selectFiles);          
    Any ideas would be greatly appreciated.
    Thanks!!!!!

    Hi,
    I have the same problem. Can anybody help please?
    Thanks,
    Kaveh

  • Arrow of a selected JMenu with a submenu doesnt work

    Hello,
    I've a problem with a menubar with some JMenu's and some submenu's.
    The color of the arrow of a JMenu is always black when it is selected. Even when I changed the DefaultUI settings for this component.
    Sow when I change the follow parameters the text and the arrow have the good color.
    Menu.foreground (same for MenuItem)
    but when I change the follow parameters only the color of the text will change when selected and the arrow is still black
    Menu.selectedForeground (same for MenuItem)
    Do i something wrong or is this a bug ?
    Thx in advance!

    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JPopupMenu with submenu

    Hello,
    I have a grid of buttons. If the user clicks a button with the right mouse button,
    a JPopupMenu shows up. The popup menu includes also 2 submenus (JMenu).
    When the user selects a menuitem, I need to know which was the selected button,
    because it identifies the object on which the operation has to be performed.
    If the menuitem is not in a submenu, I can get the button using
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();But if the selected menuitem is in the submenu, popup.getInvoker returns the JMenu (submenu)
    and not the button.
    How do I get which button was pressed?
    thanks Marina

    Sorry it is not clear to me how.
    This is the code that shows the popup
    mb.addMouseListener( new java.awt.event.MouseListener() {
              public void mouseEntered(MouseEvent e) {
              public void mouseExited(MouseEvent e) {
              public void mouseReleased(MouseEvent e) {
              public void mouseClicked(MouseEvent e) {
                   if (e.getButton() == MouseEvent.BUTTON3)
                        JButton button = (JButton)e.getSource();
                        if (button.isEnabled())
                             mcPopup.show(button,0,button.getHeight());
              public void mousePressed(MouseEvent e) {
    The different clicks are then handled by the ActionListener:     if(actionString.equals("ccbinfo")) //default action for left click on the button
                   b = (JButton) arg0.getSource();
              else if (actionString.contains("power")) //action for submenu items
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) ?
              else // action for popup items (not in submenu)
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();
    In the ActionListener the button information from the MouseClicked event is not available,
    how do I pass the button info to the menu?
    The menu is constructed only once, and the attached to the button only when right clicked.     private void buildPopupMenu()
              mcPopup = new JPopupMenu();
              pwrOnPopup = new JMenu("Power on"); //submenu
              pwrOffPopup = new JMenu("Power off"); //submenu
    ... //build and add items
         mcPopup.add(pwrOnPopup);
         mcPopup.add(pwrOffPopup);
    thanks Marina                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem printing JTable

    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    class DisplayQueryResultsDOD extends JFrame implements Printable,ActionListener
    ResultSetTableModelDOD tableModel;
    JTextArea queryArea;
    JTable resultTable;
    // create ResultSetTableModel and GUI
    DisplayQueryResultsDOD()
    super( "Displaying Query Results" );
    // Cloudscape database driver class name
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // URL to connect to books database
    String url = "jdbc:odbc:MyDataSource";
    // query to select entire authors table
    String query = "SELECT * FROM person";
    // create ResultSetTableModel and display database table
         try
    // create TableModel for results of query
    // SELECT * FROM authors
              tableModel =
              new ResultSetTableModelDOD( driver, url, query );
    // set up JTextArea in which user types queries
              queryArea = new JTextArea( query, 3, 100 );
              queryArea.setWrapStyleWord( true );
              queryArea.setLineWrap( true );
              JScrollPane scrollPane = new JScrollPane( queryArea,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    // set up JButton for submitting queries
              JButton submitButton = new JButton( "Submit Query" );
    // create Box to manage placement of queryArea and
    Box box = Box.createHorizontalBox();
              box.add( scrollPane );
              box.add( submitButton );
    // create JTable delegate for tableModel
              JTable resultTable = new JTable( tableModel );
    // place GUI components on content pane
              Container c = getContentPane();
              c.add( box, BorderLayout.NORTH );
              c.add( new JScrollPane( resultTable ),
              BorderLayout.CENTER );
    // create event listener for submitButton
              submitButton.addActionListener(
         new ActionListener()
         public void actionPerformed( ActionEvent e )
    // perform a new query
         try
              tableModel.setQuery( queryArea.getText() );
    // catch SQLExceptions that occur when
    // performing a new query
         catch ( SQLException sqlException )
              JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error",JOptionPane.ERROR_MESSAGE );
    } // end actionPerformed
    } // end ActionListener inner class
    // set window size and display window
    JMenuBar menuBar = new JMenuBar();
         JMenu filemenu= new JMenu("File");
         JMenu submenux=new JMenu("Open");
         JMenuItem np=new JMenuItem("Launch Panel");
         submenux.add(np);
         //openmenuitem.addActionListener(this);
         submenux.setActionCommand("Open");
         submenux.setMnemonic('O');
         filemenu.add(submenux);
         menuBar.add(filemenu);
         JMenuItem printItem = new JMenuItem("Print");
         printItem.setMnemonic('P');
         filemenu.add(printItem);
         JMenuItem ExitItem = new JMenuItem("Exit");
    ExitItem.setMnemonic('x');
         filemenu.add(ExitItem);
         JMenu viewmenu=new JMenu("View");
         JMenuItem repItem=new JMenuItem("Reports");
         JMenu submenu=new JMenu("sort by");
         submenu.add(new JMenuItem("Marital Status"));
    submenu.add(new JMenuItem("Rank"));
         submenu.add(new JMenuItem("Tribe"));
         submenu.add(new JMenuItem("Educational Level"));
         viewmenu.add(submenu);
         menuBar.add(viewmenu);
         setJMenuBar(menuBar);
    printItem.addActionListener(this);
         ExitItem.addActionListener
         new ActionListener()
    public void actionPerformed(ActionEvent ae)
    System.exit(0);
    setSize( 1500,900);
    // setVisible( true );
    } // end try
    // catch ClassNotFoundException thrown by
    // ResultSetTableModel if database driver not found
         catch ( ClassNotFoundException classNotFound )
         JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );
              System.exit( 1 ); // terminate application
    // catch SQLException thrown by ResultSetTableModel
    // if problems occur while setting up database
    // connection and querying database
         catch ( SQLException sqlException )
         JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 ); // terminate application
    } // end DisplayQueryResults constructor
         public void actionPerformed(ActionEvent e)
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try
    printJob.print();
    catch (Exception ex)
    ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int page) throws
    PrinterException {
    if (page > 0) { /* We have only one page, and 'page' is zero-based */
    return NO_SUCH_PAGE;
    /* User (0,0) is typically outside the imageable area, so we must
    * translate by the X and Y values in the PageFormat to avoid clipping
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    /* Now print the window and its visible contents */
    resultTable.printAll(g);
    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
    // execute application
    public static void main( String args[] )
    DisplayQueryResultsDOD app = new DisplayQueryResultsDOD();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } // end class DisplayQueryResults
    I get an exception
    pls help

    I included this statement only to check if it would print or not, because before that I tried printing the table without setting the size. Anyway, when I tried the same code under Windows it worked fine. Talking about platform independent...:-)

  • JMenuItem ActionEvent Dinamically - Problems

    Hi, friends
    I am trying to use a JMenu and a JMenuItem wich are dinamicaly
    constructed getting data using a Oracle's Database Table.
    They are working fine, but I can't figured out how can I add
    ActionEvent dinamicaly. The piece of my code is down here:
    JMenuBar menuOpcao = new JMenuBar;
    JMenu menu[] = new JMenu[5];
    JMenuItem submenu[] = new JMenuItem[20];
    for (x=0;x<menu.lenght;x++)
    menu[x] = new JMenu();
    menu[x].setLabel(" menu " + x); //menu 1, menu 2...
    for (y=0;y<submenu.lenght;y++)
    submenu[y] = new JMenuItem();
    submenu[y].setLabel(" submenu " + y); // submenu 1...
    submenu[y].addActionListener(new ActionListener()
    { public void actionPerformed(ActionEvent e){
    System.out.println(e);}
    menu[x].add(submenu[y];
    menuOpcao.add(menu[x]);
    My problem: the ActionEvent is not working, because I need know
    wich Item I am clicking, so I can execute a query in a Database.
    Any Ideas?
    Thank you.
    null

    You don't use MouseListeners. You use ActionListeners.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for working examples.

  • TableModelListener doesn't appear to be working

    Hi,
    I have the following code that is called when a menu item is selected. When the method tableChanged is commented out, the table is displayed just fine. With it in, even if the if statements are commented out, it doesn't display. I just get the frame title being displayed.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    public class updateCurrentHiLo extends JTable implements TableModelListener {
            public updateCurrentHiLo() {
                    super();
                    String[] columnNames = {"Currency",
                                    "Current Hi",
                                    "Current Lo"};
                    Object[][] data = {
                            {"AUD/USD",DataCapture.currentHigh[0], DataCapture.currentLow[0]},
                            {"GBP/USD",DataCapture.currentHigh[1], DataCapture.currentLow[1]},
                            {"EUR/USD",DataCapture.currentHigh[2], DataCapture.currentLow[2]},
                            {"EUR/JPY",DataCapture.currentHigh[3], DataCapture.currentLow[3]},
                            {"USD/JPY",DataCapture.currentHigh[4], DataCapture.currentLow[4]},
                            {"USD/CHF",DataCapture.currentHigh[5], DataCapture.currentLow[5]},
                            {"USD/CAD",DataCapture.currentHigh[6], DataCapture.currentLow[6]},
                            {"NZD/USD",DataCapture.currentHigh[7], DataCapture.currentLow[7]}
                    DefaultTableModel model = new DefaultTableModel(data, columnNames);
                    //model.addTableModelListener( this ); //We can now check whether the table has been updated.
                    setModel(model);
                    //setFont( new Font("Garamond", Font.BOLD, 50));  //Set the look and feel of the table
                    //setRowHeight(50);  //If you change font size don't forget to change the row height.
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
                    setPreferredScrollableViewportSize(getPreferredSize());      
                    model.addTableModelListener( this ); //We can now check whether the table has been updated.
            public void tableChanged(TableModelEvent e)     {
                    TableModel model = getModel();
                    if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                            int column = e.getColumn();
                            /*if ( column == 1 && DhbMath.equals( ((Double)model.getValueAt(row,column)).doubleValue(),DataCapture.currentHigh[row] ) == false ) {
                                    DataCapture.currentHigh[row] = ((Double)model.getValueAt(row,column)).doubleValue();
                                    System.out.println(DataCapture.currentHigh[row]);
                            /*else if ( column == 2 ) {
                                    DataCapture.currentLow[row] = ((Double)model.getValueAt(row,column)).doubleValue();
    }This is the code that calls the table:
    public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem)(e.getSource());
            if ( source.getText().equals("Exit") ) {
                    int clickVALUE = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Quit Confirmation", JOptionPane.YES_NO_OPTION);                    
              if (clickVALUE == 0)     {
                         System.exit(0);
            else {
                            if ( source.getActionCommand().equals("HiLo") ) {
                                    //Do summin
                                    JFrame test = new JFrame("Update Current Highs and Lows");
                                    test.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                                    //JOptionPane.showInputDialog(
                                    updateCurrentHiLo table = new updateCurrentHiLo();
                                    JScrollPane scrollPane = new JScrollPane( table );
                                    test.add( scrollPane );
                                    test.pack();
                              test.setLocationRelativeTo( null );
                              test.setVisible(true);
        }Any help would be appreciated.
    Regards,
    Dave

    Hi,
    I've made a SSCE to illustrate the problem:
    Main class: RateTable.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JComponent;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.JTabbedPane;
    import javax.swing.JFrame;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.util.Date;
    import java.util.LinkedList;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.DecimalFormat;
    import java.text.ParseException;
    import java.util.StringTokenizer;
    import java.net.URL;
    import java.io.*;
    import java.io.*;
    public class RateTable {
        private static void createAndShowGUI() {
            //Create and set up the window.
            MenuCreator createMenu = new MenuCreator();
            JFrame frame = new JFrame("TabbedPaneDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setJMenuBar(createMenu.createMenuBar());
            //Create and set up the content pane.
            JComponent newContentPane = new TabbedPaneDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.getContentPane().add(new TabbedPaneDemo(), BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)  throws IOException {
                    createAndShowGUI();
    }SimpleTable.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    public class SimpleTable extends JTable {
            public SimpleTable() {
                    super();
                    String[] columnNames = {"Column 1", "Column 2"};
                    Object[][] data = {
                            {"AUD/USD",new Double(0)},
                            {"GBP/USD",new Double(0)},
                    DefaultTableModel model = new DefaultTableModel(data, columnNames);
                    model.addTableModelListener( this ); //We can now check whether the table has been updated.
                    setModel(model);
                    setFont( new Font("Garamond", Font.BOLD, 50));  //Set the look and feel of the table
                    setRowHeight(50);  //If you change font size don't forget to change the row height.
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
    }MenuCreator.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    import java.lang.Number;
    public class MenuCreator implements ActionListener, TableModelListener {
        JTextArea output;
        JScrollPane scrollPane;
        String newline = "\n";
        updateCurrentHiLo table;
        public JMenuBar createMenuBar() {
                    JMenuBar menuBar;
                    JMenu menu, menu2, submenu;
                    JMenuItem menuItem;
                    JRadioButtonMenuItem rbMenuItem;
                    JCheckBoxMenuItem cbMenuItem;
                    //Create the menu bar.
                    menuBar = new JMenuBar();
                    //Build the first menu.
                    menu = new JMenu("RateTable");
                    menu.setMnemonic(KeyEvent.VK_R);
                    menuBar.add(menu);
                    menuItem = new JMenuItem("Update Current High & Low");
                    menuItem.setMnemonic(KeyEvent.VK_U);
                    menuItem.setActionCommand("HiLo");
                    menuItem.addActionListener(this);
                    menu.add(menuItem);
            return menuBar;
        public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem)(e.getSource());
            if ( source.getActionCommand().equals("HiLo") ) {
                    JFrame test = new JFrame("Update Current Highs and Lows");
                    test.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                    table = new updateCurrentHiLo();
                    TableModel model = table.getModel();
                    model.addTableModelListener( this );
                    JScrollPane scrollPane = new JScrollPane( table );
                    test.add( scrollPane );
                    test.pack();
              test.setLocationRelativeTo( null );
              test.setVisible(true);
        public void tableChanged(TableModelEvent e)     {
                    TableModel model = table.getModel();
                    if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                            int column = e.getColumn();
                            System.out.println("Row "+row);
                            System.out.println("Column "+column);
                            if ( column == 1 ) {
                                    Object test = table.getValueAt(row,column);
                                    System.out.println(test);
                                    //If the following line is commented out, we don't have a problem
                                    Double value = (Double)test;
    }updateCurrentHiLo.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    public class updateCurrentHiLo extends JTable  {
            public updateCurrentHiLo() {
                    super();
                    String[] columnNames = {"Currency",
                                    "Current Hi",
                                    "Current Lo"};
                    Object[][] data = {
                            {"AUD/USD", new Double(0), new Double(0)},
                            {"GBP/USD", new Double(0), new Double(0)},
                            {"EUR/USD", new Double(0), new Double(0)},
                            {"EUR/JPY", new Double(0), new Double(0)},
                            {"USD/JPY", new Double(0), new Double(0)},
                            {"USD/CHF", new Double(0), new Double(0)},
                            {"USD/CAD", new Double(0), new Double(0)},
                            {"NZD/USD", new Double(0), new Double(0)},
                    TableModel model = new DefaultTableModel(data, columnNames);
                    setModel(model);
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
                    setPreferredScrollableViewportSize(getPreferredSize());      
    }TabbedPaneDemo.java
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.JTabbedPane;
    import javax.swing.JFrame;
    import java.awt.event.*;
    public class TabbedPaneDemo extends JPanel {
        SimpleTable table = new SimpleTable();
        public TabbedPaneDemo() {
            super(new GridLayout(1, 1));
            JTabbedPane tabbedPane = new JTabbedPane();
            //SimpleTable table = new SimpleTable();
            JScrollPane scrollPane = new JScrollPane( table );
            JPanel panel = new JPanel(false);
            panel.add(scrollPane);
            panel.setPreferredSize(new Dimension(410, 50));
            tabbedPane.addTab("Tab 1", null, panel,
                    "Does nothing");
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            //Add the tabbed pane to this panel.
            add(tabbedPane);
            //The following line enables to use scrolling tabs.
            tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    }Hope someone can help me track down this error.

  • Problem in Disabled the Menus

    hi everyone,
    Hello am developing a application in java. I used InternalFrame and JDesktop.. My problem is after the login i want to disabled the menu in the Menubar when the user login sucessfully it will be enabled and ready to click. But am having a problem because my code in login is separated into the MainFrame.. i got to java file 1. MainFrame_PCM.java and MyLoginInternalFrame.java. So when the MainFrame_PCM was run it will call MyLoginInternalFrame as my login in window what i want is by default the MenuBar in MainFrame_PCM was set disabled and after login successfully i will set them enabled .Hope you understand my problem .Any help will do ..
    Thank you very much in advance
    Armando Dizon

    Hi Pravinth,
    Thank you very very much in reply in my email.Below is my code of the MainFrame and the LoginFrame as i mention in my previous post. The scencario in the thread that similar in my problem is you have to go to Main menu and click login and login form or frame will pop up in my case automatic popup and what i want sir is when the popup frame will appear and successfully login the Menu will be setEnabled. Thank you i really apprecaite your help
    /*File name : MainFrame_PCM.java*/
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import java.awt.event.*;
    import java.awt.*;
    * MainFrame_PCM.java is a 1.4 application that requires:
    * MyInternalFrame.java
    public class MainFrame_PCM extends JFrame implements ActionListener
    JDesktopPane desktop;
    public MainFrame_PCM()
    super("Peso Collection Module");
    //Make the big window be indented 50 pixels from each edge
    //of the screen.
    int inset = 50;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
    //Set up the GUI.
    desktop = new JDesktopPane(); //a specialized layered pane
    createLoginFrame(); //create first "window"
    setContentPane(desktop);
    setJMenuBar(createMenuBar());
    //Make dragging a little faster but perhaps uglier.
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    /* This portion creates the Menu Tool Bar.
    // And creates the Menu Toor Bar sub menus.
    // Ining parti na ning code a ini gawa yang
    //menu Bar and Sube menus pra keng Main Menu
    protected JMenuBar createMenuBar()
    JMenuBar menuBar = new JMenuBar();
    //Set up Main Menus
    JMenu menu = new JMenu("Main Menu");
    menu.setMnemonic(KeyEvent.VK_D);
    menuBar.add(menu);
    JMenu menu2 = new JMenu("Maintenance");
    menu2.setMnemonic(KeyEvent.VK_M);
    menuBar.add(menu2);
    ///////////////////// SUB MENUS CODE HERE ///////////////////
    //a submenu
              menu2.addSeparator();
              JMenu submenu = new JMenu("Manage Users");
              submenu.setMnemonic(KeyEvent.VK_S);
              JMenuItem menuItem8 = new JMenuItem("Add New User");
              menuItem8.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_A, ActionEvent.ALT_MASK));
              menuItem8.setActionCommand("adduser");
              menuItem8.addActionListener(this);
              submenu.add(menuItem8);
              JMenuItem menuItem9 = new JMenuItem("Edit User Profile");
              menuItem9.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_E, ActionEvent.ALT_MASK));
              menuItem9.setActionCommand("editusers");
              menuItem9.addActionListener(this);
              submenu.add(menuItem9);
              menu2.add(submenu);
              JMenuItem menuItem10 = new JMenuItem("Delete User");
              menuItem10.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_D, ActionEvent.ALT_MASK));
              menuItem10.setActionCommand("deleteusers");
              menuItem10.addActionListener(this);
              submenu.add(menuItem10);
              menu2.add(submenu);
              //Set up the Maintenance Menu item.
    JMenuItem menuItemMtc = new JMenuItem(" Program Access");
    menuItemMtc.setMnemonic(KeyEvent.VK_U);
    // menuItemMtc.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_L, ActionEvent.ALT_MASK));     
    menuItemMtc.setActionCommand("manage_users");
    menuItemMtc.addActionListener(this);
    menu2.add(menuItemMtc);
              /*--------End of Maintenance Menu item--------*/
    //Set up the Main menu item.
    JMenuItem menuItem = new JMenuItem("Login");
    menuItem.setMnemonic(KeyEvent.VK_L);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_L, ActionEvent.ALT_MASK));     
    menuItem.setActionCommand("login");
    menuItem.addActionListener(this);
    menu.add(menuItem);
              JMenuItem menuItem2 = new JMenuItem("User Maintenance");
    menuItem2.setMnemonic(KeyEvent.VK_N);
    menuItem2.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_N, ActionEvent.ALT_MASK));     
    menuItem2.setActionCommand("user");
    menuItem2.addActionListener(this);
    menu.add(menuItem2);
              //Set up the QUIT menu item.
    menuItem = new JMenuItem("Quit");
    menuItem.setMnemonic(KeyEvent.VK_Q);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_Q, ActionEvent.ALT_MASK));
    menuItem.setActionCommand("quit");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    /*--------End of Main Menu item--------*/
    return menuBar;
    //////////////////// END OF SUB MENUS HERE ////////////////////
    //React to Sub menu selections. keni la mayayaus deng forms potng me click!
    public void actionPerformed(ActionEvent e)
    if ("login".equals(e.getActionCommand())) //new login fram
    createLoginFrame();
                   else if ("user".equals(e.getActionCommand())) //new temporary ya ini
                   createFrame();
                   else if ("adduser".equals(e.getActionCommand())) //new user frame
                   createManageUserFrame();//call the Manage User Form Functions
                   else if ("editusers".equals(e.getActionCommand())) //new user frame
                   createEditUserFrame();//call the Edit User Form Functions
                   else if ("deleteusers".equals(e.getActionCommand())) //new user frame
                   createDeleteUserFrame();//call the Edit User Form Functions
              else //quit
    quit();
         /*-------------- End Of Sub Menus Reactions ------------*/     
         //Create a new internal frame for User Login
              protected void createLoginFrame()
                   MyLoginInternalFrame frame = new MyLoginInternalFrame();
                   frame.setVisible(true); //necessary as of 1.3
                   desktop.add(frame);
                   try
                        frame.setSelected(true);
                   } catch (java.beans.PropertyVetoException e) {}
              //Create a new internal frame for User Maintenance TEMPORARY YA INI BOI
              protected void createFrame()
                   MyInternalFrame frame = new MyInternalFrame();
                   frame.setVisible(true); //necessary as of 1.3
                   desktop.add(frame);
              try
                        frame.setSelected(true);
                   } catch (java.beans.PropertyVetoException e) {}
              // Create a new internal fram for Manage Users
              protected void createManageUserFrame()
                   ManageUserForm frame = new ManageUserForm();
                   frame.setVisible(true); //necessary as of 1.3
                   desktop.add(frame);
              try
                        frame.setSelected(true);
                   } catch (java.beans.PropertyVetoException e) {}
              // Create a new internal fram for Edit Users
              protected void createEditUserFrame()
                   createEditUserForm frame = new createEditUserForm();
                   frame.setVisible(true); //necessary as of 1.3
                   desktop.add(frame);
              try
                        frame.setSelected(true);
                   } catch (java.beans.PropertyVetoException e) {}
              // Create a new internal fram for Edit Users
              protected void createDeleteUserFrame()
                   createDeleteUserForm frame = new createDeleteUserForm();
                   frame.setVisible(true); //necessary as of 1.3
                   desktop.add(frame);
              try
                        frame.setSelected(true);
                   } catch (java.beans.PropertyVetoException e) {}
    //Quit the application.
    protected void quit() {
    System.exit(0);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    MainFrame_PCM frame = new MainFrame_PCM();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Display the window.
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
                        javax.swing.SwingUtilities.invokeLater(new Runnable()
                             public void run() {
                                  createAndShowGUI();
    /*File name : MyLoginInternalFrame.java*/
    import javax.swing.JInternalFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class MyLoginInternalFrame extends JInternalFrame implements ActionListener
         static final int xOffset = 320, yOffset = 200;
         JPasswordField pass_word;
         JTextField user_name;
         JLabel lbl;
         JButton btnclear, btnexit,btnsearch;
         String url;
         Connection connect;
    public MyLoginInternalFrame()
         super("User Login ");
                        //Database Connectivity
                        try
                        url = "jdbc:odbc:Plogbook";
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        connect = DriverManager.getConnection(url);
                             catch(ClassNotFoundException cnfex)
                             cnfex.printStackTrace();
                             System.err.println("Failed to load JDBC/ODBC driver");
                             System.exit(1);     
                             catch (SQLException sqlex)
                             sqlex.printStackTrace();     
                             catch (Exception ex)
                             ex.printStackTrace();     
                   //Fields to be Set Up
                   Container c = getContentPane();
                   GridLayout ly = new GridLayout(0,3);
                   c.setLayout(ly);
                   //Blank Labels
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" Username:");
                   c.add(lbl);
                   user_name = new JTextField(20);
                   user_name.setToolTipText("Enter Your User Name");
                   c.add(user_name);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" Password:");
                   c.add(lbl);
                   pass_word = new JPasswordField(200);
                   pass_word.setToolTipText("Enter Your Password");
                   c.add(pass_word);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   btnsearch = new JButton("Login");
                   btnsearch.addActionListener(this);
                   c.add(btnsearch);
                   //btnclear = new JButton("Clear");
                   //btnclear.addActionListener(this);
                   //c.add(btnclear);
                   btnexit = new JButton("Cancel");
                   btnexit.addActionListener(this);
                   c.add(btnexit);
                   //Blank Labels
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   lbl = new JLabel(" ");
                   c.add(lbl);
                   setSize(300,150);
                   setLocation(xOffset, yOffset);
                   //Quit the application.
                   protected void quit()
                   System.exit(0);
                   public void actionPerformed(ActionEvent e)
                   // Clear the fields
                        if(e.getSource() == btnclear)
                        user_name.setText("");
                        pass_word.setText("");
                   // Exit the program
                        if(e.getSource() == btnexit)
                        //setVisible(false);
                        quit();
                             // Search the file
                                  if(e.getSource()==btnsearch)
                                            try
                                                 Statement statement=connect.createStatement();
                                                 String sqlQuery ="SELECT * FROM a_user WHERE user_id = '"+ user_name.getText() + "' AND password = '"+ pass_word.getText() + "'";
                                                 ResultSet rs = statement.executeQuery(sqlQuery);
                                                 if(rs.next())
                                                      setVisible(false);
                                                      JOptionPane.showMessageDialog(null,"ACCESS GRANTED");     
                                                      else
                                                           JOptionPane.showMessageDialog(null,"ACCESS DENIED");
                                                           user_name.setText("");
                                                           pass_word.setText("");
                                                 catch (SQLException sqlex)
                                                      sqlex.printStackTrace();          
                                                      JOptionPane.showMessageDialog(null, sqlex.toString());     
                   public static void main(String arg[])
                             MyLoginInternalFrame frm = new MyLoginInternalFrame();
                             frm.show();
    }

  • JButton can not fire ActionEvent

    Hi,
    There is a problem found on JRE 1.5 Update 4on Windows XP for a JButton in my application.
    Here is the short description of the app.
    There are ImageIcons loaded into JButtons. There JButtons are added to a JPanle. The JPanle is then add to a JScrollPane. The scroll pane itself is added as a menu item for a Popmenu. When I click the image icon of the button, it will invoke the action listener's actionPerfromed method. The action listener has been earlier added to the JButtons.
    It workked with JRE 1.4.0 but it fail witj JRE 5.0 Update 4. It is like a bug to me. Or the JButton class stops deliver action events when it is part of a menu item. Any idea why?
    J.

    Hey, good morning, Jaspre
    I found a mistake in my problem statement. You should add a JMenu to the JPopupMenu and add the JScrollPane to the JMenu.
    Maybe the code should not add a JMenu to a JPopupMenu, but it's there in the code. Below is a test which I modify from yours. It does not show the dialog on 1.5.0.4 runtime.
    This test case also shows 2 other possible bugs.
    1.The border text for the JButtons do not position at the right place using JRE 1.5.0.4.
    2.The JScrollPane's behaviour is very strange so that users' experience will not be satisfied.
    For each description, please run it against JRE 1.4.0 and 1.5.0.5 to see what I mean.
    Thanks
    Jack
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonTest extends JFrame
         public ButtonTest() {
              super("ButtonTest");
              ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(ButtonTest.this,
                             "Clicked " + ((JButton)e.getSource()).getText());
            JPanel panel = new JPanel();
            GridBagConstraints c = new GridBagConstraints ();
            c.fill = GridBagConstraints.BOTH;
            c.weightx = 1 ;
            c.weighty = 1 ;
            GridBagLayout layout = new GridBagLayout();       
            panel.setLayout(layout);
              JButton b;
              for (int i = 0; i < 10; i++) {
                   b = new JButton("Button-"+(i+1));
                   b.addActionListener(al);
                   c.gridx = 0 ;
                 c.gridy = i ;
                 layout.setConstraints(b,c);
                 b.setBorder (BorderFactory.createTitledBorder
                         (b.getBorder (), "border")) ;
                   panel.add(b);
              JScrollPane scroller = new JScrollPane(panel);
              scroller.setPreferredSize(new Dimension (200,500));
              final JPopupMenu menu = new JPopupMenu();
              JMenu submenu = new JMenu();
              menu.add(submenu);
              submenu.add(scroller);
              getContentPane().addMouseListener(new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        popup(e);
                   public void mouseClicked(MouseEvent e) {
                        popup(e);
                   public void mouseReleased(MouseEvent e) {
                        popup(e);
                   private void popup(MouseEvent e) {
                        if (e.isPopupTrigger())
                             menu.show(e.getComponent(), e.getX(), e.getY());
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              setSize(600, 400);
         public static void main(String[] args){
              ButtonTest bt = new ButtonTest();
              bt.setLocationRelativeTo(null);
              bt.setVisible(true);
    }

  • Sublist of JList?

    JMenu has a submenu, but it it possible to implement a sublist for a JList?
    I have an existing GUI that displays a list. I can't change that. What I want to do is, when you click on a certain item on the list, it displays whether another list or combobox ala menu-submenu style. I've tried implementing the example ListCellRenderer, but it extends JLabel. How do I go about adding a JComboBox or list in my ListCellRenderer?
    Any hint is appreciated.

    ListCellRenderer in the example extends JLabel because that's the commonest thing that people use in making a JList. But you can write a ListCellRenderer that extends any component that you like.

  • Dynamic jmenu bar

    i have a dynamic JMenu on a jframe. The menu is populated by looking up database entries and ptting them into the right place. This is done by a method 'menus()'.
    I also have an addingredients class which adds new ingredient entries into the database, problem is when it does this, the JMenu has to be repopulated. The following code shows the main frame
    // Recipe Creation GUI
    // Written by Michael Emett
    // Monday 15th Decemeber 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame.*;
    import java.sql.*;
    import java.util.*;
    public class TextAreaDemo extends JFrame     {
    private static JTextArea part1;
    private JButton Browse, Enter, Preview, Remove;
    public static JList printList, newList;
    private JCheckBox pic;
    private JLabel namePrompt, title1, title2, title3;
    private static JTextField nameInput;
    private JPanel jp, jp1, jp2, jp3, jp4, jp5;
    private Connection con;
    private Statement stmt;
    public static JMenu fileMenu;
    private static JMenuBar bar;
    // additions /////////////////////////////////////////////////////////////////////////
    //set up GUI
    public TextAreaDemo()     {
    super( "Recipe Entry Sheet" );
    // set up File menu and its menu items
    // Menu and button Initialization ////////////////////////////////////////////////////
    //myMouse = new MyMouseAdapter();
    //final JMenu
    fileMenu = new JMenu( "Ingredients");
             fileMenu.setMnemonic( 'I' );
    fileMenu.add(menus());
    bar = new JMenuBar();
    setJMenuBar( bar );
    JMenu file = new JMenu( "File");
    file.setMnemonic( 'F' );
        bar.add(file);
              JMenuItem Adder = new JMenuItem( "New Ingredient");
             Adder.setMnemonic( 'N' );
    JMenuItem Subber = new JMenuItem( "New subMenu");
             Subber.setMnemonic( 'S' );
             // set up About... menu item
             JMenuItem aboutItem = new JMenuItem( "About..." );
             aboutItem.setMnemonic( 'A' );
    namePrompt = new JLabel( "Recipe Name " );
    nameInput = new JTextField( 20 );
    title1 = new JLabel( "Selected ingredients" );
    title3 = new JLabel( "Please enter the Recipe Instructions" );
    title2 = new JLabel( "Enter The SubMenu Name " );
    pic = new JCheckBox("Add Picture", false);
    file.add( Adder );
         Adder.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        getList f = new getList();
    // Add Ingredient menu item //////////////////////////////////////////////////////////
    file.add( Subber );
         Subber.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        AddSubMenu f = new AddSubMenu();
    // About menu item ///////////////////////////////////////////////////////////////////
    file.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects About...
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( TextAreaDemo.this,
                      "Developed by Michael Emett, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
              }     // end anonymous inner class
         );  // end call to addActionListener
    // Exit menu item ////////////////////////////////////////////////////////////////////
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'x' );
         file.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //create Button Enter
    Enter = new JButton("Enter");
    Enter.addActionListener(
              new ActionListener()     {
                              public void actionPerformed( ActionEvent event )
                        StringBuffer a = new StringBuffer();
                        StringBuffer b = new StringBuffer();
                        StringBuffer c = new StringBuffer();
                        for(int i= 0; i< victor.size(); i++){
                        b.append(victor.elementAt(i));
                        b.append("; ");
                        a.append(nameInput.getText());
                        c.append(part1.getText());
                        //System.out.println(a);
                        //System.out.println(b);
                        //System.out.println(c);
                        InsertRecipe f = new InsertRecipe(a,b,c);
                        //invalidate();
                //fileMenu.updateUI();
               // fileMenu.revalidate();
    //create Button Remove
    Remove = new JButton("Remove");
    //add Actionlistener
    Remove.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
    int[] arr;
    arr = printList.getSelectedIndices();
    int counter = 0;
         for (int i= 0; i< arr.length; i++){
              int n=arr;
              victor.remove(n-counter);
              counter++;
    printList.setListData(victor);
    //create Button Remove
    Browse = new JButton("Browse");
    //create Button Preview
    Preview = new JButton("Clear");
    Preview.addActionListener(
    new ActionListener() {  // anonymous inner class
    // display message dialog when user selects Preview...
    public void actionPerformed( ActionEvent event )
    int result = JOptionPane.showConfirmDialog
                             (null,      "Are you sure to want to clear this form", "Clear?",      JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                             if(result == JOptionPane.YES_OPTION)
                             {TextAreaDemo.clear();
                                  //System.out.println("Recipe Entered");
              }//end of joptionpane
    printList = new JList();
    printList.setVisibleRowCount(9);
    printList.setFixedCellWidth(150);
    printList.setFixedCellHeight(15);
    printList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    newList = new JList();
    newList.setVisibleRowCount(9);
    newList.setFixedCellWidth(150);
    newList.setFixedCellHeight(15);
    newList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    // Initialise Text Areas //
    part1 = new JTextArea( 25, 50);
    part1.setFont(new Font("Courier", Font.BOLD, 12));
    part1.setLineWrap(true);
    part1.setWrapStyleWord(true);
    // JPanels for Layout //
    jp = new JPanel();
    jp1 = new JPanel();
    jp2 = new JPanel();
    jp3 = new JPanel();
    jp4 = new JPanel();
    jp5 = new JPanel();
    final Container c = getContentPane();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
         c.setLayout(gbl);
         gbc.weightx = 0.1;
         gbc.weighty = 0.5;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    add(jp1, gbc, 0, 0, 1, 1);
    gbc.fill = GridBagConstraints.NONE;
    add(jp2, gbc, 0, 1, 1, 1);
    add(jp3, gbc, 1, 0, 2, 2);
    jp1.add(jp4, BorderLayout.CENTER);
    jp2.add(jp, BorderLayout.CENTER);
    bar.add( namePrompt );
    bar.add( nameInput);
    bar.add( fileMenu );
    jp4.setLayout(new BorderLayout());
    jp4.add(title1, BorderLayout.NORTH);
    jp4.add(new JScrollPane( printList), BorderLayout.CENTER);
    jp4.add(Remove, BorderLayout.SOUTH);
    jp.setLayout(new BorderLayout());
    jp.add(pic, BorderLayout.NORTH);
    jp.add(new JScrollPane (newList), BorderLayout.CENTER);
    jp.add(Browse, BorderLayout.SOUTH);
    jp3.setLayout(new BorderLayout());
    jp3.add (title3, BorderLayout.NORTH);
    jp3.add (new JScrollPane(part1), BorderLayout.CENTER);
    //c.addMouseListener(myMouse);
    gbc.anchor = GridBagConstraints.LAST_LINE_END;
    add(jp5, gbc, 2, 3, 1, 1);
    jp5.setLayout(new FlowLayout());
    jp5.add(Preview);
    jp5.add(Enter);
    setSize(770, 620);
         pack();
         setVisible(true);
         setResizable(false);
    private static Vector victor = new Vector();
    public static void printListset(String t) {
         victor.add(t);
    for(int i = 0; i<victor.size(); i++)
    printList.setListData(victor);
    public void add(Component ce, GridBagConstraints constraints, int x, int y, int w, int h) {
                   constraints.gridx = x;
                   constraints.gridy = y;
                   constraints.gridwidth = w;
                   constraints.gridheight = h;
                   getContentPane().add(ce, constraints);
    public static JMenu menus()     {
         // Map Created to Handle JMenuItem Addition //
              Map labelToMenu = new HashMap();
              Map labelToMenu2 = new HashMap();
              Map labelToMenu3 = new HashMap();
              String url = "jdbc:odbc:database";
              Connection con;
              Statement stmt;
                        try     {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch(ClassNotFoundException e)     {
                        System.err.print("Class Not found");
                        String query = "select baseIngred.IngredientType, baseIngred.PrimaryKey FROM baseIngred";
                        String query2 = "select baseIngred.IngredientType, baseIngred.PrimaryKey,"
                        + "subMenu.menuNumber, subMenu.subMenu FROM baseIngred, "
                        + "subMenu WHERE baseIngred.PrimaryKey = subMenu.menuNumber ORDER BY submenu";
                                  String query3 = "select subMenu.subMenu, subMenu.PrimaryNumber,"
                                       + "Ingredient.Ingredient, Ingredient.MenuNumber FROM subMenu, Ingredient"
                        + " WHERE Ingredient.MenuNumber = subMenu.PrimaryNumber ORDER BY PrimaryNumber";
         String query4 = "select Ingredient.Ingredient, Ingredient.MenuNumber FROM Ingredient";
                             try     {
                                       con = DriverManager.getConnection(url, "myLogin", "myPassword");
                                       stmt = con.createStatement();
         // Initial Jmenu added ///////////////////////////////////////////////////////////////
                   ResultSet rs = stmt.executeQuery(query);
                   String[] arr = new String[100];
                   int[] num = new int[200];
                   int[] num2 = new int[200];
                   int counter = 0;
                   int counter2 = 0;
                   while     (rs.next())     {
                                  //String t is set to the value contained in ingredient type
                                  String t = rs.getString("IngredientType");
                                  //map labelToMenu has String t and a new JMenu with the menu
                                  //name contained in t stored in it
                                  labelToMenu.put(t, fileMenu.add(new JMenu(t)));
                                  //an array containing values of the priamry key is produced
                                  num[counter] = rs.getInt("PrimaryKey");
                                  //a counter is incremeted so that upon further
                                  //interations it is stored in a new array field
                                  counter++;
         // Second Jmenu added ////////////////////////////////////////////////////////////////
                   ResultSet rs2 = stmt.executeQuery(query2);
                   while     (rs2.next()) {
                                  //String first is set to the value contained in ingredient type
                                  String first = rs2.getString("IngredientType");
                                  //String second is set to the value contained in subMenu
                                  String second = rs2.getString("subMenu");
                                  //firstlevel looks up item t in the map, and creates a jmenu name as it.
                                  JMenu firstLevel = (JMenu)labelToMenu.get(first);
                                  //handles menu placement by comparing PrimaryKeys with MenuNumbers
                                  // f = rs2.getInt("menuNumber");
                                  num2[counter2] = rs2.getInt("menuNumber");
         for (int nm = 0; nm<num.length; nm++){
                   if (num[nm] == num2[counter2]
                                            //adds the second value to the jmenu with th name stored in t.
                                            labelToMenu2.put(second, (firstLevel.add(new JMenu (second))));
                                       }counter2++;
         // Third JMenu added /////////////////////////////////////////////////////////////////
         ResultSet rs3 = stmt.executeQuery(query3);
              while     (rs3.next()) {
                                  //String next is set to the value contained in subMenu
                                  String next = rs3.getString("subMenu");
                                  //String third is set to the value contained in ingredient
                                  String third = rs3.getString("Ingredient");
                                  JMenu secondLevel = (JMenu)labelToMenu2.get(next);
                                  int f2 = rs3.getInt("MenuNumber");
                                  //System.out.println(f2);
                                  int f3 = rs3.getInt("PrimaryNumber");
                   if (f3 == f2){
                             labelToMenu3.put(third, secondLevel.add(new JMenuItem(third)));
         // Add AtionListeners ////////////////////////////////////////////////////////////////
         ResultSet rs4 = stmt.executeQuery(query4);
              while     (rs4.next()) {
                   String third2 = rs4.getString("Ingredient");
         JMenuItem thirdLevel = (JMenuItem)labelToMenu3.get(third2);
         thirdLevel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String actionText = source.getText();
                   PopUp pop = new PopUp(actionText);
                        stmt.close();
                        con.close();
                             }catch(SQLException ex)     {
                        System.err.println(ex);
    return (fileMenu);
         //                                        End Of Connection                                             //
         // Add subMenu menu item /////////////////////////////////////////////////////////////
    public static void clear()     {
    nameInput.setText("");
    victor.removeAllElements();
    printList.setListData(victor);
    part1.setText("");
    public static void rebuild()     {
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );
    public static void main(String args[])     {
         TextAreaDemo t = new TextAreaDemo();
         t.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    the code inside the method 'rebuild()' will work from inside the main JFrame body if assigned to a button (such as the example position denoted by HERE in the code), but that is undesirable as it requires the user to refresh manually every time they add a new ingredient. what i need is a method that can be called from another class/method/whatever.
    thankyou for any help you can offer, it is much appreciated

    The code you offered did not solve my problem. I have since entered the followinginto the actionlistener of a button on the JFrame,
    refreshMenu = new JButton("Refresh Menu");
    refreshMenu.addActionListener(
             new ActionListener() { 
                // display message dialog when user selects Preview...
                public void actionPerformed( ActionEvent event )
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );          
    );This does what i need, but i need these statements to be made from an external class, not a JButton,

  • JPopupMenu with a submenu (doesn't work)

    I have a JPopupMenu that displays some info for me and I would like to add a submenu but it doesn't seem to work. I can successfully add the submenu but it doesn't "expand" when I mouse over the submen.
    JPopupMenu pm = new JPopupMenu();
    JMenu submenu = new JMenu("submenu");
    JMenuItem jmi = new JMenuItem(...);
    submenu.add(jmi);
    pm.add(submenu);The popup menu looks as it should and the only thing that is missing is the action that should expand the submenu when I mouse over (and clicking doesn't work either).
    Any ideas?

    I don't think it is my code because I have tried it with other JPopupMenu stuff and it never works. Here is a simple working example of it. If you can modify this code to work I will be a bielver...
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    public class PopUpMenuTest extends JPanel implements MouseListener, MouseMotionListener {
       private JPopupMenu jpm;
       private JFrame frame;
       public PopUpMenuTest() {
          super();
          addMouseListener(this);
          addMouseMotionListener(this);
          JFrame.setDefaultLookAndFeelDecorated(true);
          frame = new JFrame("Testing PopUpMenuTest");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setContentPane(this);
          frame.setSize(600, 400);
          frame.setVisible(true);
       public static void main(String[] args) {
          new PopUpMenuTest();
       public void mouseClicked(MouseEvent me) {
          System.out.println("Mouse clicked...");
          jpm = new JPopupMenu();
          jpm.setLightWeightPopupEnabled(false);
          jpm.add(new JMenuItem("Testing 1"));
          jpm.add(new JMenuItem("Testing 2"));
          jpm.addSeparator();
          JMenu submenu = new JMenu("A submenu");
          JMenuItem menuItem1 = new JMenuItem("An item in the submenu");
          submenu.add(menuItem1);
          JMenuItem menuItem2 = new JMenuItem("Another item");
          submenu.add(menuItem2);
          jpm.add(submenu);
          jpm.setVisible(true);
          jpm.setLocation(frame.getX()+me.getX(), frame.getY()+me.getY());
          jpm.setVisible(true);
       public void mouseMoved(MouseEvent arg0) {
          if (jpm != null) {
             jpm.setVisible(false);
             jpm = null;
       public void mouseEntered(MouseEvent arg0) {}
       public void mouseExited(MouseEvent arg0) {}
       public void mousePressed(MouseEvent arg0) {}
       public void mouseReleased(MouseEvent arg0) {}
       public void mouseDragged(MouseEvent arg0) {}
    }

  • How do I force JMenu not to open but to forward the click

    Hi!
    I'm working on a swing application. To control it I use a JMenuBar as a container which contains several JMenu items. I do not use JMenuItems at all!
    When I click on such a JMenu the click is forwarded using a MenuListener - that all works without any problem.
    When I click on one of those items it is activated just like I would use a submenu with it. Just like clicking on "File" at regular applications and moving the mouse in a horizontal way I can just by moving the mouse using the other JMenu's. I don't want that, I just want to click them without them to become marked or activated in a way!
    How can I change that?
    Thank you in advance!

    Just like
    clicking on "File" at regular applications and moving
    the mouse in a horizontal way I can just by moving
    the mouse using the other JMenu's. I'm not sure I understand just exactly what you mean by this. Do you mean that when you click on the File menu,
    and by moving the mouse across the menu bar, the other menus are activated (focus given to the menu over
    which the mouse hovers)?
    Is this what you are referring to?
    Reformer!

  • Is it possible to change the default border on a JMenu?

    Hello,
    I'm working on an application that has a simple menu system. Clicking a button opens a JPopupMenu, which contains JMenu and JMenuItem objects. I want to change the border on the JPopupMenu and its JMenu submenus to a simple line border. Calling setBorder on the JPopupMenu works just fine, but calling it on JMenu doesn't change the border. The following code illustrates my point.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MenuTest {
       JFrame f;
       JPanel p;
       JPopupMenu popup;
       JMenu mainMenu;
       JMenu subMenu;
       JButton showPopupButton;
       public MenuTest()
          f = new JFrame("Popup Menu Test");
          p = new JPanel();
          popup = new JPopupMenu();
          subMenu = new JMenu("Submenu");
          mainMenu = new JMenu("Main Menu");
          JMenuItem m;
          for (int i=0; i < 3; i++) {
             m = new JMenuItem("Submenu item " + i);
             subMenu.add(m);
          // This doesn't work.  The border remains set to the default Windows bevel.
          subMenu.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          popup.add(subMenu);
          for (int i=0; i < 5; i++) {
             m = new JMenuItem("Main menu item " + i);
             popup.add(m);
          showPopupButton = new JButton("Show Popup");
          showPopupButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e)
                Component c = (Component) e.getSource();
                popup.show(c, 0, c.getHeight());
          p.add(showPopupButton);
          // This works.  It sets the border of the popup menu to a black line border.
          popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          f.getContentPane().add(p);
          f.setSize(400, 300);
          f.setVisible(true);
       public static void main(String[] args)
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch (Exception e) { }
          new MenuTest();
    }Any ideas? Do I have to extend JMenu and do some custom painting to accomplish this? I'd also like to change the roll-over color on the menu items, but neither JMenu nor JPopupMenu seem to support that. It looks like borders and rollover colors are L&F dependent.
    Thanks in advance for any help.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Example {
        public static void main(String[] args)  throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("MenuItem.selectionForeground", Color.GREEN);
            UIManager.put("MenuItem.selectionBackground", Color.BLACK);
            JMenuBar mb = new JMenuBar();
            Border border = BorderFactory.createRaisedBevelBorder();
            JMenu file = new BorderedMenu("File", border);
            file.add(new JMenuItem("New"));
            file.add(new JMenuItem("Open"));
            file.add(new JMenuItem("Close"));
            JMenu edit = new BorderedMenu("Edit", border);
            edit.add(new JMenuItem("Cut"));
            edit.add(new JMenuItem("Paste"));
            edit.add(new JMenuItem("Copy"));
            mb.add(file);
            mb.add(edit);
            JFrame f = new JFrame("Example");
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static class BorderedMenu extends JMenu {
            private Border border;
            public BorderedMenu(String text, Border border) {
                super(text);
                this.border = border;
            public JPopupMenu getPopupMenu() {
                JPopupMenu p = super.getPopupMenu();
                p.setBorder(border);
                return p;
    }By the way, I find the following program handy when snooping around the UI defaults.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class Listing {
        public static void main(String[] args) throws Exception {
            UIDefaults defs = UIManager.getLookAndFeelDefaults();
            ArrayList list = new ArrayList();
            for(Iterator i = defs.entrySet().iterator(); i.hasNext(); ) {
                Map.Entry entry = (Map.Entry) i.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Color)
                    list.add(key);
            Collections.sort(list);
            JPanel panel = new JPanel(new GridLayout(0,1));
            String lastCompName = "";
            for(int i=0; i<list.size(); ++i) {
                Object key = list.get(i);
                String text = key.toString();
                int dotIndex = text.indexOf('.');
                String compName = text.substring(0, dotIndex > 0 ? dotIndex : text.length());
                if (!compName.equals(lastCompName)) {
                    lastCompName = compName;
                    panel.add(new JLabel());
                Color color = defs.getColor(key);
                JLabel label = new JLabel(text, new ColorIcon(color), JLabel.LEFT);
                panel.add(label);
            JFrame f = new JFrame("Listing");
            f.getContentPane().add(new JScrollPane(panel));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setSize(f.getWidth(), 600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class ColorIcon implements Icon {
        public static final int ICON_WIDTH = 20;
        public static final int ICON_HEIGHT = 16;
        private Color color;
        public ColorIcon(Color color) {
            this.color = color;
        public int getIconWidth() {
            return ICON_WIDTH;
        public int getIconHeight() {
            return ICON_HEIGHT;
        public void paintIcon(Component c, Graphics g, int x, int y) {
            if (color != null) {
                Color old = g.getColor();
                g.setColor(color);
                g.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
                g.setColor(Color.BLACK);
                g.drawRect(x, y, ICON_WIDTH-1, ICON_HEIGHT-1);
                g.setColor(old);
    }

  • MouseEvents are not triggered for JMenu

    I would like to listen for MouseEvents but i'm not sure if it is a bug in java or some lack of knowledge on my side concerning event handling.
    I have a simple menu with one mouse listener and seems that mouseReleased and mouseClicked events are not triggered always as i would expect.
    if i run the code that has been attached below, than i have the following strange scenarios.
    Menu0 is not opened and click on it once:
    pressed Menu0
    clicked Menu0
    There is no mouseReleased received. why?
    Menu0 is opened and click on it once again:
    pressed Menu0
    released Menu0
    clicked Menu0
    Menu0 is collapsed and i have all the events. ok
    Menu0 is opened and click on Menu1:
    pressed Menu1
    released Menu1
    Menu0 is collapsed and there is no mouseClicked event. why?
    Menu0 is opened and go over Menu2 and click on it:
    pressed Menu2
    clicked Menu2
    There is no mouseReleased event. why?
    Press the mouse over Menu2 and release it over Menu3:
    pressed Menu2
    released Menu2
    why is it 'released Menu2' and not 'released Menu3' if it is pressed and released Menu2 than where is the clicked event anyway.
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MouseEventTest
         public static void main( String[] args )
              JFrame frame;
              JMenuBar menuBar;
              JMenu menu, subMenu;
              JMenuItem menuItem;
              MouseListener mouseListener;
              mouseListener = new MouseAdapter() {
                   public void mouseEntered( MouseEvent e )
                   public void mouseExited( MouseEvent e )
                   public void mouseClicked( MouseEvent e )
                        System.err.println( "clicked " + ((JMenuItem) e.getSource()).getText());
                   public void mousePressed( MouseEvent e )
                        System.err.println( "pressed " + ((JMenuItem) e.getSource()).getText());
                   public void mouseReleased( MouseEvent e )
                        System.err.println("released " + ((JMenuItem) e.getSource()).getText());
              menuBar = new JMenuBar();
              menu = new JMenu( "Menu0" );
              menu.addMouseListener( mouseListener );
              menuBar.add( menu );
              menuItem = new JMenuItem( "Menu1" );
              menuItem.addMouseListener( mouseListener );
              menu.add( menuItem );
              subMenu = new JMenu( "Menu2" );
              subMenu.addMouseListener( mouseListener );
              menu.add( subMenu );
              menuItem = new JMenuItem( "Menu3" );
              menuItem.addMouseListener( mouseListener );
              subMenu.add( menuItem );
              menuItem = new JMenuItem( "Menu4" );
              menuItem.addMouseListener( mouseListener );               
              subMenu.add( menuItem );
              frame = new JFrame();
              frame.setTitle( "MouseEvent test for JMenu" );
              frame.setBounds( 320, 240, 320, 240 );
              frame.setJMenuBar( menuBar );
              frame.addWindowListener( new WindowAdapter() {
                   public void windowClosing( WindowEvent e ) {
                        System.exit(0);
              frame.setVisible( true );
    }

    Well there are differences across Operating Systems. For example I'm using JDK1.4.2 on XP. When I click on Menu0 I get:
    pressed Menu0
    released Menu0
    clicked Menu0
    It is always better to use a "higher" level event when possible. In this case you should be using an ActionListener, if you want to know when a menu or menuItem is clicked. Or maybe you could use a MenuListener to know when a menu is opened and closed.

Maybe you are looking for

  • Error Query for Crystal Report

    Hi Everyone       I have an error with my Crystat Reports state = "TOR"         If rdo_WSO.Checked = True Then             With Frm_Print                 .strReport = "Filter"                 .strWhere = "{TblTORGrad.TORWithoutSO} = '' and {TblTORGra

  • Wireless trackpad

    Hello, My wireless trackpad looses its connection with my iMac every now and then. I have to switch it off for a few moments then switch it back on again and it works OK. What causes this and can it be rectified? Seasons greetings to you all. Roger24

  • MacAir 10.7.3 share Time Machine with iMac 10.4.11?

    Will the "sharing" feature allow me to use Time Machine on my iMac OS 10.4.11 if I use my MacAir OS 10.7.3 as a base? (I know that Time Machine is not compatible with my iMac 10.4.11 by itself).

  • How to reduce render time?

    I have created two separate events in FCP X that are both completely done and fully rendered.  I now want to combine them onto one timeline and then send them to Compressor to burn a DVD for a client.  It is frustrating to have to wait for this new 3

  • The requested file was not a valid font file

    I have a serius problem with OTF fonts shipped with CS3 collection. I had to reinstall windows to solve this issue a couple of months ago and now it's bugging me again. When I double click on Minion (or other adobe OTF fonts) in fonts (control panel)