JCheckBox in a JMenu

hi,
i have a JCheckBox in a JMenu, this code is implemented since 2 years ago and have always worked. Recently, I have installed the 1.5 Java version and the JcheckBox no longer works. Does anyone had this problem?
thanks in advance
Zede

Remind us why you haven't switched to JCheckBoxMenuItem since...

Similar Messages

  • JCheckBox to JMenu (no ACCELERATOR_KEY shown)

    Hi,
    i have a ActionClass created with this value:
    putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('S', Event.CTRL_MASK, false));If i add this action to JMenu, the accelerator info is shown in the menu and can be used:
    boardMenu.add(showSolutionAction);But if create a JCheckbox with my ActionClass, the accelerator isn't shown and isn't working.
    JCheckBox solutionCheckbox = new JCheckBox(showSolutionAction);
    boardMenu.add(solutionCheckbox);I'm working with Java6b2, but i think it's the same with Java5.
    I think it's an unwanted behavior. What do you think?
    Does someone knows a workaround?
    Cheers,
    Ingo

    I think it's an unwanted behavior. What do you think? I think its desireable behaviour.
    When using a JCheckBox the user already has a visible clue on how to invoke the button if you use a mnemonic. There is no visual clue if you set an accelerator, so how does the user know what the accelerator is.
    Does someone knows a workaround?Two solutions:
    a) JMenuItem overrides the configurePropertiesFromAction() method to specifically set the accelerator. So you can extend JCheckBox to add the same logic:
        protected void configurePropertiesFromAction(Action a) {
            super.configurePropertiesFromAction(a);
            KeyStroke ks = (a==null) ? null :
                (KeyStroke)a.getValue(Action.ACCELERATOR_KEY);
            setAccelerator(ks==null ? null : ks);
        }b) Set the accelerator yourself when you create the check box:
    JCheckBox checkbox = new JCheckBox(action);
    checkbox.setAccelerator(  (KeyStroke)action.getValue(Action.ACCELERATOR_KEY) );

  • JMenu and JCheckBox

    Hi all,
    How to select/unselect more than one JCheckBoxMenuItem in a time in a JMenu ?
    (for instance i'm not able to select 3 item out of 10 in one time -need to do the manip 3 times ...)
    thanks in advance

    Ok, i give you an example to be more concrete:
    Lets say we have a JMenu with Checkbox giving different movie categories (action, thriller,comedy,western...) .
    -> i want to view in my jtable only the categories "action" and "western" by selecting them in the Menu.
    -> but as it's currently implemented, once you select one of the category, the JMenu directly auto-closes, so you have once again to open the menu to select the second.
    Suppose you have 10 checkbox (out of 20) to select...

  • Dynamic jmenu bar

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

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

  • Add Drop Shadow to JMenu Problem

    Hi,
    I got this code from "Swing Hacks", for some reason it does not run for me, but throws exceptions. I can not figure out why this is happening. This code straight out of the book, should be runnable. Below is the custom class, then the driver-test class, then the Exception:
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.*;
    public class CustomPopupMenuUI extends BasicPopupMenuUI{
         public static ComponentUI createUI(JComponent c){
              return new CustomPopupMenuUI();
         public Popup getPopup(JPopupMenu popup, int x,
                   int y){
              Popup pp = super.getPopup(popup, x,y);
              JPanel panel = (JPanel)popup.getParent();
              panel.setBorder(new ShadowBorder(3,3));
              panel.setOpaque(false);
              return pp;
    class ShadowBorder extends AbstractBorder{
         int xoff,yoff;
         Insets insets;
         public ShadowBorder(int x, int y){
              this.xoff = x;
              this.yoff = y;
              insets = new Insets(0,0,xoff,yoff);
         public Insets getBorderInsets(Component c){
              return insets;
         public void paintBorder(Component comp, Graphics g,
                   int x, int y, int width, int height){
              g.setColor(Color.BLACK);
              g.translate(x,y);
              // draw right side
              g.fillRect(width-xoff,yoff,xoff,height-yoff);
              // draw bottom side
              g.fillRect(xoff,height-yoff,width-xoff,yoff);
              g.translate(-x,-y);
    // Driver Below
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    public class MenuTest {
         public static void main(String[] args)throws Exception{
              UIManager.put("PopupMenuUI","CustomPopupMenuUI");
              //UIManager.put("MenuItemUI","LucentMenuItemUI");
              JFrame frame = new JFrame();
              JMenuBar mb = new JMenuBar();
              //mb.setUI(new CustomMenuUI());
              frame.setJMenuBar(mb);
              JMenu menu = new JMenu("File");
              mb.add(menu);
              menu.add(new JMenuItem("Open"));
              menu.add(new JMenuItem("Save"));
              menu.add(new JMenuItem("Close"));
              menu.add(new JMenuItem("Exit"));
              menu = new JMenu("Edit");
              mb.add(menu);
              menu.add(new JMenuItem("Cut"));
              menu.add(new JMenuItem("Copy"));
              menu.add(new JMenuItem("Paste"));
              menu.add(new JMenuItem("Paste Special.."));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add("North",new JButton("Button"));
              frame.getContentPane().add("Center",new JLabel("Label"));
              frame.getContentPane().add("South",new JCheckBox("checkbox"));
              frame.pack();
              frame.setSize(200,150);
              frame.show();
    }Exception:
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPopupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
         at javax.swing.UIDefaults.getUIError(Unknown Source)
         at javax.swing.MultiUIDefaults.getUIError(Unknown Source)
         at javax.swing.UIDefaults.getUI(Unknown Source)
         at javax.swing.UIManager.getUI(Unknown Source)
         at javax.swing.JPopupMenu.updateUI(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JMenu.ensurePopupMenuCreated(Unknown Source)
         at javax.swing.JMenu.add(Unknown Source)
         at hacks.MenuTest.main(MenuTest.java:23)
    advTHANKSance

    I am also using xp and java version 1.4.2_08, but to no avail.. see below:
    C:\workspace\Swing Hacks\src>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    C:\workspace\Swing Hacks\src>java hacks.MenuTest
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:23)
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:30)
    I don't understand what the issue could be..
    Can anyone reproduce this error??

  • Help needed with ItemListeners for JCheckboxes

    Hi,
    I have created a menu called "Test" and it contains toplevel menu item "File"
    and File Menu contains subitems "NEw" and "Exit".
    When i click File->NEW it displays a new Frame named f1 which contains 2
    Jradiobuttons(r1 and r2 ) and 6 Jcheckboxes(c1,c2,c3,c4,c5,c6).
    My Question is how can i write itemlisteners for checkboxes such that after compiling the program when i check anyone of the checkboxes c1,c2,c3 or all c1,c2,c3 then RadioButtob r1 should get enabled.
    similarly when i check anyone of the checkboxes c4,c5,c6 or all c4,c5,c6 then RadioButtob r2 should get enabled.
    I am sending the code i have written .
    Kindly help me.
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    // Make a main window with a top-level menu: File
    public class MainWindow extends JFrame {
        public MainWindow() {
            super("Test");
            setSize(500, 500);
            // make a top level File menu
            FileMenu fileMenu = new FileMenu(this);
            // make a menu bar for this frame
            // and add top level menus File and Menu
            JMenuBar mb = new JMenuBar();
            mb.add(fileMenu);
            setJMenuBar(mb);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exit();
        public void exit() {
            setVisible(false); // hide the Frame
            dispose(); // tell windowing system to free resources
            System.exit(0); // exit
        public static void main(String args[]) {
            w = new MainWindow();
            w.setVisible(true);
        private static MainWindow w ;
        protected JRadioButton r1, r2;
        protected JCheckBox  c1, c2,c3,c4,c5,c6;
        // Encapsulate the look and behavior of the File menu
        class FileMenu extends JMenu implements ActionListener {
            private MainWindow mw;
            private JMenuItem itmPE   = new JMenuItem("NEW");
            private JMenuItem itmExit = new JMenuItem("Exit");
            public FileMenu(MainWindow main) {
                super("File");
                this.mw = main;
                this.itmPE.addActionListener(this);
                this.itmExit.addActionListener(this);
                this.add(this.itmPE);
                this.add(this.itmExit);
            // respond to the Exit menu choice
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == this.itmPE) {
                    Frame f1 = new Frame("ProductMeasurementEvaluationTool");
                    f1.setSize(600,400);
                    f1.setLayout(null);
                    r1 = new JRadioButton("Radiobutton1");
                    r1.setBounds( 50, 70, 104, 24);
                    f1.add(r1);
                    r1.setBackground(Color.white);
                    r2 = new JRadioButton("Radiobutton2");
                    r2.setBounds( 280, 70, 104, 24);
                    f1.add(r2);
                    r2.setBackground(Color.white);
                    c1 = new JCheckBox("Checkbox1");
                    c1.setBounds( 80, 100, 93, 24);
                    f1.add(c1);
                    c1.setBackground(Color.white);
                    c2 = new JCheckBox("Checkbox2");
                    c2.setBounds( 80, 120, 93, 24);
                    f1.add(c2);
                    c2.setBackground(Color.white);
                    c3 = new JCheckBox("Checkbox3");
                    c3.setBounds( 80, 140, 93, 24);
                    f1.add(c3);
                    c3.setBackground(Color.white);
                    c4 = new JCheckBox("Checkbox4");
                    c4.setBounds( 320, 100, 93, 24);
                    f1.add(c4);
                    c4.setBackground(Color.white);
                    c5 = new JCheckBox("Checkbox5");
                    c5.setBounds( 320, 120, 93, 24);
                    f1.add(c5);
                    c5.setBackground(Color.white);
                    c6 = new JCheckBox("Checkbox6");
                    c6.setBounds( 320, 140, 93, 24);
                    f1.add(c6);
                    c6.setBackground(Color.white);
                    f1.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                    f1.setVisible(true);
                }else {
                    mw.exit();
    }

    hi dek delirium,
    Thanks for the fast reply.. i have compiled the code but i got some errors ...
    i am using JCreator as IDE. i am posting the complete code and errors..
    thankyou
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.JComponent;
    // Make a main window with a top-level menu: File
    public class MainWindow extends JFrame {
        public MainWindow() {
            super("Test");
            setSize(500, 500);
            // make a top level File menu
            FileMenu fileMenu = new FileMenu(this);
            // make a menu bar for this frame
            // and add top level menus File and Menu
            JMenuBar mb = new JMenuBar();
            mb.add(fileMenu);
            setJMenuBar(mb);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exit();
        public void exit() {
            setVisible(false); // hide the Frame
            dispose(); // tell windowing system to free resources
            System.exit(0); // exit
        public static void main(String args[]) {
            w = new MainWindow();
            w.setVisible(true);
        private static MainWindow w ;
        protected JRadioButton r1, r2;
        protected JCheckBox  c1, c2,c3,c4,c5,c6;
        // Encapsulate the look and behavior of the File menu
        class FileMenu extends JMenu implements ActionListener {
            private MainWindow mw;
            private JMenuItem itmPE   = new JMenuItem("NEW");
            private JMenuItem itmExit = new JMenuItem("Exit");
            public FileMenu(MainWindow main) {
                super("File");
                this.mw = main;
                this.itmPE.addActionListener(this);
                this.itmExit.addActionListener(this);
                this.add(this.itmPE);
                this.add(this.itmExit);
            // respond to the Exit menu choice
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == this.itmPE) {
                    Frame f1 = new Frame("ProductMeasurementEvaluationTool");
                    f1.setSize(600,400);
                    f1.setLayout(null);
                    r1 = new JRadioButton("Radiobutton1");
                    r1.setBounds( 50, 70, 104, 24);
                    f1.add(r1);
                    r1.setBackground(Color.white);
                    r2 = new JRadioButton("Radiobutton2");
                    r2.setBounds( 280, 70, 104, 24);
                    f1.add(r2);
                    r2.setBackground(Color.white);
                    CBGroup l1 = new CBGroup(r1); // Listener that enables r1
                    CBGroup l2 = new CBGroup(r2); // Listener that enables r1
                    c1 = new JCheckBox("Checkbox1");
                    c1.setBounds( 80, 100, 93, 24);
                    f1.add(c1);
                    c1.setBackground(Color.white);
                    c2 = new JCheckBox("Checkbox2");
                    c2.setBounds( 80, 120, 93, 24);
                    f1.add(c2);
                    c2.setBackground(Color.white);
                    c3 = new JCheckBox("Checkbox3");
                    c3.setBounds( 80, 140, 93, 24);
                    l1. add (c1,c2,c3);
                    f1.add(c3);
                    c3.setBackground(Color.white);
                    c4 = new JCheckBox("Checkbox4");
                    c4.setBounds( 320, 100, 93, 24);
                    f1.add(c4);
                    c4.setBackground(Color.white);
                    c5 = new JCheckBox("Checkbox5");
                    c5.setBounds( 320, 120, 93, 24);
                    f1.add(c5);
                    c5.setBackground(Color.white);
                    c6 = new JCheckBox("Checkbox6");
                    c6.setBounds( 320, 140, 93, 24);
                    l2.add (c4,c5,c6);
                    f1.add(c6);
                    c6.setBackground(Color.white);
                    f1.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                    f1.setVisible(true);
                }else {
                    mw.exit();
        public class CBGroup {
            ArrayList<JCheckBox> triggers = new ArrayList<JCheckBox> ();
            JRadioButton controlledItem;
            public CBGroup(JRadioButton anItem) {
                controlledItem = anItem;
            public void add(JCheckBox... someTriggers) {
                for (JCheckBox cb : someTriggers) {
                    cb.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ie) {
                            controlItem();
                    triggers.add(cb);
            public boolean isAnyActive() {
                for (JCheckBox cb : triggers)
                    if (cb.isSelected())
                        return true;
                return false;
            private void controlItem() {
                controlledItem.setSelected(isAnyActive());
    }The errors i got are
    Z:\JCRA\MainWindow.java:115: <identifier> expected
    ArrayList<JCheckBox> triggers = new ArrayList<JCheckBox> ();
    ^
    Z:\JCRA\MainWindow.java:122: <identifier> expected
    public void add(JCheckBox... someTriggers) {
    ^
    Z:\JCRA\MainWindow.java:143: <identifier> expected
    ^
    Z:\JCRA\MainWindow.java:145: '}' expected
    ^
    4 errors

  • 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);
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Problem with JCheckBox in a JTable

    Hello,
    I have a JTable with JCheckBox as Editor for boolean values.
    I added a ListSelectionListener on that JTable.
    My problem is :
    when I click on a cell which have a JCheckBoxEditor, there is only one event generated : the one which unselect the row previously selected.
    So i can't answer the selection.
    what could have append ?
    thanks a lot.
    fleur.

    hi,
    I have no custom editor for this table.
    here is my code :
    public VDEComposant(Locale langue,InterfaceModeleur listener,Composant composant,int largeur) {
    super(langue,listener,largeur);
    this.setLayout(new BorderLayout());
    _modele=listener.getModele();
    _composantCourant=composant;
    this.addComposantsListener((ComposantsListener)listener.getGestionnaire());
    construitBarreOutils();
    setNbLigne1(this.listeComposant(composant).size());
    int m=0;
    if (composant==Composant.COMPOSANT){
    _donCompPereApTM=this.creeModeleDonnee1(composant);
    _donCompPereApTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompPereApTM));
    m=1;
    else{
    if (composant.getPere()==Composant.COMPOSANT){
    _donCompApTM=creeModeleDonnee1(composant);
    _donCompApTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompApTM));
    else {
    _donCompUtTM=creeModeleDonnee1(composant);
    _donCompUtTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompUtTM));
    getTableau1().addMouseListener(((OngletDonnees)((OngletDonnees)getIHM().getOngletDonnees())).getOngletComposants());
    MultipleComboBoxCellEditor editor = new MultipleComboBoxCellEditor(new JComboBox());
    getTableau1().getColumnModel().getColumn(4+m).setCellEditor(editor) ;
    getTableau1().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableau1().getSelectionModel().addListSelectionListener(this);
    Dimension d1 = new Dimension(_largeur, getNbLigne1()*16);
    JScrollPane sc1 = new JScrollPane(getTableau1());
    sc1.setViewportView(getTableau1());
    if((composant.getPere()!=null)&&(composant.getPere()!=Composant.COMPOSANT)){
    this.add(_outils,BorderLayout.NORTH);
    String s="";
    if((composant.getPere()==null)||(composant.getPere()==Composant.COMPOSANT)){
    String sc="";
    if(composant==Composant.COMPOSANT_IMAGE){
    sc=" "+_ressources.getString("images");
    if(composant==Composant.COMPOSANT_LINEAIRE){
    sc=" "+_ressources.getString("lineaires");
    if(composant==Composant.COMPOSANT_METAD){
    sc=" "+_ressources.getString("lotdonnees");
    if(composant==Composant.COMPOSANT_NGS){
    sc=" "+_ressources.getString("nongraphiques");
    if(composant==Composant.COMPOSANT_SURFACIQUE){
    sc=" "+_ressources.getString("surfaciques");
    if(composant==Composant.COMPOSANT_SYMBOLIQUE){
    sc=" "+_ressources.getString("symboliques");
    s=_ressources.getString("liste_composant")+sc;
    else{
    s=_ressources.getString("description_composant");
    JLabel lab = new JLabel(s,JLabel.CENTER);
    JPanel inter = new JPanel(new GridLayout(1,1));
    inter.add(lab);
    inter.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createEtchedBorder()));
    Box boite1 = Box.createVerticalBox();
    boite1.add(inter);
    boite1.add(sc1);
    _inter.add(boite1);
    //ajout du deuxieme tableau
    _donAttCompTM=this.creeModeleDonnee2(composant);
    _donAttCompTM.addTableModelListener(this);
    setTableau2(new JTable(_donAttCompTM));
    getTableau2().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableau2().getSelectionModel().addListSelectionListener(this);
    getTableau2().addMouseListener(((OngletDonnees)((OngletDonnees)getIHM().getOngletDonnees())).getOngletComposants());
    //ComboBox pour saisir le type de l'attribut
    _typeA = new JComboBox();
    _typeA.addItem(TypeEtendu.DATE.getNom());
    _typeA.addItem(TypeEtendu.DOMAINE.getNom());
    _typeA.addItem(TypePrimitif.ENTIER.getNom());
    _typeA.addItem(TypePrimitif.LOGIQUE.getNom());
    _typeA.addItem(TypePrimitif.REEL.getNom());
    _typeA.addItem(TypePrimitif.TEXTE.getNom());
    (getTableau2().getColumnModel().getColumn(3)).setCellEditor(new DefaultCellEditor(_typeA));;
    //renderer pour la colonne des nom qui indique en gras l'attribut identifiant
    getTableau2().getColumnModel().getColumn(1).setCellRenderer(new AttributTableCellRenderer(_composantCourant));
    Dimension d2 = new Dimension(_largeur ,(getNbLigne2()*16));
    JScrollPane sc2 = new JScrollPane(getTableau2());
    sc2.setViewportView(getTableau2());
    _inter.createVerticalStrut(16);
    inter = new JPanel(new GridLayout(1,1));
    lab = new JLabel(_ressources.getString("attributs"),JLabel.CENTER);
    inter.add(lab);
    inter.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createEtchedBorder()));
    Box boite2=Box.createVerticalBox();
    boite2.add(inter);
    boite2.add(sc2);
    _inter.add(boite2);
    if((composant.getPere()!=null)&&(composant.getPere()!=Composant.COMPOSANT)){
    this.add(_inter,BorderLayout.CENTER);
    else{
    this.add(_inter,BorderLayout.NORTH);
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm =(ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    else {
    int ligneSel = lsm.getMinSelectionIndex();
    if(e.getSource()==getTableau2().getSelectionModel()){
    String alias = (String) _donAttCompTM.getValueAt(ligneSel,1);
    attribut = composantCourant.getAttribut(alias);
    else if(e.getSource()==getTableau1().getSelectionModel()){
    VectorTableModel vtm = null;
    int i = 0;
    if(_donCompApTM != null){
    vtm = _donCompApTM;
    if(_donCompPereApTM != null){
    vtm = _donCompPereApTM;
    i =1;
    if(vtm != null){
    String alias = (String) vtm.getValueAt(ligneSel,i);
    composantSelectionne= modele.getComposant(alias);
    else{
    composantSelectionne=composantCourant;
    I hope it make sens,
    thanks.

  • How to set cell background color for JCheckBox renderer in JTable?

    I need to display table one row with white color and another row with customized color.
    But Boolean column cannot set color background color.
    Here is my codes.
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.TreeSet;
    public class BooleanTable extends JFrame
        Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
        String[] header = {"CheckBoxes"};
        public BooleanTable()
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            TableModel model = new AbstractTableModel()
                public String getColumnName(int column)
                    return header[column].toString();
                public int getRowCount()
                    return data.length;
                public int getColumnCount()
                    return header.length;
                public Class getColumnClass(int columnIndex)
                    return( data[0][columnIndex].getClass() );
                public Object getValueAt(int row, int col)
                    return data[row][col];
                public boolean isCellEditable(int row, int column)
                    return true;
                public void setValueAt(Object value, int row, int col)
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
            JTable table = new JTable(model);
            table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
            getContentPane().add( new JScrollPane( table ) );
            pack();
            setLocationRelativeTo( null );
            setVisible( true );
        public static void main( String[] a )
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            new BooleanTable();
        private class MyCellRenderer extends JCheckBox implements TableCellRenderer
            public MyCellRenderer()
                super();
                setHorizontalAlignment(SwingConstants.CENTER);
            public Component getTableCellRendererComponent(JTable
                                                           table, Object value, boolean isSelected, boolean
                                                           hasFocus, int row, int column)
                if (isSelected) {
                   setForeground(Color.white);
                   setBackground(Color.black);
                } else {
                   setForeground(Color.black);
                   if (row % 2 == 0) {
                      setBackground(Color.white);
                   } else {
                      setBackground(new Color(239, 245, 217));
                setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
             return this;
    }

    Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
    Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
    private class MyCellRenderer implements TableCellRenderer {
        private JPanel    _panel = null;
        private JCheckBox _checkBox = null;
        public MyCellRenderer() {
            //  Create & configure the gui components we need
            _panel = new JPanel( new BorderLayout() );
            _checkBox = new JCheckBox();
            _checkBox.setHorizontalAlignment( SwingConstants.CENTER );
            // Layout the gui
            _panel.add( _checkBox, BorderLayout.CENTER );
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            if( isSelected ) {
               _checkBox.setForeground(Color.white);
               _panel.setBackground(Color.black);
            } else {
               _checkBox.setForeground(Color.black);
               if( row % 2 == 0 ) {
                  _panel.setBackground(Color.white);
               } else {
                  _panel.setBackground(new Color(239, 245, 217));
            _checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
            return _panel;
    }

  • Scroll down/up functionality in a jMenu?

    What i mean is a jMenu similar to that of internet explorer's
    Favorites menu. When you have a ton of favorites you get a little arrow
    pointing down or up depending on where you are in the menu. Is it possible to implement something similar in java with a jmenu? if so how?
    Ps thanks to all who helped with my previous JMenu question. I got it figured out :)

    Found this for you
    http://forum.java.sun.com/thread.jsp?forum=57&thread=310457&message=1250922#1250922

  • How do I add a JCheckBox to a JTable - URGENT HELP NEEDED

    Hello All,
    This is kicking my butt. I need to create a JTable that I can dynamically add and delete rows of data to and this table must contain a JCheckBox which I can read the value of. I've been able to find examples out there that provides the ability to have a JCheckBox in the JTable, but do not also provide the function to add / delete rows from the JTable. I need to have both funtions in my table. Can somebody out there please help me with this?
    Here's a simple example that I'm working with as a test to figure this out. This example has the functionality to add rows of data.
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel();
              JTable table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", "v2" });
              model.addRow(new Object[] { "v3", "v4" });
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane,BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[]{"Test", new Boolean(true)});
    }

    I got it, I added the public Class getColumnClass to new DefaultTableModel(). Here it is for your viewing pleasure.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         JTable table;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel()
                   public Class getColumnClass(int col)
                        switch (col)
                             case 1 :
                                  return Boolean.class;
                             default :
                                  return Object.class;
              table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", new Boolean(false)});
              model.addRow(new Object[] { "v3", new Boolean(false)});
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane, BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[] { "Karl", new Boolean(true)});

  • How to change background color to JCheckBox in a JTable?

    Dear Friends,
    I have an JTable in my application. It has four columns. First, third and fourth column contains JCheckBox (JCheckBox is created using Boolean.class), secod column contains values.
    I have to change some of the cell color where JCheckBox is present.
    Could anyone please tell me how to change the color of the cell in the JTable?
    Thanks in advance,
    Sathish kumar D

    You would use a custom renderer.
    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db
    Alternative link: SSCCE
    Edited by: Darryl.Burke

  • Using a JCheckBox in the header of a JTable

    I would like to know if it is possible to put a JCheckBox in the header of a column of a JTable.
    In fact my table has several columns and its first column uses checkboxes to signify the seleced items in the table. I would like to have a checkbox in the header of this column so when it is checked, I select all possible items from the table (not all rows are selectable).
    I have not seen any eample of putting something other than text in table headers. Does anyone know if this is possible and how to do it?

    I haven't tried check boxes but I use my own header renderers for other purposes. They are the same as cell renderers, so this sort of thing should work...
    TableColumn tc = myTable.getColumnModel().getColumn(0);
    tc.setHeaderRenderer(new CheckHeaderRenderer());
    class CheckHeaderRenderer extends JCheckBox implements TableCellRenderer
      public Component getTableCellRendererComponent(JTable table,
                                               Object  value,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int     row,
                                               int     column)
        // whatever
        return this;

  • 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...

Maybe you are looking for

  • ICloud flags known good email as junk!

    For the past few months, iCloud mail has frequently flagged known good email as junk. In all cases, the messages that are flagged are from correspondents who have been sending me messages for years without any problem. Now, all of a sudden, iCloud th

  • Why were my PDFs so small in Megabytes size?

    Hi, Just something that has been bugging me - I recently sent 64 pages of a magazine to the printers with each page exported as a seperate pdf using the press quality preset. I was surprised and alarmed at the small file sizes of the pdfs - many page

  • Interview Questions :: Correct questions to ask ?

    Hi, I just got off another Interview that I took & was disappointed once again. We are looking for mid-level Programmers who can write good code ( which would initiate good debates ) as well as "think" on thier own ( not just patch freely avaliable c

  • File Vault back-up time machine no longer working

    For some time it worked.  As soon as I logged out my encrypted Home Folder was backed-up.  Then the last 2 months it will not back-up my home folder.  Is there anyway to make it happen?

  • Reboot lost all purchased songs

    When I downloaded the new version of iTunes, it started downloading songs I didn't have, then my computer crashed and didn't turn back on so I had to reboot it. I lost all my music, especially the ones I actually care about like my purchased music. I