JMenuItem question?

You can set an accelerator for a JMenuItem like this:
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));Which sets the accelerator to Ctrl + C.
My question is, how do you make Ctrl + Shift + C or F5 to become accelerators?

have you tried combining them with "or"?
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
      ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));Edited by: Encephalopathic on Jun 2, 2008 2:25 PM

Similar Messages

  • Problem Writing to text area reposted forgot my code

    I have 3 seperate Classes Main, GUI, and FileChange.
    The Main class runs and constructs the GUI class. The GUI class builds my application. Then the program stops until a user action is committed. If the user opens a file the FileChange class gets the selected file and manipulates it. I tokenize the stings in the file and send the info i want back over to the JTextArea in the GUI class but nothing prints out. The program compiles but informaiton is not written to the text area, why?
    The file change makes a call like such:
    g.outputText(genre, composer, artist, albumTitle, trackNum, songTitle, count);
    the the method that is called does this:
    mainText.append(gnr+" ");
    if(count==1){mainText.append(cmp+" ");}
    mainText.append(art+" "+alb+" "+trk +" "+st.substring(3)+".mp3");
    I dont understand why I cant append text to the JTextArea. I can place text in the TextArea during constructor initialization of the GUI class but not when i call the method that appends text from the FileChange class.The Code is posted below
    Thanks in advance for your help
    p
    Main Class//////////////////////////////////////////////////
    package musicmatch_library_test;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.util.*;
    public class Main implements WindowListener
    public Main()
         super();
         public static void main(String args[])
    GUI f = new GUI();
    f.setSize(800,600);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
         public void windowActivated(WindowEvent e)
         public void windowClosed(WindowEvent e)
         public void windowClosing (WindowEvent e)
              GUI f = new GUI();
              f.quitApplication( );
         public void windowDeactivated(WindowEvent e)
         public void windowDeiconified(WindowEvent e)
         public void windowIconified(WindowEvent e)
         public void windowOpened(WindowEvent e)
    GUI Class
    package musicmatch_library_test;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.io.*;
    class GUI extends JFrame implements ActionListener, FilenameFilter
    private JMenuBar menuBar = new JMenuBar(); // Creating The MenuBar
    protected JFileChooser dialogBox = new JFileChooser(); //create load dialog box
    private JMenu fileMenu, editMenu, helpMenu; // Menu Options
    protected JMenuItem fileOpen, fileSaveAs, fileExit; // File Option
    private JMenuItem editDelete; //Edit Options
    private JCheckBoxMenuItem wordWrap;
    private JMenuItem helpQuestions, helpAbout; // Help Options
    private JTextArea mainText = new JTextArea();
    //public FileChange changeFile = new FileChange();
    public GUI()
         super("Library Converter v.001"); //Title bar text
         getContentPane().setLayout(new BorderLayout());
    this.setJMenuBar(menuBar); // Add menu Bar to the screen
    initFileMenu(); // goes to the file menu method
    initEditMenu(); // " " edit menu method
    initHelpMenu(); // " " help menu method
    initTextArea();     // " " text area setup
    System.setProperty("line.separator", "\r\n");
         public boolean accept(File dir, String name)
              System.out.println("accept():");
              if (name.endsWith(".txt")) return true;
              return false;
         public void actionPerformed(ActionEvent e)
    if(e.getSource() == fileExit)     //if statement to close app
    quitApplication();
    }//end if (e.getSource() == fileExit)
    if(e.getSource() == fileSaveAs)
    FileChange changeFile = new FileChange();
    changeFile.fileSaveAs();
    }//end if (e.getSource() == fileSaveAs)
    if(e.getSource() == fileOpen)     //if statement to open a file
    openFile();
    }//end if (e.getSource() == fileOpen)
    if(e.getSource() == wordWrap)     //if statement to turn word wrap on/off
    if(wordWrap.getState() == false)
    mainText.setLineWrap(false);
    mainText.setLineWrap(false);
    }//end if (wordWrap.getState() == false)
    else if(wordWrap.getState() == true)
    mainText.setLineWrap(true);
    mainText.setLineWrap(true);
    }//end else if (wordWrap.getState() == true)
    }//end if (e.getSource() == wordWrap)
         }//end action performed
         private void initEditMenu()
    editMenu = new JMenu("Edit"); //Adding Edit to Menu
    editMenu.setMnemonic('E');
    menuBar.add(editMenu);
    wordWrap = new JCheckBoxMenuItem("Word Wrap", false); //adding a word wrap on/off button
    wordWrap.addActionListener(this);
    wordWrap.setEnabled(true);
    editMenu.add(wordWrap);
    editDelete = new JMenuItem("Delete"); //adding delete inside the "edit" options
    //editDelete.addActionListener(this);
    editDelete.setEnabled(false);
    editMenu.add(editDelete);
         }//intEditMenu
         private void initFileMenu()
    fileMenu = new JMenu("File"); // Adding File to the menu bar
    fileMenu.setMnemonic('F');
    menuBar.add(fileMenu);
    fileOpen = new JMenuItem("Open"); // Adding open to the Menu
    fileOpen.setMnemonic('O');
    fileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
    fileOpen.addActionListener(this);
    fileOpen.setEnabled(true);
    fileMenu.add(fileOpen);
    fileSaveAs = new JMenuItem("Save File As"); // Save file info
    fileSaveAs.setMnemonic('S');
    fileSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
    fileSaveAs.addActionListener(this);
    fileSaveAs.setEnabled(false);
    fileMenu.add(fileSaveAs);
    fileExit = new JMenuItem("Exit"); //Exit Item
    fileExit.setMnemonic('X');
    fileExit.addActionListener(this);
    fileMenu.add(fileExit);
         private void initHelpMenu()
    helpMenu = new JMenu("Help"); //adding help menu
    helpMenu.setMnemonic('H');
    menuBar.add(helpMenu);
    helpQuestions = new JMenuItem("Questions"); // Questions Item
    helpQuestions.addActionListener(this);
    helpQuestions.setEnabled(false);
    helpMenu.add(helpQuestions);
    helpMenu.addSeparator();
    helpAbout = new JMenuItem("About"); //addind About stuff
    helpAbout.addActionListener(this);
    helpAbout.setEnabled(false);
    helpMenu.add(helpAbout);
    private void initTextArea()
         mainText.setEditable(false);
         mainText.setVisible(true);
    JScrollPane scrollPane = new JScrollPane(mainText);
    getContentPane().add(scrollPane, "Center");
         public void openFile()
         {//method to start the opening of a file
              FileChange changeFile = new FileChange();
    //fileSaveAs.setEnabled(true);
              mainText.setText("Please Be Patient While Opening The File");
              dialogBox.setCurrentDirectory(new File("C:/Documents and Settings/Administrator/My Documents/Java Stuff/Personal Projects")); //set default path
              dialogBox.showOpenDialog(this);                         //opens the dialog box to select a file
              changeFile.fileManip(dialogBox.getSelectedFile().getPath());//get the directory plus the file and pass it to fname in displayTab1()
         }// end openFile()
    public void outputText(String gnr, String cmp, String art, String alb, String trk, String st, int count)
         mainText.append(gnr+" ");
         if(count==1){mainText.append(cmp+" ");}
         mainText.append(art+" "+alb+" "+trk +" "+st.substring(3)+".mp3");
         public void quitApplication( )
              setVisible(false );
              dispose( );
              System.exit(0);
    FileChange Class
    package musicmatch_library_test;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    class FileChange extends GUI
         JTextArea fcText = new JTextArea();
    public     FileChange()
         super();
         public void fileManip(String fname)
         {//this mehtod will edit and display and save certain info in tab1s display area
         GUI g = new GUI();
         try
    BufferedReader inFile = new BufferedReader(new FileReader(fname));
    PrintWriter outStream = new PrintWriter (new FileWriter(fileSaveAs())); //dialogBox.getSelectedFile()
              String line = inFile.readLine();
              fcText.setText("");
              int count;          
              while(line != null)
                   StringTokenizer cut = new StringTokenizer(line, "\\");
                   count = cut.countTokens();
                   if(count == 6 || count ==7)
                        String drive = cut.nextToken();
                        String folder = cut.nextToken();
                        String genre = cut.nextToken();
                        String composer=null;
                        if(count ==7)
                             composer = cut.nextToken();
                             count = 1;
                             String artist = cut.nextToken();
                             String albumTitle = cut.nextToken();
                             String trackNum = cut.nextToken("\\ -");
                             String songTitle = cut.nextToken(".");
                             g.outputText(genre, composer, artist, albumTitle, trackNum, songTitle, count);
                        outStream.print(genre+" ");
                        if(count==1){outStream.print(composer+" ");}
                        outStream.println(artist+" "+albumTitle+" "+trackNum +" "+songTitle.substring(3)+".mp3");
                        count = 0;
                   }//if(count == 6)
                        line = inFile.readLine();
              }//end while(line != null)
              outStream.close();
              inFile.close();
         }//end try
         catch(FileNotFoundException e)
              g.fileSaveAs.setEnabled(false);
              fcText.setText("NO File will be open, File Not Found");
         }//end catch (FileNotFoundException e)
         catch(IOException e)
    g.fileSaveAs.setEnabled(false);
    fcText.setText("NO File will be open");
    System.exit(1);
         }//end catch (IOException e)
         catch(NoSuchElementException e)
              fcText.setText("No MoreTokens");
    }//end FileManip()     
         public File fileSaveAs()
    {//method for saving a file
         GUI a = new GUI();          
    a.dialogBox.setCurrentDirectory (new File("C:/Documents and Settings/Administrator/My Documents/Java Stuff/Personal Projects"));
    a.dialogBox.showSaveDialog(a.getContentPane());
    //File toSaveAs = a.dialogBox.getSelectedFile();
    return a.dialogBox.getSelectedFile();
    }//end fileSaveAs()

    For instance in your main you can have:
    public class Main implements WindowListener {
      public static GUI f;
      public Main(){
        super();
      public static void main(String args[]) {
        f = new GUI();
        f.setSize(800,600);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
          //Window Adapter Stuff...By the way if you use the WindowAdapter
          //You don't have to stub out the methods you don't use, just write
          //the ones you do use, that is what makes adapters better then
          //listeners...
      public static GUI getGUIInstance() {
        return f;
    //then in the fileChange methods that need to use the GUI do:
      GUI g = Main.getGUIInstance();Steve

  • JMenuItem icon/Text verticle alignment question

    hello,
    can some one help with my question:
    I got 5 JMenuItems in a JMenu, some JMenuItems have icon, some not, I want to align them with icon and text in a neat format, like those in Sun's Forte IDE's Menu:
    but I can only do it like this:
    icon1 open..
    save As..
    icon2 new..
    Exit..
    (above each line represent a JMenuItem, I need to make "save as" ,"Exit" to in line with "open" and "new" in verticle direction,NOT with the icon)
    sb suggest always set an icon for each JMenuItem, set an transparent Icon for alignment those without icons.
    but this sounds not so attractive, are there any other ways? thanks a lot.

    Create a method to do the icons. One can have one parameter (menu text) and the other could have two parameters (icon name, menu text). Have the one with just one parameter set up a default transparent icon.
    Garry.

  • JMenuItem icon, text alignment question

    hello,
    can some one help with my question:
    I got 5 JMenuItems in a JMenu, some JMenuItems have icon, some not, I want to align them with icon and text in a neat format, like those in Sun's Forte IDE's Menu:
    but I can only do it like this:
    icon1 open..
    save As..
    icon2 new..
    Exit..
    (above each line represent a JMenuItem, I need to make "save as" ,"Exit" to in line with "open" and "new" in verticle direction,NOT with the icon)
    sb suggest always set an icon for each JMenuItem, set an transparent Icon for alignment those without icons.
    but this sounds not so attractive, are there any other ways? thanks a lot.

    you can always take a mort drastic action by subclassing MenuItem and
    overriding the painting method.
    But I belive that the first suggestion is faster.

  • Questions on events in a multi-class GUI

    I have a GUI application that is constructed as follows:
    1. Main Class - Actually creates the JFrame, contains main method, etc.
    2. MenuBar Class - Constructor creates a new JMenuBar structure and populates it with various JMenus and JMenuItems. A new instance of this class is instantiated in the Main Class to be used in the setMenuBar() method.
    3. ContentPane Class - Constructor creates a vertical JSplitPane. A new instance of this class is instantiated in the Main Class to be used in the setContentPane() method.
    4. BottomPane Class - Constructor creates a JPanel and populates it with various stuff. A new instance of this class is instantiated in the Content Pane Class to be used as the bottom pane in the vertical JSplitPane.
    5. TopPane Class - Constructor creates a horizontal JSplitPane and populates the left pane with a JScrollPane containing a JList. A new instance of this class is instantiated in the Content Pane Class to be used as the top pane in the vertical JSplitPane.
    6. TabbedPane Class - Constructor creates a JTabbedPane. A new instance of this class is instantiated in the Top Pane Class to be used as the right pane in the horizontal JSplitPane.
    7. DisplayPane Class - Constructor creates a JPanel. A new instance of this class is instantiated in the Tabbed Pane Class as the first tab. The user has the ability to click at points in this pane and a dialog box will pop up prompting the user for a string. Once the user enters something and clicks "OK", an instance of a custom Java2D component that I've created will be added to the DisplayPane where the user had clicked, with the string the user inputted being used as its name. The user can then drag the component around, enter a key combination to display all the names, etc.
    8. Custom Java2D Component Class - Constructor creates my custom Java2D component. Instances of this are added to the Display Pane Class, as I have described.
    Now, originally, I was going to ask "How do you work with events between these multiple classes?" but I have solved half of that problem myself with the following class:
    9. Listener Class - A new instance of this class is declared in the constructor of the Main Class, and is thus passed down through the GUI hierachy via the constructors of the various classes. I then use the addActionListener() method on various components in the other classes, and then the Listener Class can capture an event using the getActionCommand() method to figure out what fired the event.
    So that covers the "How do I capture events in multiple classes?" question. Now I'm left with "How do I affect changes on those classes based on events?"
    For example: In my MenuBar class, I have a "Save" menu item. When this is clicked, I want to declare a new JFileChooser and then use the showSaveDialog() method, which throws up a dialog for saving a file. The problem is, the showSaveDialog() method takes a Component which is the parent frame. Obviously the Listener Class is not a frame. I want to use the Main Class as the parent frame. How would I do this sort of thing?
    Another example: In my MenuBar class, I have a "New" menu item. For now, I want this to invoke a method in the DisplayPane Class that erases all of my custom Java2D components that have been made, thus giving the user a clean slate. How would I give my Listener Class access to that method?
    A final example: Every time the user adds one of my custom Java2D components, I want that component's name to be added to the JList that is in my TopPane class. Vice versa with deleting a component: its name should be removed from the JList. How would I listen for new components being added? (A change listener on the pane? One on the ArrayList<> that contains all of the components? Something else?) And, of course, how would I give the Listener Class the ability to change the contents of the JList?
    One idea I've come up with so far is to instantiate a new instance of each of my GUI classes in the Listener class, but that doesn't really make much sense. Wouldn't those be new instances that are totally separate from the instances the rest of my program is using? Another thought is to make the Listener Class an internal class inside the Main Class so that it can use the accessor methods of the GUI classes, but a.) I would like to avoid stuffing everything in one class and b.) this brings up the question of "How would I get an accessor method that is in a class that is two or three deep in the hierarchy?" (.getSomething().getSomethingInsideThat().getSomethingInsideTheInsideThing()?)
    Help with answering any or all of my questions would be much appreciated.

    Hrm. At the moment, for my first attempt, I'm doing something similar, it just strikes me as quite unwieldy.
    Start of Listener class, with method for setting what it listens to. (I can't use a constructor for this because the MenuBar and the ContentPane take an instance of
    this Listener class in through their constructors. You can't pass the Listener in through their constructors while simultaneously passing them in through this
    Listener's constructor. That would be an endless cycle of failure. So I just instantiate an instance of this Listener class, then pass it in through the MenuBar and
    ContentPane constructors when I instantiate instances of them, and then call this setListensTo() method.)
    public class Listener implements ActionListener
      private MenuBar menuBar;
      private ContentPane contentPane;
      public void setListensTo(MenuBar menuBar, ContentPane contentPane)
        this.menuBar = menuBar;
        this.contentPane = contentPane;
      }The part of my actionPerformed() method that does some rudimentary saving, which I will make more complicated later:
    else if (evt.getActionCommand() == "saveMenuItem")
      JFileChooser fileChooser = new JFileChooser();
      int returnVal = fileChooser.showSaveDialog(menuBar.getTopLevelAncestor());
      if (returnVal == JFileChooser.APPROVE_OPTION)
        File file = fileChooser.getSelectedFile();
        ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();
        try
          BufferedWriter out = new BufferedWriter(new FileWriter(file));
          for (int i = 0; i < nodes.size(); i++)
            Node node = nodes.get(i);
            out.write(node.getIndex() + "," + node.getXPos() + "," + node.getYPos() + "," + node.getName());
            out.newLine();
          out.close();
        catch (IOException e)
          //To be added                    
    }That part that seems unwieldy is the
    ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();The reason I'm using a separate Listener class is because if I put, say, the actions for the MenuBar in the MenuBar class, and then want to save stuff in the JPanel
    at the bottom of the hierachy, I would have to go up from the MenuBar into the JFrame, and then back down the hierachy to the JPanel, and vice versa. Kind of like
    walking up a hill and then down the other side. I imagine this would be even more unwieldy than what I'm doing now.
    On the plus side, I am making progress, so thanks all for the help so far!

  • Dynamic addition of  JMenuItem in JMenu

    I am trying to create a menu for my project. For that i have added the main menus and for each menu there will be menu item. But the problem is i will get the list of menu items for each menu , only at the runtime of my project. i.e. i wabt to add progrramatically add the menu items. Iam really confused with this. I will appriciate if any one help me on this.
    And also i want to know ..is that possible to get the mouse listener for menu.
    Thank in advance
    Regards,
    SAthish

    You can add and remove menu items from the jmenu dynamically, the only thing you will have to take care of is invoking validate() after each insertion/deletion (it's a bit buggy there). All you have to do is create the items on demand and add (remove) them via the add(JMenuItem) (remove(JMenuItem)) method.
    As for your second question, a JMenu is nothing but a JComponent, so you should be able to add a mouse listener like you would with any other component...

  • JButton, JMenuItem, & Action

    I have an inheritance question regarding the relationships between these objects.
    Basically, I would like to have a generic actionPerformed() method for objects inside an Action object, but I want a little more customization whenever the action is represented as a button.
    For example, if my action is a JButton, I would like there to be two states, whereas I only want one state in my JMenuItem. Here is what I have right now for two seperate classes that implement (generally) the same functionality.
    class MyButton extends JButton implements ActionListener {
      public MyButton(String name) {
        super(name);
        setBackground(Color.RED);
        addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        if(getBackground() == Color.RED) {
          setBackground(Color.GREEN);
          // Perform State 1 operations.
        } else {
          setBackground(Color.RED);
          // Perform State 2 operations.
    class MyMenuItem extends JMenuItem implements ActionListener {
      public MyMenuItem(String name) {
        super(name);
        addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        // Perform State 1 operations.
    }Is there a good way to represent one Action object for these two implementations? Thanks for the help.

    here is what I would do...
    move the actionPerformed method to its one class and handle it differently, it might look like this...
    class MyButton extends JButton {
      public MyButton(String name) {
        super(name);
        setBackground(Color.RED);
    public class MyListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        if(e.getSource().getBackground() == Color.RED) {
          e.getSource()setBackground(Color.GREEN);
          // Perform State 1 operations.
        } else {
          e.getSource().setBackground(Color.RED);
          // Perform State 2 operations.
    class MyMenuItem extends JMenuItem {
      public MyMenuItem(String name) {
        super(name);
    public static void main(String[] args) {
      MyListener color = new MyListener();
      MyMenuItem item = new MyMenuItem("name");
       item.addActionListener(color);
       MyButton button = new MyButton("button");
       button.addActionListener(color);
    }This way you have one listener instance for your button. you'll have to do some work in the actionListener to identify the source of the event, but you should be able to figure that out on your own. The 'code' I posted is untested, but you should get the idea.

  • Setting icon for the JMenuItem

    I am trying to set the Icon for the JMenuItem and not able to do so.
    I have the Images directory in the classes which has all the images. Is this the way to give the dir path. When do I give '\' and when do I give '/' or'//' or'\\'? Thanks.
    I gave
    JMenuItem mnuitmFileNew = new JMenuItem(new ImageIcon("Images//new.jpg"));
    and later in Jbinit() method I have this.
    mnuitmFileNew.setMnemonic('N');
    mnuitmFileNew.setText("New");
    mnuitmFileNew.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    mnuitmFileNew_actionPerformed(e);
    });

    Hi,
    I'm not sure if you've seen this yet:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    If you still have any questions please post again.
    Regards,
    Matt
    Java Developer Technical Support
    Sun Microsystems

  • JMenu and JTabbedPane questions

    Hello I got 2 questions :
    1) Is it possible to change the icon of JMenu when the mouse cursor is on it ? setRolloverIcon function doesnt work in this case, like it does for the JButton.
    2) When I create my application I got 1 JTabbedPane object visible. Now, every time I click a selected JMenuItem, I wanna add another JTabbedPane object to the window. So in the class MyMenu I got this code in actionListener:
    if(arg.equals("menu1")) {
         JTabbedPane tabbedPane = new JTabbedPane();
         tabbedPane.addTab("tab", null, null, "nothing");
         frame.getContentPane().add(tabbedPane);
    The problem is that it doesnt appear on the window, but instead when I resize it, there is a vertical line in the place where the right "edge" of the old window was.
    Can anyone tell me what do I do wrong ?
    Thx in advance.

    Actually I dont know but the simpliest way seems to be subclassing the menu Item, and listen for mouse events. When you learn a better way to do it you can change your code :)
    Java always allowed me to do such tricks :)

  • JComboBox simple question

    I think is a very simple question, I ve got a JComBox with an array of Strings. Something like this:
    JPanel myPanel;
    JComBox box;
    String levels[]={"Level 1","Level 2","Level 3","Level 4","Level 5"};
    box = new JComboBox (levels);
    myPanel.add(box);
    Ok. My question is: How can I let just the level 1 enable at first, or how can I enable or disable just one level of the JCombox, like level 1 and 2 enable but level 3, 4 and 5 disable.
    Thanks a lot!! Hope someone helps me!!

    I don't think this is possible with a JComboBox. I believe it is with a JMenu and JMenuItems.
    You could only display valid options by adding/deleting them. Or you could handle it in the listener code. ie if they select an invalid option do nothing. This would require you keeping track of which options are valid elsewhere in the code.

  • Several windows and grid questions

    Hello, I have a couple of Swing related questions that follow:
    Q 1)
    Imagine I'm writing a basic GUI that has 2 "windows": the main window and the about box window. Basicly there's a JMenu with a JMenuItem that has an action that will set the about box visibility to true.
    My question is: what's the most correct way to do this?
    a) declare both windows in the Gui constructor, having the main window's visibility set to true and the about box window visibility set to false, changing that visibility inside a actinPerformed () method
    b) declare the main window in the Gui constructor, and then creating the about box window inside the actionPerformed method, when the MenuItem is selected
    c) other. please explain
    Q 2)
    Is there any way to automaticly draw a grid within a JFrame or does it have to be done with Graphics' drawRect, drawLine and so on?
    Thanks in advance.

    Q1: c, have a getter for the aboutBox and instanciate when needed (also possible with b). If the user never clicks the menuItem, why instanciate and clean up later?
    Q2: DrawRect /line

  • Adding popup menus on jmenuitem

    hello
    I would like to add a popup menu when right-click on a jmenuitem , given that the left click will launch the jmenuitem action.
    I've done this by invoking:
    jMenuItem.setArmed(false);
    when a right click is detected, so i bring up my popup and the action is not launched.
    But the jMenuItem hides himself and the popup stay in the middle of nothing (a bit ugly)
    QUESTION:
    how to tell the jMenuItem and the corresponding jMenu to stay visible while and after I use the popup ? Is it possible ?
    Thank you for any help,
    Xavier

    Repost...

  • Making a JMenuItem bring up a new frame

    Hey,
    I was wondering what sort of ActionListener code I would need to apply to a JMenuItem to have that item display a new Frame when it is selected. Basically I want to make an "About" box for my program, and I wish this to be in a new frame separate from my main frame...
    Thanks

    So you want some kind of Dialog... Some kind of "J" Dialog... But where could you find information on that kind of thing?
    I guess, and this is admittedly a longshot, read the API.
    If you point your browser at the online API docs you should see a list of all classes. Search for JDialog and work out from there. You should find examples of how to use the associated classes and methods.
    If you have a specific problem or question with regard to implementing what you want, post you question in the swing forum and you'll get help.
    Mark

  • JMenuItems are selected by default

    When I run my application and click on the Menu items, My JMenuItems are shown as selected. Once I hover the mouse on each menu item, they get de-selected after that they work normally. That is, only the menu item that gets the mouse on it gets selected. What is the problem, I checked up my code I see nothing wrong with it. tnx for any idea u may have

    I think you want me to elaborate the question here it is.
    I have a JMenu named 'File'. I have many JMenuItems under the 'File' JMenu. When I click on the 'File' JMenu, I see all the JMenuItems. And all of them are selected! Here is how I implemented the JMenuItems
    public class NewFile extends JMenuItem{      //the other menu items are implemented in a similar way
         public NewFile(String str){
              super(str);
              setArmed(true);
              addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent e){
    }I then added an instance of the FileMenuItem to FileMenu in this way
    class FileMenu extends JMenu{
         private NewFile newFile;     
         public FileMenu(String str){
              super(str);          
              newFile = new NewFile("New");
              openFile = new OpenFile("Open");
              closeFile = new CloseFile("Close");
              saveFile = new SaveFile("Save");
              printFile = new PrintFile("Print");
              exitFile = new ExitFile("Exit");
              add(newFile);
              add(openFile);
              add(closeFile);
              addSeparator();
              add(saveFile);
              addSeparator();
              add(printFile);
              addSeparator();
              add(exitFile);
    }I'm trying to make it work as follows. A JMenuItem should be selected only when I click on it!
    Tnx

  • JPopupMenu - setSelected (JMenuItem)

    Hi
    I have a popup menu with a number of menu items which I add to the popupMenu. I call setSelected with one of them (not the first added) and then show. But it is always the first item that is shown as being selected, even though when I call getSelectionModel().getSelectedIndex it returns the index of the item I set to be selected.
    I can see that others have had similar problems, but haven't been able to find anyone that could answer them.

    Why do you want the menu item selected?
    This works, but may not fully answer your question. ***************************************************************************************************
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.UIManager;
    public class PopupTest extends JFrame implements ActionListener
    public static void main( String[] args )
    PopupTest test = new PopupTest();
    test.pack();
    test.show();
    private JPopupMenu popup;
    private JMenuItem menuItem1;
    private JMenuItem menuItem2;
    public PopupTest()
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch( Exception e )
    popup = new JPopupMenu();
    menuItem1 = new JMenuItem( "Item 1");
    menuItem1.setActionCommand( "Item 1");
    menuItem1.addActionListener( this );
    menuItem2 = new JMenuItem( "Item 2");
    menuItem2.setActionCommand( "Item 2");
    menuItem2.addActionListener( this );
    popup.add( menuItem1 );
    popup.add( menuItem2 );
    JButton button = new JButton("Button 1");
    button.setActionCommand("Button 1");
    button.addActionListener( this );
    this.getContentPane().add( button );
    button = new JButton("Button 2");
    button.setActionCommand("Button 2");
    button.addActionListener( this );
    this.getContentPane().add( button, BorderLayout.EAST );
    public void actionPerformed(ActionEvent e)
              System.out.println(e.getActionCommand());
    popup.show( this, 0,0 );
    if( e.getActionCommand().equals( "Button 1" ) )
    popup.setSelected( menuItem1 );
    menuItem1.setArmed( true );
    menuItem2.setArmed( false );
    else if( e.getActionCommand().equals( "Button 2" ) )
    popup.setSelected( menuItem2 );
    menuItem1.setArmed( false );
    menuItem2.setArmed( true );

Maybe you are looking for