JCheckBox and JPopupMenu

I have a JPopupMenu containing several checkboxes within some submenus. Everytime I select one check box, the popup menu closes and I have to do it all over again. Is there any way to allow multiple selections in a JPopupMenu?
Thanks!

I have it set up so when I select a specific checkbox a popup menu appears right next to it. A dialog would be nice, but I have put too much time into this to change it now. Any thoughts about how to keep the popup menu open while selections are being made? Thanks for replying so quick!

Similar Messages

  • Problem with InputVerifier and JPopupMenu

    Hello, I have a problem related to the usage of InputVerifier and JPopupMenu.
    Consider the following scenario:
    - A frame composed of two components: a JTextField and a JComboBox
    - An InputVerifier that was set in the JComboBox (and in its associated JTextComponent)
    - A JPopupMenu which is enabled by a right mouse click over the components of the frame.
    The verify() method of the InputVerifier class is executed every time the focus is on the JComboBox and is requested by other component.
    Suppose that the focus is on the JComboBox, and a right mouse click is executed over this components. In summary, we have:
    1) The method verify() of the InputVerifier associated to the JComboBox is executed
    2) The focus changes from the JTextComponent (associated to the JComboBox) to the JRootPane (associated to the JTextComponent (that is associated to the JPopupMenu)).
    Now suppose that, the user clicks in the JTextField component (note that the JPopupMenu is visible and has the focus). What happens is that the focus goes from the JRootPane -> JTextComponent (associated to the JComboBox) -> JTextField.
    Despite the focus flow through the JTextComponent, the Swing plattaform, when executing the runInputVerifier() in the JComponent context, get the JRootPane component as the focusOwner instead of the JTextComponent.
    In this way, the Swing platform tries to invoke the InputVerify of the JRootPane (that is set with "null"), and the JComboBox InputVerifier is not executed as expected.
    It works as if the focus is flowing from the JRootPane directly to the JTextField.
    However, if the user clicks on the JComboBox before clicking in the JTextField, the Swing platform executes the correct InputVerifier, i.e., the one associated to the JComboBox (actually, the one associated to the JTextComponent).
    Any thoughts to solve this problem?
    Thanks

    A plus information, I am using jdk1.5.0_22.

  • Regarding JCheckBox and JRadioButton

    hi,
    I have a screen which contains JCheckBox and JRadioButton component on it. when focus is on checkbox i wanted the background color to be green. But once the focus is lost, the background color should be changed to normal.
    Is it possible? Please help me out.. I need it very urgently.
    regards,
    Deepa Raghuraman

    Hello!
    If you mean keyboard focus:
    yourCheckBox.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {
                 // change color to green
            public void focusLost(FocusEvent e) {
                 // change color to 'normal'
    });I hope it helps you.
    regards
    Feri

  • Having trouble with JCheckBox and JTree

    I am trying to render the JTree to display JCheckBox's instead of just ordinary JLabels.
    It's fine, compiles, and when you view it it looks normal, until you try to check one.
    You can't check it at all.
    What am i doing wrong with this?
    Thanks

    OK, here it is...
    public class EmotiTreeCellRenderer extends DefaultTreeCellRenderer {
         protected JCheckBox label;
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
              if ( value instanceof DefaultMutableTreeNode ) {
                   label = new JCheckBox();
                   label.setOpaque( false );
                   if ( selected && hasFocus ) {
                        label.setForeground( Color.blue );
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
                   Object userObject = node.getUserObject();
                   if ( userObject instanceof Emoticon ) {
                        Emoticon emoticon = (Emoticon)userObject;
                        String icon = emoticon.getIconKeys();
                        try {
                             label.setText( "<html><body><img src=\"" + new File( emoticon.getRealPathToEmoticon() ).toURL().toString() + "\" alt=\"" + parseAlt( icon ) + "\"> " + parseAlt( icon ) + "</body></html>" );
                        } catch ( MalformedURLException mfe ) {
                             label.setText( "<html><body>" + parseAlt( icon ) + "</body></html>" );
                        return label;
                   } else if ( userObject instanceof EmotiPack ) {
                        EmotiPack pack = (EmotiPack)userObject;
                        label.setText( pack.getName() );
                        return label;
              return super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
         protected String parseAlt(String html) {
              return html.replace( "<", "<" ).replace( ">", ">" ).replace( "\"", "&#34;" );
    }

  • JMenuItem and JPopupMenu

    Is there an esay why round this issue?
    I've got a JMenuItem that I would like to add to MULTIPLE menu's.
    when I add the JMenuItem to a "new" JPopup it dissappears from the previous one.
    eg
    JPopupMenu menu1 = new JPopupMenu();
    JPopupMenu menu2 = new JPopupMenu();
    JMenuItem disappearingItem = new JMenuItem("I'll only appear once");
    menu1.add(disappearingItem);
    menu2.add(disappearingItem);I know I could "just" create a new JMenuItem that is the same, but this seems like a hassle. Why can't I have the same JMenuItem appearing in different menus?
    Thanks,
    Steve

    Hello,
    I think its to avoid incosistency.
    This is the responsible source-code from java.awt.Container:
    /* Reparent the component and tidy up the tree's state. */
             if (comp.parent != null) {
              comp.parent.remove(comp);
                        if (index > ncomponents) {
                            throw new IllegalArgumentException("illegal component position");
                }Ragards,
    Tim

  • Netbeans and JPopupMenu

    Im having a problem creating a JPopupMenu,
    Im using the netbeans GUI builder, I've added the popup menu to the Jframe, and can get it to display itself when right clicked, however i cannot get it to hold any components.
    I tried adding a menu item to it, first by dragging and dropping, which did not work, then by right clicking and adding from pallete, which did work.
    However, the menu item is not diplayed.
    I tried adding various other containers too, but they are not displayed either, any ideas what im doing wrong?
    Thanks,
    James

    Yes quite, netbeans is absolutley fine, frankly, the java website suggests using it for gridbag... Some people just like to feel 1337.
    Curiously its working now, kinda.
    There seems to be a bug of somesort that causes the palette to empty, at which point i have to recreate the project and it comes back, since then however, the popupmenu seems to work, although the offset is a bit wonky
    jPopupMenu1.setLocation(evt.getX(), evt.getY());
                jPopupMenu1.setEnabled(true);
                jPopupMenu1.setVisible(true); that should put the menu where the mouse was at the time, however it seems to be off slightly, any ideas why?

  • Learning SQL Query with JCheckBox and JButton

    Hello,
    I am learning how to access a very simple Access table. I am able to connect to the database and return a simple query. As I make it more complicated is where I have confused myself. The program is suppose to allow the user to pick any field they want to query using JCheckBox. After they have checked the fields off, the run query button is hit and outputs the results in a JOPtion Pane with a JTable. I am trying to do a test run and I can't make the query at least output something. If I can get any clues to the right direction would be appreciated. Thanks.
    package mypackage25;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class QueryAddressBook extends JFrame
        private JLabel selectQueryLabel;
        private JCheckBox firstName, lastName,
                       telephone, addressI, addressII, city,
                       state, zip;
        private JPanel selectQueryPanel, checkBoxPanel, executePanel;
        private JButton runQueryButton, clearSQLButton;
        private Connection connection;
        private Statement statement;
        private ResultSet resultSet;
        public QueryAddressBook()
          super("Query an Address Book");
          //Driver and Connection
          try
          //Driver for MicrosoftAccess
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          //Inform the user that the Driver was loaded successfully
          System.out.println("Driver Loaded");
          //Connect to specific database(i.e. MyAddress3) in Access
          Connection connection=DriverManager.getConnection("jdbc:odbc:MyAddress3");
          //Inform User
          System.out.println("Database connected");
          }//end try
          catch(ClassNotFoundException cnfe)
            cnfe.printStackTrace();
          }//end catch
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
          //get content pane and set its layout
          Container container=getContentPane();
          container.setLayout(new BorderLayout());
          //GUI Components
          selectQueryLabel=new JLabel("Select Fields to be Queried");
          firstName=new JCheckBox("First Name");
          lastName=new JCheckBox("Last Name");
          telephone=new JCheckBox("Telephone");
          addressI=new JCheckBox("Address I");
          addressII=new JCheckBox("Address II");
          city=new JCheckBox("City");
          state=new JCheckBox("State");
          zip=new JCheckBox("Zipcode");
          //register listeners for JCheckBoxes
          CheckBoxHandler handler=new CheckBoxHandler();
          firstName.addItemListener(handler);
          lastName.addItemListener(handler);
          telephone.addItemListener(handler);
          addressI.addItemListener(handler);
          addressII.addItemListener(handler);
          city.addItemListener(handler);
          state.addItemListener(handler);
          zip.addItemListener(handler);
          //set up selectQueryPanel
          selectQueryPanel=new JPanel();
          selectQueryPanel.setLayout(new FlowLayout());
          selectQueryPanel.add(selectQueryLabel);
          //set up CheckBox Panel
          checkBoxPanel=new JPanel();
          checkBoxPanel.setLayout(new FlowLayout());
          checkBoxPanel.add(firstName);
          checkBoxPanel.add(lastName);
          checkBoxPanel.add(telephone);
          checkBoxPanel.add(addressI);
          checkBoxPanel.add(addressII);
          checkBoxPanel.add(city);
          checkBoxPanel.add(state);
          checkBoxPanel.add(zip);
          //set up execute panel
          executePanel=new JPanel();
          executePanel.setLayout(new FlowLayout());
          //set up buttons
          runQueryButton=new JButton("Run Query");
          clearSQLButton=new JButton("Clear SQL");
          runQueryButton.addActionListener
            new ActionListener()
              public void actionPerformed(ActionEvent event)
                if(event.getSource().equals(runQueryButton))
                  runSQLQuery();
          executePanel.add(runQueryButton);
          executePanel.add(clearSQLButton);
          container.add(selectQueryPanel, BorderLayout.NORTH);
          container.add(checkBoxPanel, BorderLayout.CENTER);
          container.add(executePanel, BorderLayout.SOUTH);
          setSize(800,150);
          setVisible(true);
        public static void main(String args[])
          QueryAddressBook dwgui=new QueryAddressBook();
          dwgui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }//end main
        //private inner class for ItemListener event handling
        private class CheckBoxHandler implements ItemListener
          public void itemStateChanged(ItemEvent event)
          }//end method itemStateChanged
        }//end private inner class CheckBoxHandler
        private void runSQLQuery()
          String output="";
          try
            statement=connection.createStatement();
            resultSet=statement.executeQuery("select firstName from address");
            while(resultSet.next())
              output+=resultSet.getString(1)+"\n";
            JOptionPane.showMessageDialog(null,output);
            System.out.println(output);
          }//end try
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
        }//end runSQLQuery
    }//end class

    At present your query string is
    "Select firstName from Address"
    Instead of using the above hardcoded string, try to build the
    query String using logic that checks which check boxes are selected
    by the user.
    Example..
    String query = "SELECT ";
    if (firstName.isSelected()) {
    query = query + " firstName";
    Be sure, you add the comma properly between two fields :-)

  • How to disable a JCheckBox and leave the text the original color?

    When a JCheckBox is disabled, its text gets dim (gray). I need to just dim the checkbox but leave the text the original color.
    I can't find the code where the text color changes when the box is disabled...
    (I have found the code that draws the square and the box at: com.sun.java.swing.plaf.windows.WindowsIconFactory .)
    Any ideas?

    Try this checkbox, i think you could customize to achieve exact behaviour:
    import java.awt.Graphics;
    import javax.swing.JCheckBox;
    import javax.swing.JToggleButton;
    public class KCheckBox extends JCheckBox
        private boolean clickable;
        private boolean enabled2;
        public KCheckBox()
            super();
            init();
         * @param text
        public KCheckBox( String text )
            super( text );
            init();
        private void init()
            setModel( new MyButtonModel() );
            this.clickable = true;
            this.enabled2 = true;
        public void paint( Graphics g )
            // store existing state
            boolean e = ((MyButtonModel)getModel()).isEnabled();
            // if !enabled - set not enabled
            // otherwise - set enabled
            ((MyButtonModel)getModel()).setEnabledNoFire( this.enabled2 );
            super.paint( g );
            // restore previous state
            ((MyButtonModel)getModel()).setEnabledNoFire(e);
        public void setClickable(boolean clickable)
            this.clickable = clickable;
            super.setEnabled(clickable && this.enabled2);
        public boolean isClickable()
            return this.clickable;
        public void setEnabled(boolean enabled)
            this.enabled2 = enabled;
            super.setEnabled(enabled && this.clickable);
        public boolean isEnabled()
            return this.enabled2;
        private class MyButtonModel extends JToggleButton.ToggleButtonModel
            public void setEnabledNoFire( boolean b )
                if (b) {
                    stateMask |= ENABLED;
                } else {
                    stateMask &= ~ENABLED;
    }Edited by: unvadim on Sep 5, 2008 4:41 PM

  • JCheckBox and identation of sub-elements

    I wonder how I can layout a list of checkboxes with sub elements, like a list of checkboxes again (see my ASCII art figure). The sub elements should be indented like the label of the checkbox above.
    I can't use a static value for this indentation, since the size of the icon depends on the L'n'F. On the other side I don't want to loose the connection between the label and the checkbox (means I want to select the checkbox by clicking on the label).
    Any suggestions?
    o First choice
       o Sub choice 1
       o Sub choice 2
    o Second choiceRegards,
    Leif

    Joerg22 wrote:
    leif.bladt wrote:
    The arrangement is indeed fixed. But as I create the checkbox with the following code, I don't know, where the icon ends and where the label starts.
    new JCheckBox("Description")
    In your example your don't use an icon at all. But I assume the icons vary with each checkbox, do they?
    @Kevin
    How do you apply horizontal glue when the components are added in BoxLayout.Y_AXIS? Or do you mean to add a panel for each checkbox?I meant to add a Panel for each JCheckBox. But upon further thought, the Box.createGlue() is an unnecessary step. Just use the X alignment discussed in the BoxLayout [features |http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html#features] section of the tutorial.

  • Accessibilty and JPopupMenu

    I am using JAWS 6 with JDK 1.4.2_06 and Access Bridge 1.2.
    If I add Menuitems to a JMenu which is added to the menubar everything works as expected. One of the menu items is another JMenu, a sub-menu. When JAWS reads this it speaks "submenu" indicating that there is a sub-menu to the right of the current menu item. However, If I attached the exact same menuitems to a JPopupMenu,
    JAWS never speaks "submenu" so the user has no iindication that there is a sub-menu to the right.
    I've taken the attached code from "The JFC Swing Tutorial - Second Edition" and tweaked it slightly so the menubar and popup menu contain the same items.
    It seems as if the accessibility api is expecting the first set of menu items to be attached to a menu parent.
    If worked around this for now by adding another top level menu to the popupmenu to which I add the menuitems.
    Is this a Java or JAWS bug ?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Like MenuDemo, but with popup menus added.
    public class TextFieldDemo {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public JMenuBar createMenuBar() {
    JMenuBar menuBar;
    JMenu menu;
    //Create the menu bar.
    menuBar = new JMenuBar();
    //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");
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    menu.add(mi);
    menuBar.add(menu);
    //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);
    return menuBar;
    public Container createContentPane() {
    //Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);
    //Create a scrolled text area.
    output = new JTextArea(5, 30);
    output.setEditable(false);
    scrollPane = new JScrollPane(output);
    //Add the text area to the content pane.
    contentPane.add(scrollPane, BorderLayout.CENTER);
    return contentPane;
    public void createPopupMenu() {
    JMenuItem menuItem;
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    popup.add(mi[i]);
    //Add listener to the text area so the popup menu can come up.
    MouseListener popupListener = new PopupListener(popup);
    output.addMouseListener(popupListener);
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TextFieldDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create/set menu bar and content pane.
    TextFieldDemo demo = new TextFieldDemo();
    frame.setJMenuBar(demo.createMenuBar());
    frame.setContentPane(demo.createContentPane());
    //Create and set up the popup menu.
    demo.createPopupMenu();
    //Display the window.
    frame.setSize(450, 260);
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    class PopupListener extends MouseAdapter {
    JPopupMenu popup;
    PopupListener(JPopupMenu popupMenu) {
    popup = popupMenu;
    public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
    if (e.isPopupTrigger()) {
    popup.show(e.getComponent(),
    e.getX(), e.getY());
    private JMenuItem[] createAMenu()
    JMenu submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    JMenuItem items[] = new JMenuItem[8];
    //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");
    items[0]=menuItem;
    menuItem = new JMenuItem("Both text and icon");
    menuItem.setMnemonic(KeyEvent.VK_B);
    items[1]=menuItem;
    menuItem = new JMenuItem("icon only");
    menuItem.setMnemonic(KeyEvent.VK_D);
    items[2]=menuItem;
    //a group of radio button menu items
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    items[3]=rbMenuItem;
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    items[4]=rbMenuItem;
    //a group of check box menu items
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    items[5]=cbMenuItem;
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    items[6]=cbMenuItem;
    //a submenu
    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));
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    submenu.add(menuItem);
    items[7]=submenu;
    return(items);

    Hi;
    I want to add chekboxes to a poupup menu ,how can I do that. I already have a submenu with names of columns ton hide and show them using chekcboxes and i want that same menu as a popup when i click in the tableheader.
    thanx

  • JRadioButton/JCheckBox and text alignement

    Hi all,
    It is possible only using JRadioButton and JCheckBox to have when using several
    of these elements to have text on the left aligned to left and the button right aligned
    with the gap in between being variable so that start of text and buttons are aligned.
    I would like to have that
    Text of my fist button    0
    2nd text                  0
    3rd text                  0                        
    ^--- text left aligned    ^---- here the radiobuttons/check boxes right alignedI know how to set text on the left side: myRadioButton.setHorizontalTextPosition(myRadioButton.LEADING).
    This is not a problem.
    Thanx,
    Xavier.

    Looking at this, I can't see an easy way. Using the
    components you specified, I guess I would set the font
    to a fixed size font, and pad the labels with spaces.
    If I was going it, I would make each label a JLabel,
    not assign a label to a checkbox, and put them
    together with a GridLayout. Hope this helpsWell this can be a solution but I would like two things:
    -1 be able to use any font
    -2 have the default behaviour of RadioButton or Checkbox
    that is text also selectable not only the button itself.
    I tried another solution: working the FontMetrics and
    defined gap between text and icon. But it must be buggy
    because it is look and feel (L&F) dependant. In my example,
    it only works as expected for motif L&F (i'm running under XP).
    And funny enough in my real application, it also works on XP.
    Metal that should be the most portable is the worse! :(
    I tried J2SE 1.4.3_02 and 1.5.0beta1: same result reagding
    alignement.
    Is it a bug or a mistake from my side?
    Here is my code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class DoubleAligned extends JFrame {
      protected JMenu lookAndFeelMenu;
      protected Action metalAction;
      protected Action motifAction;
      protected Action windowsAction;
      public static final String METAL_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
      public static final String MOTIF_LOOK_AND_FEEL = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
      public static final String WINDOWS_LOOK_AND_FEEL = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
      protected JPanel singleAlignementPane;
      protected JPanel doubleAlignementPane;
      protected ButtonGroup singleBG;
      protected JRadioButton jRadioButton_s1;
      protected JRadioButton jRadioButton_s2;
      protected JRadioButton jRadioButton_s3;
      protected JRadioButton jRadioButton_s4;
      protected JCheckBox jCheckBox_s1;
      protected Set buttonSet;
      protected ButtonGroup doubleBG;
      protected JRadioButton jRadioButton_d1;
      protected JRadioButton jRadioButton_d2;
      protected JRadioButton jRadioButton_d3;
      protected JRadioButton jRadioButton_d4;
      protected JCheckBox jCheckBox_d1;
      /** Creates a new instance of JSCResultModePanel */
      public DoubleAligned(String title) {
        super(title);
        lookAndFeelMenu = createLookAndFeelMenu();
        JMenuBar mb = new JMenuBar();
        mb.add(lookAndFeelMenu);
        setJMenuBar(mb);
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BorderLayout());
        singleAlignementPane = createSingleAlignPane();
        doubleAlignementPane = createDoubleAlignPane();
        jPanel.add(singleAlignementPane,BorderLayout.WEST);
        jPanel.add(doubleAlignementPane,BorderLayout.EAST);
        setContentPane(jPanel);
      private JPanel createSingleAlignPane() {
        JPanel jPanel = new JPanel();
        jPanel.setBorder(BorderFactory.createTitledBorder("Single aligned (swing default)"));
        // Creation of the layout
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.weighty = 1.0;   //request any extra vertical space
        c.weightx = 1.0;   //request any extra horizontal space
        c.gridwidth = 1;
        c.insets = new Insets(2,2,2,2);
        c.anchor = GridBagConstraints.EAST;
        c.fill = GridBagConstraints.BOTH;
        jPanel.setLayout(gridbag);
        // Creation of sub elements
        singleBG = new ButtonGroup();
        jRadioButton_s1 = new JRadioButton("First radio button long text");
        jRadioButton_s1.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s1.setBackground(Color.PINK);
        jRadioButton_s2 = new JRadioButton("2nd is shorter");
        jRadioButton_s2.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s2.setBackground(Color.GREEN);
        jRadioButton_s3 = new JRadioButton("shortest");
        jRadioButton_s3.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s3.setBackground(Color.RED);
        jRadioButton_s4 = new JRadioButton("4th");
        jRadioButton_s4.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s4.setBackground(Color.MAGENTA);
        singleBG.add(jRadioButton_s1);
        singleBG.add(jRadioButton_s2);
        singleBG.add(jRadioButton_s3);
        singleBG.add(jRadioButton_s4);
        jCheckBox_s1 = new JCheckBox("Check box is also taken into account");
        jCheckBox_s1.setHorizontalTextPosition(JCheckBox.LEADING);
        jCheckBox_s1.setBackground(Color.YELLOW);
        // Layout of all the components (components added column by column)
        c.gridx = 0;
        c.gridy = 0;
        jPanel.add(jRadioButton_s1,c);
        c.gridy = 1;
        jPanel.add(jRadioButton_s2,c);
        c.gridy = 2;
        jPanel.add(jRadioButton_s3,c);
        c.gridy = 3;
        jPanel.add(jRadioButton_s4,c);
        c.gridy = 4;
        jPanel.add(jCheckBox_s1,c);
        return jPanel;
      private JPanel createDoubleAlignPane() {
        JPanel jPanel = new JPanel();
        jPanel.setBorder(BorderFactory.createTitledBorder("Double aligned"));
        // Creation of the layout
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.weighty = 1.0;   //request any extra vertical space
        c.weightx = 1.0;   //request any extra horizontal space
        c.gridwidth = 1;
        c.insets = new Insets(2,2,2,2);
        c.anchor = GridBagConstraints.EAST;
        c.fill = GridBagConstraints.BOTH;
        jPanel.setLayout(gridbag);
        // Creation of sub elements
        doubleBG = new ButtonGroup();
        buttonSet = new HashSet();
        int largerButtonSize = 0;
        jRadioButton_d1 = new JRadioButton("First radio button long text");
        jRadioButton_d1.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d1.setBackground(Color.PINK);
        buttonSet.add(jRadioButton_d1);
        jRadioButton_d2 = new JRadioButton("2nd is shorter");
        jRadioButton_d2.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d2.setBackground(Color.GREEN);
        buttonSet.add(jRadioButton_d2);
        jRadioButton_d3 = new JRadioButton("shortest");
        jRadioButton_d3.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d3.setBackground(Color.RED);
        buttonSet.add(jRadioButton_d3);
        jRadioButton_d4 = new JRadioButton("4th");
        jRadioButton_d4.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d4.setBackground(Color.MAGENTA);
        buttonSet.add(jRadioButton_d4);
        singleBG.add(jRadioButton_d1);
        singleBG.add(jRadioButton_d2);
        singleBG.add(jRadioButton_d3);
        singleBG.add(jRadioButton_d4);
        jCheckBox_d1 = new JCheckBox("Check box is also taken into account");
        jCheckBox_d1.setHorizontalTextPosition(jCheckBox_d1.LEADING);
        jCheckBox_d1.setBackground(Color.YELLOW);
        buttonSet.add(jCheckBox_d1);
        // Layout of all the components (components added column by column)
        c.gridx = 0;
        c.gridy = 0;
        jPanel.add(jRadioButton_d1,c);
        c.gridy = 1;
        jPanel.add(jRadioButton_d2,c);
        c.gridy = 2;
        jPanel.add(jRadioButton_d3,c);
        c.gridy = 3;
        jPanel.add(jRadioButton_d4,c);
        c.gridy = 4;
        jPanel.add(jCheckBox_d1,c);
        return jPanel;
      private JMenu createLookAndFeelMenu() {
        JMenuItem menuItem = null;
        JMenu jMenu = new JMenu("Look and feel");
        // *** Metal menu item ***
        metalAction = new AbstractAction("Metal", null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(METAL_LOOK_AND_FEEL);
        menuItem = jMenu.add(metalAction);
        // *** Motif menu item ***
        motifAction = new AbstractAction("Motif", null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(MOTIF_LOOK_AND_FEEL);
        menuItem = jMenu.add(motifAction);
        // *** Windows menu item ***
        windowsAction = new AbstractAction("Windows",null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(WINDOWS_LOOK_AND_FEEL);
        menuItem = jMenu.add(windowsAction);
        return jMenu;
      private int getMax(int item1, int item2) {
        return item1<item2 ? item2 : item1;
      public void paint(Graphics g) {
        FontMetrics fm = getFontMetrics( g.getFont( ) );
        String stringButton;
        AbstractButton myButton;
        int maxWidth;
        Iterator i;
        maxWidth = 0;
        i = buttonSet.iterator();
        // Hack to have text on the left and left aligned with the buttons themselves
        // on the right and right aligned to.
        // WARNING: Do not use HTML button because Button.getText will return the
        // HTML source not the result. Note also that it's not possible to use
        // Button.getSize().width because it returns the size after the layout process
        // it for display.
        while (i.hasNext()) {
          stringButton = ((AbstractButton)i.next()).getText();
          maxWidth = getMax(maxWidth, fm.stringWidth(stringButton));
        i = buttonSet.iterator();
        int currentWidth;
        int newGap;
        while (i.hasNext()) {
          AbstractButton currentButton = (AbstractButton)i.next();
          stringButton = currentButton.getText();
          currentWidth = fm.stringWidth(stringButton);
          newGap = maxWidth - currentWidth + 10;
          currentButton.setIconTextGap(newGap);
        super.paint(g);
      public void updateLookAndFeel(String lookAndFeel) {
        try {
          UIManager.setLookAndFeel(lookAndFeel);
          SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
          // log an error
      public static void main(String []args) {
        DoubleAligned frame = new  DoubleAligned("A solution to have double alignemnt of several radio buttons/check boxes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

  • Jcheckbox and actionlistener

      if (bathroom.isSelected()){ bathroom is a jcheckbox, why doesnt that work.
    if (bathroom.isSelected()){
    g1.remove(namelabel);
    g1.remove(namelabel);
    g1.remove(bathroom);
    g1.remove(office);
    g1.remove(nurse);
    g1.remove(other);
    g1.setBackground(Color.red);
    p2.add(returnbutton);
    namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
    g1.add(namelabel);
    g1.add(time);
    f1.dispose();
    f1.show();
    Edited by: HermTheWorm on Oct 21, 2007 7:28 PM

    Ok! I misinterpreted your problem. I thought if you want to select or deselect a check box it will execute a command. Am I right?
    So you already have a jbutton with an actionListener and once click it will check what check box is selected and it will execute a certain command.
    e.g.
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == myButton) {
            if(myCheckBox.isSelected()) {
                // your code
    }just follow the example and if it doesn't work please post your Short, Self Contained, Compilable Example or SSCCE so that we can determine the problem.

  • JCheckBox and focus issue

    hi.
    i am usign a JCheckBox as a button (legacy code) as it is a JToggleButton underneath.
    it is in a row of 3 buttons and it iis in the middle. for some reason, i cna't seem to give it default focus. i have tryed setting hte focus, and setting hte default button, and adding it first in a BorderLayout.
    is there anythign i can do?
    thanks
    -annA

    You can only request focus on a component when it is visible.
    Or you can add a WindowListener to the window and implement the windowOpened() method to request focus.
    Or, you can override the addNotify() method of the component to request focus.

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • JCheckBox and TableCellRenderer

    I'm using a boolean value as a column within a JTable. I want to change the color of a JCheckBox from black to red in the column based on a test.
    I created a class to extend JCheckBox which implements TableCellRenderer. When the JTable is displayed, the checkbox is there, but you can't see the check in the box, just a square until you press the mouse key on the checkbox, then either the checked or unchecked
    condition can be seen.
    Here's the setup of the JTable:
    TableName.setDefaultRenderer(Boolean.class,
    new gridTableCellRenderer(DisplayData));
    If I comment out the line above, the checkbox appears correctly showing the checked or unchecked condition without depressing the mousebutton.
    Here's the class itself:
    package NewPackage;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    class gridTableCellRenderer extends JCheckBox implements TableCellRenderer {
    private Vector DisplayData = null;
    public gridTableCellRenderer( Vector DisplayData ) {
    super();
    // setOpaque(true);
    this.DisplayData = DisplayData;
    public Component getTableCellRendererComponent( JTable table,
    Object value, boolean isSelected,
    boolean hasFocus, int row, int column ) {
    Display record = (Display) DisplayData.get(row);
    if ( record.getItemID() == 0 ) {
    switch( column ) {
    case 0:
    // setBackground(Color.red);
    // setForeground(Color.black);
    // setEnabled(false);
    break;
    default:
    break;
    } /* ...end of switch statement... */
    } /* ...end of if ( record.getItemID() == 0... */
    else {
    switch( column ) {
    case 0:
    // setBackground(Color.lightGray);
    // setForeground(Color.black);
    // setEnabled(true);
    break;
    default:
    break;
    } /* ...end of switch statement... */
    } /* ...end of else statement... */
    return this;
    } /* ...end of method getTableCellRendererComponent()... */
    } /* ...end of class declaration gridTableCellRenderer... */
    As you can see, I've commented out all of the logic in an effort to try to find out what was causing the problem. As I said before, the only way I can get the checkboxes to appear correctly is commenting out the line:
    TableName.setDefaultRenderer(Boolean.class,
    new gridTableCellRenderer(DisplayData));
    Thanks in advance....

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
        public Test() {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         String[] head = {"Boolean","String","Boolean"};
         Object[][] data  = {{new Boolean(true), "Hello", new Boolean(false)},
                       {new Boolean(true), "There", new Boolean(true)},
                       {new Boolean(false), "Hello", new Boolean(false)},
                       {new Boolean(true), "There", new Boolean(false)}};
         JTable jt = new JTable(new MyModel(data, head));
         jt.setDefaultRenderer(Boolean.class, new MyRenderer());
         content.add(jt, BorderLayout.CENTER);
         setSize(200,200);
         show();
        public static void main(String[] arghs) { new Test(); }
    class MyModel extends DefaultTableModel {
        public MyModel(Object[][] Data, Object[] Head) { super(Data, Head); }
        public Class getColumnClass(int col) {
         switch (col) {
             case 0:
             case 2: return Boolean.class;
             default: return Object.class;
    class MyRenderer extends JCheckBox implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table,
                       Object value, boolean isSelected,
                       boolean hasFocus, int row, int column ) {
         setSelected(((Boolean)value).booleanValue());
         if (((String)table.getValueAt(row, 1)).equals("Hello")) {
             setBackground(Color.red);
         } else {
             setBackground(Color.pink);
         return this;
    }

Maybe you are looking for