JMenu, passing mnemonic/ keyevent

Hi
Im building a JMenu but as it has many items im using a function to make each JMenuItem. The function calls the JMenu constructor with the text and the image to be used. I want to pass the mnemonic but can't work out how to do it.
//example of function call
menu1.add(add("myText","myPic.gif"));
//what i need to send to function
menuItem.setMnemonic(KeyEvent.VK_T);also is it possible to do the same with accelerators, ie pass this info to the function
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.ALT_MASK));thanks

Okay, it's still not clear to me what you're trying it write, but is it a method like the following?
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class Blank implements ActionListener {
    static JMenuItem add(JMenu menu, ActionListener al, String text, int mnemonic, String keyStoke, String iconURL) {
        JMenuItem item = new JMenuItem(text);
        if (al != null)
            item.addActionListener(al);
        if (mnemonic != 0)
            item.setMnemonic(mnemonic);
        if (keyStoke != null)
            item.setAccelerator(KeyStroke.getKeyStroke(keyStoke));
        try {
            if (iconURL != null)
                item.setIcon(new ImageIcon(new URL(iconURL)));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        return menu.add(item);
    public void actionPerformed(ActionEvent evt) {
        System.out.println("your code here");
    public static void main(String[] args) {
        JMenuBar mb = new JMenuBar();
        JMenu menu = new JMenu("menu");
        add(menu, new Blank(), "blank", KeyEvent.VK_K, "control B", "http://forum.java.sun.com/im/ic_eye.gif");
        add(menu, null, "zip", 0, null, null);
        mb.add(menu);
        final JFrame f = new JFrame("Blank");
        f.setJMenuBar(mb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                f.setLocationRelativeTo(null);
                f.setVisible(true);
}

Similar Messages

  • How to pass a KeyEvent to a JTextPane?

    Hi,
    I have a JTextPane and I display a JPopupMenu on top of it. The menu implements a MenuKeyListener to catch typed text and filters the menu content based on the typed text.
    I also need to insert the typed characters into the document in the underlying JTextPane. So, I have a KeyEvent (MenuKeyEvent actually) and I need to make the JTextPane to process it as if it was produced by the user, i.e. match it against the action map and do the document edit for me.
    I tried to call the JTextPane.processKeyEvent(e) method but it doesn't work. Any hints?
    Thanks a lot!
    Robert

    Well, I'm wondering if it isn't working because the event is already consumed?
    Perhaps you can construct a duplicate KeyEvent and pass that along instead?
    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 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.

  • How to pass the KeyEvent from one component to other

    I am able to get a key event for a scroll bar from that scroll bars key listener. Now i want to pass this key event to another components key listener. How can i do this.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyCommunication
        public static void main(String[] args)
            final JScrollBar
                left  = new JScrollBar(JScrollBar.VERTICAL),
                right = new JScrollBar(JScrollBar.VERTICAL);
             * if KeyEvent originates with left, forwards KeyEvent to right
            left.addKeyListener(new KeyAdapter()
                public void keyPressed(KeyEvent e)
                    int keyCode = e.getKeyCode();
                    int direction = 0;
                    if(keyCode == KeyEvent.VK_UP)
                        direction = -1;
                    if(keyCode == KeyEvent.VK_DOWN)
                        direction = 1;
                    left.setValue(left.getValue() +
                                  left.getBlockIncrement(direction) * direction);
                    if(e.getSource() == left)
                        right.dispatchEvent(e);
             * forwards KeyEvent to left scrollbar if KeyEvent originates here
            right.addKeyListener(new KeyAdapter()
                public void keyPressed(KeyEvent e)
                    int keyCode = e.getKeyCode();
                    int direction = 0;
                    if(keyCode == KeyEvent.VK_UP)
                        direction = -1;
                    if(keyCode == KeyEvent.VK_DOWN)
                        direction = 1;
                    right.setValue(right.getValue() +
                                   right.getBlockIncrement(direction) * direction);
                    if(e.getSource() == right)
                        left.dispatchEvent(e);
             * paints track of focused scrollbar blue
             * use tab key for navigation between scrollbars
            FocusListener l = new FocusListener()
                Color bgColor = UIManager.getColor("ScrollBar.background");
                public void focusLost(FocusEvent e)
                    JScrollBar scrollBar = (JScrollBar)e.getSource();
                    scrollBar.setBackground(bgColor);
                    scrollBar.repaint();
                public void focusGained(FocusEvent e)
                    JScrollBar scrollBar = (JScrollBar)e.getSource();
                    scrollBar.setBackground(Color.blue);
                    scrollBar.repaint();
            left.addFocusListener(l);
            right.addFocusListener(l);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(10,0,10,0);
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = gbc.VERTICAL;
            panel.add(left, gbc);
            panel.add(right, gbc);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • GUI building difficulties, nested Frames and other stuff

    I am currently working on a GUI and I am running into some difficulties. I have created a class which extends JFrame
    public class DelFace extends JFrame implements ActionListener, ItemListenerI am instantiating an object of this class from within another object of a different class as follows:
    DelFace DelGUI = new DelFace(this,MastFile);The creation of the object takes place within the listener methods of another object:
    public void actionPerformed(ActionEvent e)
      if(e.getActionCommand().equals("Delete"))
          DelFace DelGUI = new DelFace(this,MastFile);
      }The class that creates the object that makes this call does not contain the main method. Instead the afore mentioned object is created from a class that extends JFrame
    class GUI extends JFrame implements ActionListenerSo the code in it's order of activity is as follows:
    It breaks down hardcore at the beginning
    public class StartProgram {
      private static GUI LauncherGUI;
      private static FileOps MastFile;
      public static void main(String[] args)
      MastFile = new FileOps();
      MastFile.fileStatus();            //Create File object &/or file.
      MastFile.readFile();              //Read file contents if any.
      LauncherGUI = new GUI(StartProgram.MastFile);
    }A GUI object is created, - LauncherGUI = new GUI(StartProgram.MastFile);
    From here the code differentiates somewhat - FileOperations stem from here as do all code related to the complete construction of the General User Interface.
    Specifically my difficulties lie with the GUI, therefore I will present the next peice of code related to the GUI. The following code creates a JFrame and places a whole stack of buttons on it. Included with these buttons are menus. So basically the code creates a menu bar and adds menu items to that bar and so on until a menu similar to that found in any regular program is produced. Also contained on this part of the GUI are the five buttons that are fundemental to the programs operation.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.EventObject; //Try removing this!!
    class GUI extends JFrame implements ActionListener
      private JButton button1;
      private JButton button2;
      private JButton button3;
      private JButton button4;
      private JButton button5;
      private String Path1;
      private String Path2;
      private String Path3;
      private String Path4;
      private String Path5;
      private FileOps MastFile;
      private DataEntryBox EntryBox;
      private HelpGUI Instruct;
      FrameListener GUIListener = new FrameListener();  //Listener object created.
      GUI(FileOps MastFile)
        this.MastFile = MastFile;          //Make MastFile objects methods available
                                           //to all of LauncherGUI object.
        Toolkit tk = Toolkit.getDefaultToolkit();       //intialize the toolkit.
        Dimension sSize = tk.getScreenSize();           //determine screen size.
        Container c = getContentPane();
        GridBagLayout gridbag2 = new GridBagLayout();    //GridBagLayout object
                                                        //instantiated.
        GridBagConstraints d = new GridBagConstraints();//GridBagConstraints object
                                                        //instantiated.
        c.setLayout(gridbag2);                          //Content pane's layout set
                                                        //to gridbag object.
        d.fill = GridBagConstraints.BOTH;               //Make all components fill
                                                        //their dispaly areas
                                                        //entirely.
        d.insets = new Insets(5,1,5,1);
        JMenuBar menuBar = new JMenuBar();  //Creates Menubar object called menuBar.
        setJMenuBar(menuBar);
        JMenu FMenu = new JMenu("File");    //File Menu object instantiated.
        FMenu.setMnemonic(KeyEvent.VK_F);   //Key that activates File menu...F.
        menuBar.add(FMenu);                 //File Menu added to menuBar object.
        JMenuItem NewItem = new JMenuItem("New");   //Creates New sub-menu object.
        NewItem.setMnemonic(KeyEvent.VK_N);         //Key that activates New sub-
                                                    //menu....N.
        FMenu.add(NewItem);
        NewItem.addActionListener(this);   //ActionListner for NewItem added.
        //Tutorial Note: Steps involved in creating a menu UI are as follows,
        //1). Create an instance of a JMenuBar.
        //2). Create an instance of a JMenu.
        //3). Add items to the JMenu (not to the JMenuBar).
        //Note: It is possible to include the Mnemonic activation key as part of
        //the JMenu or JMenuItem constructor. e.g.: JMenuItem NewItem = new JMenu
        //Item("New",KeyEvent.VK_N);
        JMenuItem DeleteItem = new JMenuItem("Delete");
        DeleteItem.setMnemonic(KeyEvent.VK_D);
        FMenu.add(DeleteItem);
        DeleteItem.addActionListener(this);
        JMenuItem ExitItem = new JMenuItem("Exit",KeyEvent.VK_E); //Mnemonic key
        //included with constructor method here and from now on.
        FMenu.add(ExitItem);
        ExitItem.addActionListener(this);
        JMenu HMenu = new JMenu("Help");
        HMenu.setMnemonic(KeyEvent.VK_H);
        menuBar.add(HMenu);
        JMenuItem InstructItem = new JMenuItem("Instructions",KeyEvent.VK_I);
        HMenu.add(InstructItem);
        InstructItem.addActionListener(this);
        JMenuItem AboutItem = new JMenuItem("About",KeyEvent.VK_A);
        HMenu.add(AboutItem);
        AboutItem.addActionListener(this);
        button1 = new JButton();
    /* The following if statments block first checks to see if the value held in the
    String array is equals to null (note: this only occurs when the program is first
    started and no data has been written to file). If the array is null then the
    buttons text is set to "". If the array value is not null (meaning that the file
    already holds data) then the value of the array is checked. If the value equals
    the String "null" then button text is set to "", otherwise button text is set to
    the relevant array value (a user defined shortcut name). Also the value of each
    buttons actionCommand is set to this string value. */
        if(MastFile.getFDArray(0) == null)
          button1.setText("");
          button1.setActionCommand("Link1");
        else
        if(MastFile.getFDArray(0) != null)
          if(MastFile.getFDArray(0).equals("null"))
            button1.setText("");
            button1.setActionCommand("Link1");
          else
            button1.setText(MastFile.getFDArray(0));
            button1.setActionCommand(MastFile.getFDArray(0));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 0;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button1, d);
        c.add(button1);
        button1.addActionListener(this);
        button2 = new JButton();
        if(MastFile.getFDArray(2) == null) //If the file contains no contents then..
          button2.setText("");
          button2.setActionCommand("Link2");
        else
        if(MastFile.getFDArray(2) != null)
          if(MastFile.getFDArray(2).equals("null"))//If the file contains the string
          {                                        //"null" then do as above.
            button2.setText("");
            button2.setActionCommand("Link2");
          else  //Set both button text and actionCommand to relevant shortcut name.
            button2.setText(MastFile.getFDArray(2));
            button2.setActionCommand(MastFile.getFDArray(2));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 1;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button2, d);
        c.add(button2);
        button2.addActionListener(this);
        button3 = new JButton();
        if(MastFile.getFDArray(4) == null)
          button3.setText("");
          button3.setActionCommand("Link3");
        else
        if(MastFile.getFDArray(4) != null)
          if(MastFile.getFDArray(4).equals("null"))
            button3.setText("");
            button3.setActionCommand("Link3");
          else
            button3.setText(MastFile.getFDArray(4));
            button3.setActionCommand(MastFile.getFDArray(4));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 2;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button3, d);
        c.add(button3);
        button3.addActionListener(this);
        button4 = new JButton();
        if(MastFile.getFDArray(6) == null)
          button4.setText("");
          button4.setActionCommand("Link4");
        else
        if(MastFile.getFDArray(6) != null)
          if(MastFile.getFDArray(6).equals("null"))
            button4.setText("");
            button4.setActionCommand("Link4");
          else
            button4.setText(MastFile.getFDArray(6));
            button4.setActionCommand(MastFile.getFDArray(6));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 3;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button4, d);
        c.add(button4);
        button4.addActionListener(this);
        button5 = new JButton();
        if(MastFile.getFDArray(8) == null)
          button5.setText("");
          button5.setActionCommand("Link5");
        else
        if(MastFile.getFDArray(8) != null)
          if(MastFile.getFDArray(8).equals("null"))
            button5.setText("");
            button5.setActionCommand("Link5");
          else
            button5.setText(MastFile.getFDArray(8));
            button5.setActionCommand(MastFile.getFDArray(8));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 4;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button5, d);
        c.add(button5);
        button5.addActionListener(this);
        Path1 = MastFile.getFDArray(1);       //Load Path variables with path
        Path2 = MastFile.getFDArray(3);       //details from String Array in
        Path3 = MastFile.getFDArray(5);       //MastFile object of FileOps class.
        Path4 = MastFile.getFDArray(7);       //Effectively loading these variables
        Path5 = MastFile.getFDArray(9);       //with file data.
        this.addWindowListener(GUIListener);  //Listener registered with Frame.
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*1/7);
        setTitle("Java QuickLaunch Toolbar");
        setVisible(true);
      /* The following methods return the ActionCommand and Text Label
         String values of the buttons */
      public String getButton1Command()
        return button1.getActionCommand();
      public String getButton2Command()
        return button2.getActionCommand();
      public String getButton3Command()
        return button3.getActionCommand();
      public String getButton4Command()
        return button4.getActionCommand();
      public String getButton5Command()
        return button5.getActionCommand();
      public String getBt1Text()
        return button1.getText();
      public String getBt2Text()
        return button2.getText();
      public String getBt3Text()
        return button3.getText();
      public String getBt4Text()
        return button4.getText();
      public String getBt5Text()
        return button5.getText();
      /* The following methods set the Path, Button and ActionCommand String values. */
      public void setPath1(String setPath)
        Path1 = setPath;
      public void setPath2(String setPath)
        Path2 = setPath;
      public void setPath3(String setPath)
        Path3 = setPath;
      public void setPath4(String setPath)
        Path4 = setPath;
      public void setPath5(String setPath)
        Path5 = setPath;
      public void setButton1(String setButton)
        button1.setText(setButton);
      public void setButton2(String setButton)
        button2.setText(setButton);
      public void setButton3(String setButton)
        button3.setText(setButton);
      public void setButton4(String setButton)
        button4.setText(setButton);
      public void setButton5(String setButton)
        button5.setText(setButton);
      public void setBt1Action(String setAct)
        button1.setActionCommand(setAct);
      public void setBt2Action(String setAct)
        button2.setActionCommand(setAct);
      public void setBt3Action(String setAct)
        button3.setActionCommand(setAct);
      public void setBt4Action(String setAct)
        button4.setActionCommand(setAct);
      public void setBt5Action(String setAct)
        button5.setActionCommand(setAct);
      /* actionPerformed methods */
      public void actionPerformed(ActionEvent e)
        if(e.getActionCommand().equals("New"))
          //Create a data entry box.
          EntryBox = new DataEntryBox(this,MastFile);
        else
        if(e.getActionCommand().equals("Delete"))//Example part of interest
          DelFace DelGUI = new DelFace(this,MastFile);   /// -------- ////
        else
        if(e.getActionCommand().equals("Exit"))
          System.exit(0);
        else
        if(e.getActionCommand().equals("Instructions"))
          Instruct = new HelpGUI();
        else
        if(e.getActionCommand().equals("About"))
          JOptionPane.showMessageDialog(this,"Java QuickLaunch Toolbar created by David "+
                                        "Dartnell.","Programming Credits",1);
        else
          if(e.getActionCommand().equals(button1.getActionCommand())) //Determine source of event.
          if(Path1 == null)                        //If Path var is a null reference
            EntryBox = new DataEntryBox(this,MastFile);//create a data entry box.
          else
          if(Path1 != null)                        //If not a null reference then...
            if(Path1.equals("null"))               //Determine if string is "null".
              EntryBox = new DataEntryBox(this,MastFile);
            else        //If both the reference and the String are not null then run
            {           //the relevant command/program.
              try
                Runtime.getRuntime().exec(new String[]{Path1});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button2.getActionCommand()))
          if(Path2 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path2 != null)
            if(Path2.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path2});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button3.getActionCommand()))
          if(Path3 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path3 != null)
            if(Path3.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path3});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button4.getActionCommand()))
          if(Path4 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path4 != null)
            if(Path4.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path4});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button5.getActionCommand()))
          if(Path5 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path5 != null)
            if(Path5.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path5});
              catch(IOException run){}
    Something to consider concerning actionListeners:
    It must be remembered that String values are in fact objects and as such
    they require the equals() method unlike their cousins the primitive data
    types (int, float, boolean, byte, short, long and double) which require
    the == operator.
    */A comment is placed next to the line of code that is of interest to my problem (///-------////).
    When a button is pressed in the menu section that reads "Delete" then an actionCommand event is fired and the program responds by creating a second general user interface.
    When DelFace is instantiated in the form of the object called DelGUI I am once again creating an object which extends JFrame. I now have two objects of type JFrame on the screen at once, and I conveniently position one over the top of the other, so to the general user the programs appearance has changed in only very specified ways (i.e.: I have decided to increase the GUI's dimensions in the area of height only and not width). The code that constitutes class DelFace is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DelFace extends JFrame implements ActionListener, ItemListener
      private GUI TkBar;        //GUI object.
      private FileOps Fops;     //File Operations object.
      private JCheckBox ckbox1; //Delete shortcut 1.
      private JCheckBox ckbox2; //Delete shortcut 2.
      private JCheckBox ckbox3; //Delete shortcut 3.
      private JCheckBox ckbox4; //Delete shortcut 4.
      private JCheckBox ckbox5; //Delete shortcut 5.
      private JButton OkBtn;    //OK button.
      private JButton CnBtn;    //Cancel button.
      private JOptionPane confirm;
      private boolean short1 = false;  //Boolean variables indicate whether to
      private boolean short2 = false;  //delete a shortcut entry. True = delete.
      private boolean short3 = false;
      private boolean short4 = false;
      private boolean short5 = false;
      DelFace(GUI TkBar, FileOps Fops)
        this.TkBar = TkBar;
        this.Fops = Fops;
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension sSize = tk.getScreenSize();
        Container dcon = getContentPane();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints bagcon = new GridBagConstraints();
        dcon.setLayout(gb);
        bagcon.fill = GridBagConstraints.BOTH;
        bagcon.gridwidth = GridBagConstraints.REMAINDER;
        JLabel TLabel = new JLabel("Delete Wizard",JLabel.CENTER);
        TLabel.setFont(new Font("Tahoma",Font.BOLD+Font.ITALIC,32));
        bagcon.gridx = 0;
        bagcon.gridy = 0;
        bagcon.weightx = 1.0;      //Take up all the 'x room' in this row.
        bagcon.weighty = 0.5;      //Take up all the 'y room' in this column.
        /* The weightx and weighty values are required otherwise all components will
           gravitate toward the center of screen. */
        gb.setConstraints(TLabel,bagcon);
        dcon.add(TLabel);
        JTextArea TxArea = new JTextArea("Tick the box(s) of the shortcut(s)"+
                               " that you would like to delete and"+
                               " press the Delete button. Alternatively"+
                               " press the Cancel button to exit.");
        TxArea.setLineWrap(true);
        TxArea.setWrapStyleWord(true);
        TxArea.setEditable(false);
        TxArea.setFont(new Font("Times New Roman",Font.PLAIN,15));
        TxArea.setBackground(this.getBackground());
        bagcon.gridx = 0;
        bagcon.gridy = 1;
        gb.setConstraints(TxArea,bagcon);
        dcon.add(TxArea);
        bagcon.gridwidth = 1;
        JPanel Nopan1 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 2;
        gb.setConstraints(Nopan1,bagcon);
        dcon.add(Nopan1);
        ckbox1 = new JCheckBox(TkBar.getBt1Text());
        bagcon.gridx = 1;
        bagcon.gridy = 2;
        gb.setConstraints(ckbox1,bagcon);
        dcon.add(ckbox1);
        ckbox1.addItemListener(this);
        ckbox2 = new JCheckBox(TkBar.getBt2Text());
        bagcon.gridy = 3;
        gb.setConstraints(ckbox2,bagcon);
        dcon.add(ckbox2);
        ckbox2.addItemListener(this);
        ckbox3 = new JCheckBox(TkBar.getBt3Text());
        bagcon.gridy = 4;
        gb.setConstraints(ckbox3,bagcon);
        dcon.add(ckbox3);
        ckbox3.addItemListener(this);
        ckbox4 = new JCheckBox(TkBar.getBt4Text());
        bagcon.gridy = 5;
        gb.setConstraints(ckbox4,bagcon);
        dcon.add(ckbox4);
        ckbox4.addItemListener(this);
        ckbox5 = new JCheckBox(TkBar.getBt5Text());
        bagcon.gridy = 6;
        gb.setConstraints(ckbox5,bagcon);
        dcon.add(ckbox5);
        ckbox5.addItemListener(this);
        JPanel Nopan2 = new JPanel();
        bagcon.gridx = 1;
        bagcon.gridy = 7;
        gb.setConstraints(Nopan2,bagcon);
        dcon.add(Nopan2);
        OkBtn = new JButton("OK");
        OkBtn.addActionListener(this);
        bagcon.gridx = 1;
        bagcon.gridy = 8;
        gb.setConstraints(OkBtn,bagcon);
        dcon.add(OkBtn);
        OkBtn.addActionListener(this);
        CnBtn = new JButton("Cancel");
        CnBtn.addActionListener(this);
        bagcon.gridx = 2;
        bagcon.gridy = 8;
        gb.setConstraints(CnBtn,bagcon);
        dcon.add(CnBtn);
        CnBtn.addActionListener(this);
        JPanel Nopan3 = new JPanel();
        bagcon.gridx = 3;
        bagcon.gridy = 8;
        gb.setConstraints(Nopan3,bagcon);
        dcon.add(Nopan3);
        JPanel Nopan4 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 9;
        gb.setConstraints(Nopan4,bagcon);
        dcon.add(Nopan4);
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*4/5);
        setTitle("Java QuickLaunch Toolbar");
        setResizable(false);
        setVisible(true);
      public void actionPerformed(ActionEvent e)
      { /*--- Code of INTEREST begins here!!!!!! -------
        if(e.getActionCommand().equals("OK"))   
          if(short1 || short2 || short3 || short4 || short5)
            //confirm = new JOptionPane();
            int n = confirm.showConfirmDialog(this,
                 "Do you really want to delete?","Delete Confirmation",
                 JOptionPane.YES_NO_OPTION);
            if(n == confirm.YES_OPTION)  //Works Fine!
              while(short1 || short2 || short3 || short4 || short5)
                if(short1)
                  TkBar.setBt1Action("Link1");
                  TkBar.setButton1("");
                  TkBar.setPath1("null");
                  Fops.setFDArray(0,"null");
                  Fops.setFDArray(1,"null");
                  short1 = false;
                else
                if(short2)
                  TkBar.setBt2Action("Link2");
                  TkBar.setButton2("");
                  TkBar.setPath2("null");
                  Fops.setFDArray(2,"null");
                  Fops.setFDArray(3,"null");
                  short2 = false;
                else
                if(short3)
                  TkBar.setBt3Action("Link3");
                  TkBar.setButton3("");
                  TkBar.setPath3("null");
                  Fops.setFDArray(4,"null");
                  Fops.setFDArray(5,"null");
                  short3 = false;
                else
                if(short4)
                  TkBar.setBt4Action("Link4");
                  TkBar.setButton4("");
                  TkBar.setPath4("null");
                  Fops.setFDArray(6,"null");
                  Fops.setFDArray(7,"null");
                  short4 = false;
                else
                if(short5)
                  TkBar.setBt5Action("Link5");
                  TkBar.setButton5("");
                  TkBar.setPath5("null");
                  Fops.setFDArray(8,"null");
                  Fops.setFDArray(9,"null");
                  short5 = false;
              Fops.destroyFile();   //Destroy the old (outdated) file.
              Fops.fileStatus();    //Create a new file.
              Fops.writeFile();     //Write updated data to new file.
              setVisible(false);
            if(n == confirm.NO_OPTION)  //** Does not work ***
              System.out.println("No Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION) //** Does not work ***
              System.out.println("Closed Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
        --- Code of interest ENDS here --- */
        else
        if(e.getActionCommand().equals("Cancel"))
          setVisible(false); 
      public void itemStateChanged(ItemEvent f)
        int state = f.getStateChange();
        if(state == ItemEvent.SELECTED)   //If a checkbox has been selected.
          if(f.getItem() == ckbox1)
            short1 = true;
          else
          if(f.getItem() == ckbox2)
            short2 = true;
          else
          if(f.getItem() == ckbox3)
            short3 = true;
          else
          if(f.getItem() == ckbox4)
            short4 = true;
          else
          if(f.getItem() == ckbox5)
            short5 = true;
        if(state == ItemEvent.DESELECTED)  //If a checkbox has been deselected.
          if(f.getItem() == ckbox1)
            short1 = false;
          else
          if(f.getItem() == ckbox2)
            short2 = false;
          else
          if(f.getItem() == ckbox3)
            short3 = false;
          else
          if(f.getItem() == ckbox4)
            short4 = false;
          else
          if(f.getItem() == ckbox5)
            short5 = false;
    }The code that is of interest to my current programming challenge is marked in the above code block like this:
    //*** Code of INTEREST begins here!!!!!! ********** //
    This is where my programming twilight behaviour begins to kick in. From the DelGUI object I now listen to a button event, this event when triggered causes a JOptionPane.showConfirmDialog(), as can be seen in the specified code block above. I make the JOptionPane centered over the DelGUI object ("JFrame No.: 2") which is also centered over the LauncherGUI object ("JFrame No.: 1").
    The program begins to behave quite strangely after the creation of the JOptionPane object called confirm. The JOptionPane is presented on screen without any visiual difficulty but it behaves quite strangely when it's buttons are pressed. The JOptionPane contains three event sources, the YES, NO and Close buttons.
    In my program the YES button causes a set of file operations to take place and then sets the "JFrame No.: 2"(DelGUI) invisible. It does this via the method setVisible(false). "JFrame No.: 2" is effectively the JOptionPane's parent component and as soon as it is setVisible(false) the JOptionPane is also cleared from the screen. I believe from my research that this is the JOptionPane's default behaviour, meaning that as soon as a button or event source is activated the JOptionPane will destroy itself.
    The end of the trail is near, thankyou for reading this if you have got this far, and please carry on....
    The Challenge:
    The program does not behave as desired at the two points in the code commented as such: ** Does not work ***
    if(n == confirm.NO_OPTION)
              System.out.println("No Option is being heard");
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION)
              System.out.println("Closed Option is being heard");
              //confirm.setVisible(false);
            }If the NO_OPTION or the CLOSED_OPTION are pressed then the JOptionPane remains visible. After pressing the JoptionPane's button a second time it will disappear completely. I have tried a number of things in an attempt to work this out. Firstly I have inserted println messages to ensure that the events are being detected. These messages are always displayed whenever either the NO or Close buttons are pressed.
    As these messages are being passed to the Standard Output, twice by the time the JOptionPane has disappeared, I can only assume that the events are being detected.
    In addition to checking the event situation I have attempted to explicity set the JOptionPane invisible, in the form:
    confirm.setVisible(false); The above line of code did not change the situation. Still I need two button clicks for the JOptionPane to display it's default behaviour which is to set itself invisible (or possibly the object is alloted to garbage collection), either way it is no longer on screen. I have also tried this code with no if statements related to NO_OPTION and CLOSE_OPTION. This was done in an attempt to allow the default behaviour to take place. Unfortunately two presses were still required in this situation.
    A forum member mentioned the possibility that two JOptionPanes are being created. I have checked my code and am confident that I have not explicitly created the JOptionPane twice (the code throughout this question should support this).
    Is it possible that two JOptionPanes are being created because of the nature of my code, the fact that there are two JFrames on the screen at once when the JOptionPane is instantiated? I am using the this keyword to specify the parent of the JOptionPan

    Well, I've checked your code and I've seen where is the error.
    In Delface constructor (Delface.java, line 127), you've got this block of code :
    1. OkBtn = new JButton("OK");
    2. OkBtn.addActionListener(this);
    3. bagcon.gridx = 1;
    4. bagcon.gridy = 8;
    5. gb.setConstraints(OkBtn,bagcon);
    6. dcon.add(OkBtn);
    7. OkBtn.addActionListener(this);
    Have a deep look at lines 2 and 7 : you're registering twice an actionListener on this button. Then you're receiving twice the event and it shows two JOptionPanes. In fact, you've also the problem with the 'ok' option, but you don't see it, because the 'n' variable in your event handler is global to your class, then it's shared between the two calls to the event handlers.

  • Reading Forms Key Mappings from java bean - how ?

    I want to be able to invoke key trigger code in a Forms 10g run-time from a java bean (extends BeanWrapper) either by:
    a) using inherited method calls passing the KeyEvent retrieved from my listener, or
    b) dispatching a custom event from the bean with a parameter value which identifies the key trigger to process (not the key code & modifier string).
    On a), I've not been able to identify any method in the BeanWrapper hierarchy tree that might help me do this, and samples like (http://forms.pjc.bean.over-blog.com/categorie-465294.html) seem to imply that no such method exists.
    In terms of b), the oracle.forms.engine.KeyMapTable class seems to be what I want (seems to translate the KeyEvent into a FormAction/string using server settings), but getting a hold of this object through (oracle.forms.engine.Main)getHandler().getApplet() doesn't seem possible.
    How are others invoking eg: key-crerec from a Forms 10g bean component in a way which is sensitive to server key mappings ?
    Thanks in advance for your help.

    I have no experience with KeyEvents in Forms, but if the KeyMapTable class really is the solution, can't you just instantiate one yourself.
    Looking at the constructor it only needs a single argument, the oracle.forms.engine.Runform class. You should be able to get a handle on it with:
    IHandler hander = getHandler();
    if (handler instanceof UICommon) {
        UICommon u = (UICommon)handler;
        // u.getDispatcher() should get oracle.forms.engine.Runform
    }Not sure if it will work, but you can give it a try.
    I love pushing the PJC and Oracle Forms applet to its limits. Not really sure if Oracle intended the PJC framework to do stuff like this, but it sure would have helped if they have JavaDoc about the oracle.forms.* classes

  • Can we call a method from a adapter class?

    Hi
    I have added KeyAdapter class to a textfield now i want to call a method in the outer class from inside the adapter class. I tried but its showing some error,
    public class A
    A()
    TF1.addKeyListener(new KeyAdapter()
    public void keyReleased(KeyEvent e)
    A a=new A();
    ec.chkSalary();                    
    chkSalary()
    can i call the method like this?

    yeah.. i got it.. i just passed that KeyEvent object to the method
    but i did declare that as a char in that method like,
    chkSalary(e) // e is the KeyEvent reference
    and the method is
    chk(char e);
    thats it.
    thank you yaar.

  • How to trap the first key?

    Hello World,
    I am using JTable in that I am using custom TextField as a Editor Component. Now I want to trap the first key pressed in the textfield.
    I am using public boolean editCellAt(int row,int column,EventObject e) method. In this method I get the value of �e� as a null if I press any key. So I can not trap the event here.
    The next try is to putting KeyListener in textfield class, this is also not working because it gets called after EditCellAt method.
    I tried to override the processKeyBinding() method but this seems to trap all the key pressed and not allow me to navigate also.
    Can anybody provide me the solution how I can trap the first key only.
    Thanks in advance,
    Sachin Dare.

    Hello World,
    I am using JTable in that I am using custom TextField
    as a Editor Component. Now I want to trap the first
    key pressed in the textfield.what do you want it for?
    [.. usual l aproaches snipped ]
    The reason this is not working is that JTable uses a very uncommon way to route this first keyEvent: it comes via Jtable.processKeyBindings which first tries to start the edit with it (buggily "forgetting" to pass the keyEvent along...) and if this started the edit it will pass both keyStroke and keyEvent to the editorComponent's processKeyBindings. At his time the editorComponent is part of the container hierarchy.
    So a possible solution (did not try it, though) might be to have a ComponentListener on the editorComponent, set a flag when being added to the table and reset the flag when receiving the first KeyStroke in proocessKeyBinding after the componentEvent. Alternatively, you might try to set/reset the flag as a clientProperty in table.processKeyBindings.
    Greetings
    Jeanette

  • How do I reed a carrige return from a JTextArea

    How do I reed a carrige return from a JTextArea, as i would like to hadel this with a button press event.

    Try adding a keyListener and use the appropriate method to get the key used from the passed in KeyEvent
    public void keyPressed(KeyEvent e) {
    if(e.getKeyStroke() == KeyEvent.VK_ENTER) {
    ... // the rest goes here. Please check this code for it is not tested
    }ICE

  • JMenu Mnemonic in  JApplet not working

    Hi,
    Here is a code in my JApplet, but some how the Mnemonic is not working,
    why??
    I m using jdk1.4.1
    Ashish
    import javax.swing.text.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.awt.*;
    import java.math.*;
    import javax.accessibility.*;
    public class TestMenuApplet extends JApplet
         public void init()
    buildMenu();
         private void buildMenu()
         JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu("File", true);
    JMenu format = new JMenu("Format", true);     
    file.setMnemonic(KeyEvent.VK_F);
    format.setMnemonic(KeyEvent.VK_O);
    JMenuItem back = new JMenuItem("Back");
    JMenuItem close = new JMenuItem("Close");
    JRadioButtonMenuItem single =
    new JRadioButtonMenuItem("Single");
    JRadioButtonMenuItem multi =
    new JRadioButtonMenuItem("Multiple", true);
         ButtonGroup row = new ButtonGroup();
         row.add(single);
         row.add(multi);
    JMenu monthly = new JMenu("Monthly");
    JMenuItem one = new JMenuItem("One", KeyEvent.VK_O);
    JMenuItem two = new JMenuItem("Two");
    JMenuItem test = new JMenuItem("Test");
    menuBar.add(file);
    menuBar.add(format);
    file.add(back);
    file.add(close);
    format.add(single);
    format.add(multi);
    format.addSeparator();
    format.add(monthly);
    format.add(test);
    monthly.add(one);
    monthly.add(two);
    this.setJMenuBar(menuBar);
    My HTML
    <html>
    <HEAD>
    <TITLE>test</title>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="-1">
    </HEAD>
    <BODY >
    This is testing of applet
    <br>
    <!--"CONVERTED_APPLET"-->
    <!-- HTML CONVERTER -->
    <OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = "300" HEIGHT = "300"
    codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-win.cab#Version=1,4,0,0">
    <PARAM NAME = CODE VALUE = "TestMenuApplet.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
    <PARAM NAME="scriptable" VALUE="false">
    <COMMENT>
         <EMBED
    type="application/x-java-applet;version=1.4"
    CODE = "TestMenuApplet.class"
    WIDTH = "300"
    HEIGHT = "300"
    scriptable=false
         pluginspage="http://java.sun.com/products/plugin/index.html#download">
         <NOEMBED>
              </NOEMBED>
         </EMBED>
    </COMMENT>
    </OBJECT>
    <!--
    <APPLET CODE = "TestMenuApplet.class"
    WIDTH = "300"
    HEIGHT = "300"
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    </BODY>
    </html>

    Did you convert your html code to call the sun VM instead of the default browser VM ?
    Use the HtmlConverter.exe to do this passing the html file in argument.
    Denis

  • Question about JMenu.setMNemonic(KeyEvent.VK_alt);

    I have discovered I can enable the alt key Mnemonic on my initial desired JMenuBar JMenu.
    However, I want a second MNemonic option so that when I press alt a second time, it will
    then close that pull down menu.  Is it possible to do this with one method,
    and without resorting to an entire action event that checks for when the menu happens to be open,
    and a second pressing of the alt key?

    Hi,
    This was the outcome of my research.
    I thought of running the app. directly on the Sun server instead of using Exceed emulator (client). I didn't see those warning messages and the mnemonics worked fine.
    To answer my question earlier, warning messages are directly related to the issue of mnemonics not working on the client machine.
    Still looking into why its not working from any client which uses Exceed.
    Thanks,
    Sunil.

  • Problem with Alt , JMenu and Mnemonics

    I have built an application with a JMenuBar containing several JMenu's, the first of which is a File menu. All JMenus and JMenuItems have mnemonics associated with them. When I press the alt key the underlines show and focus appears to be given to the File menu (though it has not dropped down). If I then press a key, for example 'S', that is a mnemonic of the 'Save' jmenuitem in the File menu, the Save action is invoked. This should not occur because the menu has not opened yet.
    The behavior is what I'd expect had an accelerator (Alt+S) been defined for the Save menu item. But I have not defined any accelerators.
    Why does this happen and more importantly, is there a work around?

    Except for the 1st line in jbinit() it's all pretty standard stuff. Here's a snippet of the code:
    public class MainFrame extends JFrame implements ChangeListener {
    JMenuBar jMenuBar1 = new JMenuBar();
    JMenu jMenuFile = new JMenu();
    JMenuItem jMenuFileNew = new JMenuItem();
    JMenuItem jMenuFileSave = new JMenuItem();
    JMenu m_editMenu = new JMenu();
    JMenuItem m_editCutMenuItem = new JMenuItem();
    JMenuItem m_editCopyMenuItem = new JMenuItem();
    JMenuItem m_editPasteMenuItem = new JMenuItem();
    public MainFrame() {
    jbInit();
    //Component initialization
    private void jbInit() {
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false), "repaint");
    // file menu
    jMenuFile.setText("File");
    jMenuFile.setMnemonic(KeyEvent.VK_F);
    jMenuFileNew.setText("New...");
    jMenuFileNew.setMnemonic(KeyEvent.VK_N);
    jMenuFileNew.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileNewSpecial_actionPerformed(e);
    jMenuFileSave.setText("Save");
    jMenuFileSave.setMnemonic(KeyEvent.VK_S);
    jMenuFileSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileSaveSpecial_actionPerformed(e);
    jMenuFile.add(jMenuFileNew);
    jMenuFile.add(jMenuFileSave);
    // edit menu
    m_editMenu.setText("Edit");
    m_editMenu.setMnemonic(KeyEvent.VK_E);
    m_editCutMenuItem.setText("Cut");
    m_editCutMenuItem.setMnemonic(KeyEvent.VK_T);
    m_editCutMenuItem.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    editCutMenuItem_actionPerformed(e);
    m_editCopyMenuItem.setText("Copy");
    m_editCopyMenuItem.setMnemonic(KeyEvent.VK_C);
    m_editPasteMenuItem.setText("Paste");
    m_editPasteMenuItem.setMnemonic(KeyEvent.VK_P);
    m_editMenu.add(m_editCutMenuItem);
    m_editMenu.add(m_editCopyMenuItem);
    m_editMenu.add(m_editPasteMenuItem);
    jMenuBar1.add(jMenuFile);
    jMenuBar1.add(m_editMenu);
    this.setJMenuBar(jMenuBar1);
    etc...
    Pressing Alt+S invokes the action listener for the jMenuFileSave menu item. It should do nothing since there is no top level menu with a mnemonic of 'S'.

  • JMenu, Hotkeys & Action Listener

    If I set a JMenu Hotkey, it will activate whenever I press it (not just when the menu is open). I don't want the hotkey to activate when I'm typing elsewhere outside the menu (ex: JTextField). I don't want to have to use CTL+hotkey for everything on my menu.
    Any Suggestions?
    Here's example code of what I am currently doing
        fileMenu = new JMenu("File");
        fileMenuItem1 = new JMenuItem("Open", KeyEvent.VK_O);
        fileMenuItem2 = new JMenuItem("Save", KeyEvent.VK_S);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        fileMenu.setFont( menuFont );
        fileMenuItem1.setFont( menuFont );
        fileMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));# Don't want to do this for each item
        fileMenuItem1.addActionListener(this);
        fileMenu.add(fileMenuItem1);
        fileMenuItem2.setFont( menuFont );
        fileMenuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
        fileMenuItem2.addActionListener(this);   
        fileMenu.add(fileMenuItem2);
    etc...
      public void actionPerformed(ActionEvent e)
        String arg = e.getActionCommand();     
        System.out.println("KEY PRESSED: "+arg );# Should only print when 'File' Menu is open...not all the time
        etc..
      }

    If I set a JMenu Hotkey, it will activate whenever I
    press it (not just when the menu is open). I don't
    want the hotkey to activate when I'm typing elsewhere
    outside the menu (ex: JTextField). I don't want to
    have to use CTL+hotkey for everything on my menu.
    If you want the Ctrl+hotKey swallowed then your component must be the one that grabs it. So your JTextField would need to understand what Ctrl+O means. I assume you want to use Ctrl+hotKey inside the JTextField or some other text component for something other than what the menu does. That means you need to manipulate the InputMap(s) and ActionMap of the component in order to reroute that ctrl+hotKey to some other action.
    If you don't handle the key in the component that has keyboard focus, then Swing passes that event up the containment hierarchy which allows containers of that component to process the key event. So what's happenning is when you push Ctrl+hotkey in a JTextField, since he doesn't understand what Ctrl+hotkey is, Swing walks the up to the parent of that component and allows it to try to process the event. Eventually it gets to the JMenuBar which has a hotkey set, so that action is fired. (JMenuBars have InputMaps and ActionMaps too).
    Here is some example code to futher illustrate. Grab this and throw it in a public static void main(), Try typing Ctrl+O and Ctrl+P in the JTextField. See how the KeyEvents are handled?
            JTextField field = new JTextField( 20 );
            field.getInputMap( JComponent.WHEN_FOCUSED ).put( KeyStroke.getKeyStroke( KeyEvent.VK_O, KeyEvent.CTRL_MASK ), "doSomething" );
            field.getActionMap().put( "doSomething", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("I did something.");
            JPanel panel = new JPanel( new FlowLayout( FlowLayout.LEFT ) );
            panel.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ).put( KeyStroke.getKeyStroke( KeyEvent.VK_P, KeyEvent.CTRL_MASK ), "doSomething2" );
            panel.getActionMap().put( "doSomething2", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println( "The Panel is doing something!" );
            panel.add( new JLabel( "Enter something: ") );
            panel.add( field );
            JFrame frame = new JFrame();
            frame.setContentPane( panel );
            frame.pack();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setVisible( true );Read more about Key Handling in post 1.3 java here:
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • Mnemonic on JMenuItem

    I'm lost. Any idea why alt+a shortcut for my JMenuItem doesn't work?
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MainClass {
      public static void main(String[] a) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuBar menu = new JMenuBar();
        menu.add(new JMenuItem(new ShowAction()));
        frame.add(menu);
        frame.setSize(350, 150);
        frame.setVisible(true);
    class ShowAction extends AbstractAction {
      public ShowAction() {
         super("fire!");
        putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("fired");
    }

    1) The mnemonic should be a character in the menu item text, maybe VK_F.
    2) a JMenuItem is added to a JMenu which is added to a JMenuBar, which is added to the frame by using frame.setJMenuBar(...). Read the section from the Swing tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/components/menu.html]How to Use Menus.
    3) Then the mnemonic is activated only when the menu is opened.
    Maybe you really want to use an "accelerator", which allows you to invoke the Action without opening the menu.
    Or you can use "Key Bindings". The tutorial link from above also has a section on this topic.

  • Passing arraylist between constructors?

    Hi guys,
    I've pretty new to java, and I think i'm having a little trouble
    understanding scope. The program I'm working on is building a jtree
    from an xml file, to do this an arraylist (xmlText) is being built and
    declared in the function Main. It's then called to an overloaded
    constructor which processes the XML into a jtree:
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    Later, in the second constructor which builds my GUI, I try and call
    the same arraylist so I can parse this XML into a set of combo boxes,
    but get an error thrown up at me that i'm having a hard time solving- :
    public Editor( String title ) throws ParserConfigurationException
    // additional code
    // Create a read-only combobox- where I get an error.
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    This is the way I understand the Arraylist can be converted to a string
    to use in the combo boxs. However I get an error thrown up at me here
    at about line 206, which as far as I understand, is because when the
    overloaded constructor calls the other constructor:
    public Editor( String title ) throws ParserConfigurationException -
    It does not pass in the variable xmlText.
    I'm told that the compiler complains because xmlText is not defined
    at that point:
    - it is not a global variable or class member
    - it has not been passed into the function
    and
    - it has not been declared inside the current function
    Can anyone think of a solution to this problem? As I say a lot of this
    stuff is still fairly beyond me, I understand the principles behind the
    language and the problem, but the solution has been evading me so far.
    If anyone could give me any help or a solution here I'd be very
    grateful- I'm getting totally stressed over this.
    The code I'm working on is below, I've highlighted where the error
    crops up too- it's about line 200-206 area. Sorry for the length, I was
    unsure as to how much of the code I should post.
    public class Editor extends JFrame implements ActionListener
    // This is the XMLTree object which displays the XML in a JTree
    private XMLTree XMLTree;
    private JTextArea textArea, textArea2, textArea3;
    // One JScrollPane is the container for the JTree, the other is for
    the textArea
    private JScrollPane jScroll, jScrollRt, jScrollUp,
    jScrollBelow;
    private JSplitPane splitPane, splitPane2;
    private JPanel panel;
    // This JButton handles the tree Refresh feature
    private JButton refreshButton;
    // This Listener allows the frame's close button to work properly
    private WindowListener winClosing;
    private JSplitPane splitpane3;
    // Menu Objects
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem newItem, openItem, saveItem,
    exitItem;
    // This JDialog object will be used to allow the user to cancel an exit
    command
    private JDialog verifyDialog;
    // These JLabel objects will be used to display the error messages
    private JLabel question;
    // These JButtons are used with the verifyDialog object
    private JButton okButton, cancelButton;
    private JComboBox testBox;
    // These two constants set the width and height of the frame
    private static final int FRAME_WIDTH = 600;
    private static final int FRAME_HEIGHT = 450;
    * This constructor passes the graphical construction off to the
    overloaded constructor
    * and then handles the processing of the XML text
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    this( title );
    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
    for ( int i = 1; i < xmlText.size(); i++ )
    textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    System.out.println( message );
    }//end try/catch
    } //end Editor( String title, String xml )
    * This constructor builds a frame containing a JSplitPane, which in
    turn contains two
    JScrollPanes.
    * One of the panes contains an XMLTree object and the other contains
    a JTextArea object.
    public Editor( String title ) throws ParserConfigurationException
    // This builds the JFrame portion of the object
    super( title );
    Toolkit toolkit;
    Dimension dim, minimumSize;
    int screenHeight, screenWidth;
    // Initialize basic layout properties
    setBackground( Color.lightGray );
    getContentPane().setLayout( new BorderLayout() );
    // Set the frame's display to be WIDTH x HEIGHT in the middle of
    the screen
    toolkit = Toolkit.getDefaultToolkit();
    dim = toolkit.getScreenSize();
    screenHeight = dim.height;
    screenWidth = dim.width;
    setBounds( (screenWidth-FRAME_WIDTH)/2,
    (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
    FRAME_HEIGHT );
    // Build the Menu
    // Build the verify dialog
    // Set the Default Close Operation
    // Create the refresh button object
    // Add the button to the frame
    // Create two JScrollPane objects
    jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();
    // First, create the JTextArea:
    // Create the JTextArea and add it to the right hand JScroll
    textArea = new JTextArea( 200,150 );
    jScrollRt.getViewport().add( textArea );
    // Next, create the XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree to
    be editable
    XMLTree.setEditable( false );
    // Wrap the JTree in a JScroll so that we can scroll it in the
    JSplitPane.
    jScroll.getViewport().add( XMLTree );
    // Create the JSplitPane and add the two JScroll objects
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
    jScrollRt );
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(200);
    jScrollUp = new JScrollPane();
    jScrollBelow=new JScrollPane();
    // Here is were the error is coming up
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    * I'm adding the scroll pane to the split pane,
    * a panel to the top of the split pane, and some uneditible
    combo boxes
    * to them. Then I'll rearrange them to rearrange them, but
    unfortunately am getting an error thrown up above.
    panel = new JPanel();
    panel.add(queryBox);
    panel.add(queryBox2);
    panel.add(queryBox3);
    panel.add(queryBox4);
    panel.add(queryBox5);
    jScrollUp.getViewport().add( panel );
    // Now building a text area
    textArea3 = new JTextArea(200, 150);
    jScrollBelow.getViewport().add( textArea3 );
    splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    jScrollUp, jScrollBelow);
    splitPane2.setPreferredSize( new Dimension(300, 200) );
    splitPane2.setDividerLocation(100);
    splitPane2.setOneTouchExpandable(true);
    // in here can change the contents of the split pane
    getContentPane().add(splitPane2,BorderLayout.SOUTH);
    // Provide minimum sizes for the two components in the split pane
    minimumSize = new Dimension(200, 150);
    jScroll.setMinimumSize( minimumSize );
    jScrollRt.setMinimumSize( minimumSize );
    // Provide a preferred size for the split pane
    splitPane.setPreferredSize( new Dimension(400, 300) );
    // Add the split pane to the frame
    getContentPane().add( splitPane, BorderLayout.CENTER );
    //Put the final touches to the JFrame object
    validate();
    setVisible(true);
    // Add a WindowListener so that we can close the window
    winClosing = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    verifyDialog.show();
    addWindowListener(winClosing);
    } //end Editor()
    * When a user event occurs, this method is called. If the action
    performed was a click
    * of the "Refresh" button, then the XMLTree object is updated using
    the current XML text
    * contained in the JTextArea
    public void actionPerformed( ActionEvent ae )
    if ( ae.getActionCommand().equals( "Refresh" ) )
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    else if ( ae.getActionCommand().equals( "OK" ) )
    exit();
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    verifyDialog.hide();
    }//end if/else if
    } //end actionPerformed()
    // Program execution begins here. An XML file (*.xml) must be passed
    into the method
    public static void main( String[] args )
    String fileName = "";
    BufferedReader reader;
    String line;
    ArrayList xmlText = null;
    Editor Editor;
    // Build a Document object based on the specified XML file
    try
    if( args.length > 0 )
    fileName = args[0];
    if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
    ".xml" ) )
    reader = new BufferedReader( new FileReader( fileName )
    xmlText = new ArrayList();
    while ( ( line = reader.readLine() ) != null )
    xmlText.add( line );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    // Construct the GUI components and pass a reference to
    the XML root node
    Editor = new Editor( "Editor 1.0", xmlText );
    else
    help();
    } //end if ( fileName.substring( fileName.indexOf( '.' )
    ).equals( ".xml" ) )
    else
    Editor = new Editor( "Editor 1.0" );
    } //end if( args.length > 0 )
    catch( FileNotFoundException fnfEx )
    System.out.println( fileName + " was not found." );
    exit();
    catch( Exception ex )
    ex.printStackTrace();
    exit();
    }// end try/catch
    }// end main()
    // A common source of operating instructions
    private static void help()
    System.out.println( "\nUsage: java Editor filename.xml" );
    System.exit(0);
    } //end help()
    // A common point of exit
    public static void exit()
    System.out.println( "\nThank you for using Editor 1.0" );
    System.exit(0);
    } //end exit()
    class newMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    textArea.setText( "" );
    try
    // Next, create a new XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION );
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree
    to be editable
    XMLTree.setEditable( false );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    }//end actionPerformed()
    }//end class newMenuHandler
    class openMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    openMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = openItem.getParent();
    }//end openMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'open'
    choice = jfc.showOpenDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName, line;
    BufferedReader reader;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    reader = new BufferedReader( new FileReader( fileName ) );
    textArea.setText( reader.readLine() + "\n" );
    while ( ( line = reader.readLine() ) != null )
    textArea.append( line + "\n" );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    XMLTree.refresh( textArea.getText() );
    catch ( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class openMenuHandler
    class saveMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    saveMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = saveItem.getParent();
    }//end saveMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'save'
    choice = jfc.showSaveDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName;
    File fObj;
    FileWriter writer;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    writer = new FileWriter( fileName );
    textArea.write( writer );
    // The file will have to be re-read when the Document
    object is parsed
    writer.close();
    catch ( IOException ioe )
    ioe.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class saveMenuHandler
    class exitMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    verifyDialog.show();
    }//end actionPerformed()
    }//end class exitMenuHandler
    class XmlFileFilter extends javax.swing.filechooser.FileFilter
    public boolean accept( File fobj )
    if ( fobj.isDirectory() )
    return true;
    else
    return fobj.getName().endsWith( ".xml" );
    }//end accept()
    public String getDescription()
    return "*.xml";
    }//end getDescription()
    }//end class XmlFileFilter
    } //end class Editor
    Sorry if this post has been a bit lengthy, any help you guys could give
    me solving this would be really appreciated.
    Thanks,
    Iain.

    Hey. Couple pointers:
    When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
    Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
    That way people don't have to wade through irrelevant stuff and
    they have an easier time helping.
    http://homepage1.nifty.com/algafield/sscce.html
    As for your problem, this is a scope issue. You declare an
    ArrayList xmlText in main(). That means that everywhere after
    the declaration in main(), you can reference your xmlText.
    So far so good. Then, inside main(), you call
    Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
    Editor(String title, ArrayList xmlText) [which happens to be a
    constructor, but that's not important]. When you do that, you
    make the two variables title and xmlText available to the whole
    Editor(String, ArrayList) method.
    This is where you get messed up. You invoke another method
    from inside Editor(String, ArrayList). When you call
    this(title);you're invoking the method Editor(String title). You aren't passing
    in your arraylist, though. You've got code in the Editor(String) method
    which is trying to reference xmlText, but you'd need to pass in
    your ArrayList in order to do so.
    My suggestion would be to merge the two constructor methods into
    one, Editor(String title, ArrayList xmlText).

  • Keyevent used for setMnemonic show in editable jtextarea

    I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
    So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
    If anyone knows if it has or a work around, please let me know.
    Thanks
    Kevin
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class adds event handling to MenuLookDemo.
    public class MenuDemo extends JFrame
    implements ActionListener, ItemListener {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public MenuDemo() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Add regular components to the window, using the default BorderLayout.
    Container contentPane = getContentPane();
    output = new JTextArea(5, 30);
    output.setEditable(true);
    scrollPane = new JScrollPane(output);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    menuBar.add(menu);
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")";
    output.append(s + newline);
    public void itemStateChanged(ItemEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")"
    + newline
    + " New state: "
    + ((e.getStateChange() == ItemEvent.SELECTED) ?
    "selected":"unselected");
    output.append(s + newline);
    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
    String classString = o.getClass().getName();
    int dotIndex = classString.lastIndexOf(".");
    return classString.substring(dotIndex+1);
    public static void main(String[] args) {
    MenuDemo window = new MenuDemo();
    window.setTitle("MenuDemo");
    window.setSize(450, 260);
    window.setVisible(true);

    Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.

Maybe you are looking for

  • How can I get my voice memos back to the voice memo app on my iphone

    Yeah, i just synced my iphone with my iTunes library and almost everything went smooth..  my pictures, apps, contacts, calendar, etc.  But I can not find the most important thing, the voice memos..  I had transferred them to my iTunes library the las

  • What is the difference between iterator.remove() ArrayList.remove()?

    Following code uses iterator.remove() ArrayList.remove(). public class CollectionRemove     private static void checkIteratorRemove()          List<String> list = new ArrayList<String>();                list.add("1");           list.add("2");        

  • Problem syncing apple contact and outlook

    After updating my OS to Maverick, I noticed that my outlook 2011 no longer sync with my apple contact. Anybody who has the same experienced and any suggestions on how to sync this. Need your HELP badly. Thanks in advance.

  • W540 DP++?

    Hello, Just a quick question. Does the Thunderbolt port on the W540 also function as DP++? I am looking to buy some HDMI monitors, as they are much cheaper than DP ones. The port isn't labeled, and I just want to make sure. W540: i7-4700mq, K2100m, 8

  • Not able to add a server into server pool

    We are managing VM setup consisting 2 VM server with Network range 10.180.10.X Series. To meet security guide We have to change DOM0 IP range from DOMU Which is 10.180.20.X. So we have added a new VM Server (The move was done to make sure no downtime