12 Replies Latest reply: May 24, 2013 4:31 AM by 1010364 RSS

    Swing JTAble DefaultTableCellRenderer. Help!!!

    1010364
      Hello,
      I inserted a JTabel in my programm. There is a condiction that colors one or more row.
      The method works well but If select any row of the table, they (out of my condiction) change color!


      The code:

      class CustomTableCellRenderer1 extends DefaultTableCellRenderer {


      public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
      Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
      cell.setBackground(Color.yellow);
      if (cell instanceof JLabel) {
      ((JLabel) cell).setBackground(Color.red);
      ((JLabel) cell).setHorizontalAlignment(CENTER);
      ((JLabel) cell).setFont(new java.awt.Font("Calibri", 1, 12));
      }
      return cell ;
      }
      }


      if (textField.equals("Pippo")) {

      int B = 9;

      int index1 = 0;

      for (int i = 0; i < B; i++) {
      tcol = f3.getJTable().getColumnModel().getColumn(index1);
      tcol.setCellRenderer(new CustomTableCellRenderer());
      index1 = i;


      }


      Thanks
        • 1. Re: Swing JTable DefaultTableCellRenderer. Help!!!
          mKorbel
          but If select any row of the table, they (out of my condiction) change color!

          - method +public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {+

          - contains boolean isSelected, boolean hasFocus, to override those two parameters too

          - there is not required to casting Renderers Component to JLabel

          - Swing Forum (Swing is better place for this question
          • 2. Re: Swing JTable DefaultTableCellRenderer. Help!!!
            PhHein
            Mod: moved to Swing.

            When setting the background of a JLabel you have to make sure it is opaque.
            • 3. Re: Swing JTable DefaultTableCellRenderer. Help!!!
              1010364
              thanks for your quick response. I'm very sorry but this is my first java program! I will try your suggestions soon.
              • 4. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                gimbal2
                Do note that Swing is a slumbering API, its not developed anymore. If you're learning Java I wouldn't focus my time on Swing, focus on learning the core language and important APIs and concepts in stead. If later you need to do something with client user interfaces, consider studying JavaFX 2 which can be named its replacement.

                I advise that because Swing is far from the easiest thing to pick up and does require knowledge of such advanced topics as multithreading. It would be a shame if you got stuck and frustrated with the Java platform just because you can't figure out this one unimportant aspect of Java.
                • 5. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                  1010364
                  I will follow your advice.
                  Unfortunately, it is a program that I have to do. This is the last method that I have to implement. thank you very much. Whne I finished I will concentrate to learn core java language.

                  Thank you very much
                  • 6. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                    mKorbel
                    @gimbal2      wrote Do note that Swing is a slumbering API, its not developed anymore. ....... consider studying JavaFX 2 which can be named its replacement.

                    - slightly disagree in fact that, then (implementations in Java8/JavaFX8) about to allows embedding Components from JavaFX to Swing and vice_versa looks like as very contraproductive, quite useless

                    - maybe to have to accepting that Java7 in todays form is stripped down from original Suns Java7 == todays Java8, with lots of confounding changes in Swings related APIs in Java7

                    - maybe another marketing gimmick
                    • 7. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                      gimbal2
                      I really don't understand anything you post. Not a single thing. Its just a big jumble of words and random thoughts if you ask me. And whats with your need to write in bullet points? Use plain sentences man.
                      • 8. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                        1010364
                        Ok man, I'm sorry I speak english very bad, so I will try to explain my problem again.

                        The code:

                        class CustomTableCellRenderer1 extends DefaultTableCellRenderer {


                        public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
                        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
                        cell.setBackground(Color.yellow);
                        if (cell instanceof JLabel) {
                        ((JLabel) cell).setBackground(Color.red);

                        }
                        return cell ;
                        }
                        }

                        *//methode calling*

                        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

                        String sev = (String) this.severity.getSelectedItem();

                        //severity is variable name of ComboBox

                        //ComboBox selection
                        if (sev.equals("Severe")) {

                        int index = 0;
                        first++;
                        //f3 Frame ehere iis allocated the table.
                        for (int i = 0; i < f3.getJTable().getRowCount(); i++) {
                        if (f3.getJTable().getValueAt(i, 0) == null) {
                        index = i;

                        break;
                        }
                        }


                        The row is correctly colored as I want and every time I press the button next row is colored.

                        The problem:
                        If I clicks at any point of the table, the row selected is colored automatically without pressing the jButton1. I don't understand why!

                        I hope you understand my problem.
                        thanks for your patience
                        • 9. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                          mKorbel
                          - for better help sooner post an SSCCE (http://sscce.org/), short, runnable, compilable

                          - SSCCE just about JTable with XxxTableCellRenderer and JButton firing events

                          - use prepareRenderer in the case that is about stylling, highlighting whole row

                          - use code tags (https://forums.oracle.com/forums/ann.jspa?annID=1391) for relevant parts of your answer contains Java code
                          • 10. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                            1010364
                            Ok I hope to undesrtand what you told me.
                            I copied below the code of the classes; CustomTableCellRenderer and Table.
                            The question:
                            I need to implement a lot of condiction for examample:
                            if ComboBoX1.equals(Item 1)
                            row color must be RED
                            if ComboBoX1.equals(Item 2)
                            row color must be GREEN
                            ...

                            How I have implemented the programm running but any type of event (for example click on empty row) causes the cell renderer.
                            I askk you, which colud be an corretct methode to implement it?
                            I hope you understand me and I'm very sorry for my bad english language.

                            *//Class CustomTableCellRenderer*


                            package prove;

                            import java.awt.Color;
                            import java.awt.Component;
                            import javax.swing.JTable;
                            import javax.swing.table.DefaultTableCellRenderer;


                            public class CustomTableCellRenderer extends DefaultTableCellRenderer {

                            public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
                            Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
                            cell.setBackground(Color.RED);


                            return cell ;
                            }

                            }



                            *//Class Table*
                            package prove;

                            import javax.swing.table.TableColumn;


                            public class Table extends javax.swing.JFrame {


                            public Table() {
                            initComponents();
                            }


                            @SuppressWarnings("unchecked")

                            private void initComponents() {

                            combo1 = new javax.swing.JComboBox();
                            jButton1 = new javax.swing.JButton();
                            jScrollPane1 = new javax.swing.JScrollPane();
                            table1 = new javax.swing.JTable();

                            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

                            combo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

                            jButton1.setText("Button");
                            jButton1.addActionListener(new java.awt.event.ActionListener() {
                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                            jButton1ActionPerformed(evt);
                            }
                            });

                            table1.setModel(new javax.swing.table.DefaultTableModel(
                            new Object [][] {
                            {null, null, null, null},
                            {null, null, null, null},
                            {null, null, null, null},
                            {null, null, null, null}
                            },
                            new String [] {
                            "Title 1", "Title 2", "Title 3", "Title 4"
                            }
                            ));
                            jScrollPane1.setViewportView(table1);

                            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                            getContentPane().setLayout(layout);
                            layout.setHorizontalGroup(
                            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                            .addGap(22, 22, 22)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addContainerGap(77, Short.MAX_VALUE))
                            );
                            layout.setVerticalGroup(
                            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                            .addGap(19, 19, 19)
                            .addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(41, 41, 41)
                            .addComponent(jButton1)
                            .addGap(71, 71, 71)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(31, Short.MAX_VALUE))
                            );

                            pack();
                            }

                            //Condiction example. I need to implement a lot of condiction!!!
                            *private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {*                                        

                            String string1 = (String) combo1.getSelectedItem();
                            TableColumn tcol;

                            int index = 0;

                            if (string1.equals("Item 1")) {

                            for (int i = 0; i < table1.getRowCount(); i++) {
                            if (table1.getValueAt(i, 0) == null) {
                            index = i;

                            break;
                            }
                            }

                            int B = 5;

                            int index1 = 0;

                            for (int i = 0; i < B; i++) {
                            tcol = table1.getColumnModel().getColumn(index1);
                            tcol.setCellRenderer(new CustomTableCellRenderer());
                            index1 = i;

                            }
                            table1.setValueAt("pippo1", index, 0);
                            table1.setValueAt("pippo1"+ "/"+ "pippo2", index, 1);
                            table1.setValueAt("pippo1" + "-" + "pippo2", index, 2);
                            }

                            }


                            public static void main(String args[]) {


                            new Table().setVisible(true);

                            }
                            // Variables declaration - do not modify
                            private javax.swing.JComboBox combo1;
                            private javax.swing.JButton jButton1;
                            private javax.swing.JScrollPane jScrollPane1;
                            private javax.swing.JTable table1;
                            // End of variables declaration
                            }
                            • 11. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                              1010364
                              The solution:


                              public class CustomTableCellRenderer extends DefaultTableCellRenderer {
                                   private static final long serialVersionUID = -3504101284514011307L;

                                   private Color color;

                                   public CustomTableCellRenderer(Color color) {
                                        super();
                                        this.color = color;
                                   }

                                   public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus,
                                             int row, int column) {
                                        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
                                        if (row == 0) {
                                             cell.setBackground(color);
                                        } else {
                                             cell.setBackground(new Color(255, 255, 255));
                                        }
                                        return cell;
                                   }
                              }



                              private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
                                        String string1 = (String) combo1.getSelectedItem();
                                        TableColumn tcol;
                                        int index = 0;
                                        if (string1.equals("Item 1")) {
                                             int B = 4;
                                             // int index1 = 0;
                                             for (int i = 0; i < B; i++) {
                                                  tcol = table1.getColumnModel().getColumn(i);
                                                  tcol.setCellRenderer(new CustomTableCellRenderer(Color.RED));
                                                  // index1 = i;
                                             }
                                             table1.setValueAt("pippo1", index, 0);
                                             table1.setValueAt("pippo1" + "/" + "pippo2", index, 1);
                                             table1.setValueAt("pippo1" + "-" + "pippo2", index, 2);
                                        }
                                        table1.repaint();
                                   }
                              • 12. Re: Swing JTable DefaultTableCellRenderer. Help!!!
                                1010364
                                I'm sorry but it does not work.
                                It works only for row 0.
                                I need to increase any time the row index.

                                if (string1.equals("Item 1"))
                                write row, color row and encreasea the index.

                                I'm sorry!

                                Edited by: user8635532 on 24-mag-2013 4.26