This discussion is archived
4 Replies Latest reply: May 28, 2013 5:17 AM by mKorbel RSS

Swing JTable how search a string and color the row???

1010364 Newbie
Currently Being Moderated
My code posted below performs this action:

If select "Item 1" from ComboBox (combo1), write first row empty and color it... if select "Item2".... etc (for any cbutton click).
This code works fine.


My problem:
How I Can implements this?

Search a string (for example "A1"at column "0" in all rows and after write and color it!

I'm very sorry for my bad english.

classe Table

package prove;

import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JTable;
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();
        combo2 = 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"}));
        combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"A1", "A2", "A3"}));
        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(combo2, 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(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).
                addGap(21, 21, 21).
                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();
    }

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

        String string1 = (String) combo1.getSelectedItem();
        String string2 = (String) combo2.getSelectedItem();

//Da qui parte la condzione
//se seleziono la string Item1, allora popola la tabella, colora la riga e incrementa l'indice delle riga
        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(Color.RED));
                index1 = i;
            }

            table1.setValueAt("pippo1", index, 0);
            table1.setValueAt("A", index, 1);
            table1.setValueAt("B", index, 2);
            table1.setValueAt("C", index, 3);
        }
        if (string1.equals("Item 2")) {
            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(Color.RED));
                index1 = i;
            }

            table1.setValueAt("pippo2", index, 0);
            table1.setValueAt("A2", index, 1);
            table1.setValueAt("B2", index, 2);
            table1.setValueAt("C2", index, 3);
        }
        if (string1.equals("Item 3")) {
            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(Color.RED));
                index1 = i;
            }

            table1.setValueAt("pippo3", index, 0);
            table1.setValueAt("A3", index, 1);
            table1.setValueAt("B3", index, 2);
            table1.setValueAt("C3", index, 3);
        }

    }                                        
    public static void main(String args[]) {


        new Table().setVisible(true);

    }
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox combo1;
    private javax.swing.JComboBox combo2;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table1;
    // End of variables declaration

    public JComboBox getCombo1() {
        return combo1;
    }

    public JComboBox getCombo2() {
        return combo1;
    }

    public void setCombo2(JComboBox combo2) {
        this.combo1 = combo2;
    }

    public JTable getTable1() {
        return table1;
    }

    public void setTable1(JTable table1) {
        this.table1 = table1;
    }
}
//Class CustomTableCellRenderer.. Gestisce il renderer

package prove;

import com.sun.org.apache.regexp.internal.REDebugCompiler;
import java.awt.Color;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;


public class CustomTableCellRenderer extends DefaultTableCellRenderer {
   private Color color;
   private Border border;
        public CustomTableCellRenderer(Color color) {
        super();
        this.color = color;
      
    }

    @Override
  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(table.getValueAt(row, column)==null){
            cell.setBackground(null);
            
        } else if(table.getValueAt(row, column)!=null){
   
            cell.setBackground(color);
              if (cell instanceof JLabel) {
                   ((JLabel) cell).setOpaque(true);
                  ((JLabel) cell).setBackground(color);
             
        ((JLabel) cell).setHorizontalAlignment(CENTER);
        ((JLabel) cell).setFont(new java.awt.Font("Calibri", 1, 12));

            }
        }
 return cell ;
    }
 }
Edited by: user8635532 on 28-mag-2013 2.10
  • 1. Re: Swing JTable how search a string and color the row??? Urgent!!!
    gimbal2 Guru
    Currently Being Moderated
    urgent
    That is only important to you. Mentioning something is urgent will only hurt your chances of getting help as you make it seem like you believe you deserve preferred treatment - just don't do it.
    How I Can implements this?
    You start by reading the documentation of the components involved and you examine the javadocs to know what methods are available, and you go from there. You don't have a problem yet; lack of knowledge is easily solved by reading and researching.
  • 2. Re: Swing JTable how search a string and color the row??? Urgent!!!
    1010364 Newbie
    Currently Being Moderated
    Ok I modified the title!
    You're right. But I tried to read the documentation but i have many difficulties to understand how implemets it. It does not work

    thanks for all...

    Edited by: user8635532 on 28-mag-2013 2.16
  • 3. Re: Swing JTable how search a string and color the row??? Urgent!!!
    r035198x Pro
    Currently Being Moderated
    You need to read about how to use the Highlighter classes http://docs.oracle.com/javase/6/docs/api/javax/swing/text/Highlighter.html
    Here is a complete example http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneHighlightExample.htm
  • 4. Re: Swing JTable how search a string and color the row???
    mKorbel Explorer
    Currently Being Moderated
    1. nice idea, (add_on to XxxRenderer) and quasi autocomplete could be done by
    - Patern
    - Html (created dynamically on runtime)
    - you could ignore 1.st point only about if is possible or not

    2. Renderer side must contains int rowToModel = table.convertRowIndexToModel(row); is there for
    - you want to highlight whole row, then to use this index, my code only cell(s) contains searched value
    - JTable can be sorted, filtered, then Model index and JTables View index living own different, indenpendent life
    - have to override ColumnToModel in case that method table.getTableHeader().setReorderingAllowed(false); isn't set

    3. touched long timing bug in XxxRenderer, when super.getTab...., must be last code line before return value, but safer could be call table.repaint();
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.border.EmptyBorder;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    
    public class MyTableAndRenderer {
    
        private JFrame frame = new JFrame();
        private JPanel panel = new JPanel();
        private String[] items = {"Item 1", "Item 2", "Item 3", "Item 4"};
        private DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel(items);
        private JComboBox combo = new JComboBox(comboBoxModel);
        private JPanel panel1 = new JPanel();
        private String[] columnNames = {"First Name", "Last Name", "Sport",
            "# of Years", "Vegetarian"};
        private Object[][] data = {
            {"Kathy", "Smith", "Item 1", new Integer(5), (false)},
            {"John", "Doe", "Item 1", new Integer(3), (true)},
            {"Sue", "Black", "Item 3", new Integer(2), (false)},
            {"Jane", "White", "Item 3", new Integer(20), (true)},
            {"Joe", "Brown", "Item 3", new Integer(10), (false)}
        };
        private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
            private static final long serialVersionUID = 1L;
    
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        private JTable table = new JTable(model);
    
        public MyTableAndRenderer() {
            panel.setBorder(new EmptyBorder(10, 0, 2, 0));
            panel.add(combo);
            table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus,
                        int row, int column) {
                    int rowToModel = table.convertRowIndexToModel(row);
                    String str = combo.getSelectedItem().toString();
                    if (value.toString().equalsIgnoreCase(str)) {
                        setBackground(Color.RED);
                        table.repaint();
                    } else {
                        setBackground(null);
                        table.repaint();
                    }
                    super.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);
                    return this;
                }
            });
            table.getTableHeader().setReorderingAllowed(false);
            table.setAutoCreateRowSorter(true);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            panel1.setLayout(new GridLayout(1, 1, 10, 10));
            panel1.add(new JScrollPane(table));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(panel, BorderLayout.NORTH);
            frame.add(panel1);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    MyTableAndRenderer fs = new MyTableAndRenderer();
                }
            });
        }
    }

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points