Marco Silvestri
Marco Silvestri

Reputation: 35

Java - Change row color based on cell content

I have a Java application that shows things from a database. I would like to modify the colour of the rows based on the content of a cell. I tried to insert an if cycle in the data retrieving process from databse using setBackground property but without succeding in that.

Here there is code. What I'm doing wrong?

public class TableFrame2 extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                String user = "root";
                String password = "";
                TableFrame2 frame = new TableFrame2(user, password);
                frame.setVisible(true);             


            }
        });
    }

    /**
     * Create the frame.
     * @return 
     */

    public TableFrame2(String user, String password) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 399, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JScrollPane scrollPane = new JScrollPane();
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);
        table.setEditingColumn(0);
        table.setEditingRow(0);
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.setFillsViewportHeight(true);
        table.setBackground(Color.WHITE);
        table.setRowSelectionAllowed(true);
        model.addColumn("iD");
        model.addColumn("name");
        model.addColumn("type");
        table.setPreferredScrollableViewportSize(new Dimension(200, 200)); 
        scrollPane.setViewportView(table);
        try {
            String dateMerged = "2015-01-30";//yearField.getText() + "-" + monthField.getText() + "-" + dayField.getText();

            Connection connection = MysqlConnector.dbConnection(user, password);
            String query = "SELECT * FROM booking, band WHERE room_idRoom = 2 AND idBand = band_idBand AND dateBooking BETWEEN '" +dateMerged+" 00:00:00' AND '" +dateMerged+" 23:59:59'";
            PreparedStatement pst = connection.prepareStatement(query);
            ResultSet rs = pst.executeQuery();
            while (rs.next()){
                String bandName = rs.getString("nameBand");
                String bookingType = rs.getString("typeBooking");
                String bookingId = rs.getString("idBooking");
                model.addRow(new Object[] { bookingId, bandName,bookingType });

                if (bookingType == "Recording"){
                    table.setBackground(Color.RED);
                }
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.TRAILING)
                .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 114, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(89, Short.MAX_VALUE))
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
    }
}

Upvotes: 0

Views: 411

Answers (1)

camickr
camickr

Reputation: 324098

Check out Table Row Rendering which allows you do to custom rendering without creating multiple custom renderers for the different data types in your table.

Upvotes: 1

Related Questions