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

Similar Messages

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

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

  • How do the AbstractTableModel, ColumnModel and TableCellRenderer interact?

    could someone please explain to me how the AbstractTableModel, TableColumnModel and the TableCellRenderer interact?
    That is, if I have a table which used a custom AbstractTableModel, and a custom TableCellRenderer, then how do I cause the renderer to render the correct data?
    Do I have to manually invoke it from my table model? does it get called automatically for every column/row combination?
    also if I want to add a column to the table and I use:
    TableColumnModel's addColumn(TableColumn colum), do I have to invoke AbstractTableModel's fireTableStructureChanged() as well?
    Also, I implemented AbstractTableModel's
    Object valueAt(int row, int column)
    but that method is never invoked in my code. Is that ok?
    int getRowCount(), and int getColumnCount() are invoked on the other hand.
    nir

    I misspelled the name of the method.
    I was using Object getValueAt(int row, int column)...
    still this method is never invoked (I have debug messages there and they are never shown).
    And I am setting the default renderer...
    Here is my ccode:
       // this is how I define my table and table model.
       // PlayerTableDataModel is class implementing AbstractTableModel
       // dataSource is the object that will supply the data that will be presented in the table.
       PlayerTableDataModel tableModel = new PlayerTableDataModel(dataSource);
       table = new JTable(tableModel);
       table.getTableHeader().setReorderingAllowed(false);
       tableModel.setTable(table);
       table.setDefaultRenderer(RoundResult.class, new RoundResultRenderer(dataSource));
       table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);Here is my PlayerTableDataModel class:
    public class PlayerTableDataModel extends AbstractTableModel
        private DataSource dataSource;
        private JTable table;
        public PlayerTableDataModel(DataSource dataSource) {
         super();
         this.dataSource; = dataSource;;     
        // This is the method I invoke when I want to dynamically add a new column to the table.
        public void addNewColumn(GameTableHeaderRenderer headerRenderer) {
         TableColumn newColumn = new TableColumn(getColumnCount());
         newColumn.setHeaderRenderer(headerRenderer);
         newColumn.setResizable(true);
         TableColumnModel cm = table.getColumnModel();
         cm.addColumn(newColumn);
         fireTableStructureChanged();
        public void setTable(JTable table) {
         this.table = table;
        public int getRowCount() {
         return dataSource.getNumRoundsPlayed();
        public int getColumnCount() {
         if (table == null) {
             return 0;
         return dataSource.numberOfPlayers();
        public Object getValueAt(int row, int column) {
         System.out.println("this is never shown");
        public boolean isCellEditable(int row, int col) {
            return false;      
        // I want each cell in the table to hold an object of class RoundResult
        public Class getColumnClass(int c) {
         return RoundResult.class;
    }why do I have to implement getValueAt(), if it is never invoked?

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

  • JCheckbox and DPI

    Java version 1.5.0_06
    I have a column in a table that contains check boxes. Using the Windows look and feel the spacing (insets) around the check box in each cell is not proportionally the same for 96 DPI as it is for 120 DPI.
    Using the default look and feel the check boxes are proportionally the same.
    Is there a way to keep the proportions the same regardless of the DPI setting?
    Thanks for you help

    Merging 2 cells or mergin 2 different columns into 1 column?
    if u need to merge 2 cells for different rows here is the link
    http://codeguru.earthweb.com/java/Swing/JTable/index.shtml
    If you r trying to make 2 column values in one column create custom cell renderer and editor, which will be a JPanel having JTextField and Combo box.
    There is an article in the given link which shows how to set any swing component as a cell renderer (and i guess as a cell editor).

  • Change the 'disabled color text' of JCheckBox and JRadioButton

    With a JTextComponent item, you can change the disabled color text with :
    item.setDisabledTextColor(Color.blue);
    But with a JToggleButton item (JCheckBox, JRadioButton) I can't change the disabled color of its text .
    Does anyone have an idea about what I can do ??
    Thanks a lot
    ps: disabled doesn't mean deselected

    Try to set the color of disabled text with the same background color.

  • Association between Jcheckboxes and lines of JTable

    Hello everybody,
    I would like to add a JChekBox to each line of my JTable knowing that the number of lines is given only at the time of the execution. The problem is that the contructor of JscrollPane can take only one JComponent in parameters:
    JScrollPane scrollpane=new JScrollPane(MyJTable);
    How can I make association line-JChekBox dynamically.
    I m waiting for your answers impatiently.
    Thank you for being attentive

    I don't understand your question. You where given a link to the JTable tutorial, that showed you how to add check boxes to the table.
    This is done by adding Boolean values to the TableModel. So once you know the number of rows in the table you create a simple loop and do:
    table.setValueAt(row, new Boolean(true) );

  • JCheckBox and ActionEvent question

    Hey guys,
    I was wondering if it was possible to get all the checked Items in one event. I have one form and three panels that have a number of checkboxes in it. I was wondering if there was a way to be able to collect all of the checked items when i clicked a button?
    Any suggestions would be appreciated,, Thanks!
    Cheers,
    -Arch-

    my checkboxes are dynamic, it depends on how many of these checkable items were in the text file that the program reads at the start... so how exactly do i check all the checkboxes?
    do i pass the form on when i click the button?

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

Maybe you are looking for

  • How do you use user defined error messages in Value Help?

    Hi, I'm currently working on a Modifiable Value Help Selector in Web Dynpro Java, and I want to use a user defined error message when I validate the values entered by a user. Currently, it's returning its default error message ("Character <string> do

  • All music, shows, films etc not showing up in itunes but still on computer

    Hi all - my computer froze sometime in the night - i restarted it and now have lost my library in itunes. It must still be somewhere on the computer i have exactly the same free HD space as before - I also back up to my time capsule. My question is -

  • Help, Mac Pro wouldn't start now stuck on grey screen

    Hi, My Mac Pro computer wouldn't start up properly. Sometimes I would press the button 30 times and still it wouldn't start. I have taken it to a Authorised Apple shop and first of all had a new graphics board replaced. A week later the same problem,

  • [JS] Problem in importing data.

    Hello I am trying to place a .doc file in my document(textframe). For that i am using following script var myDocument = app.activeDocument; var myTextFrame = myDocument.pages.item(0).textFrames.add({geometricBounds:myGetBounds(myDocument, myDocument.

  • Duplex Printing on Glossy Paper

    I have a MG 7150 printer. I am making a photo album but encountered a problem when I tried to print on my double-sided glossy paper. When I select any paper type, other than plain paper, the option for Duplex printing is 'greyed' out.  I tried plain