简体   繁体   中英

JAVA - How to change JTable row color after clicking on it?

I 'ma Java beginner. I create an application with a JTable which is populated with a database. In my database I have some 'news'. In my JTable I display titles of 'news' and when an user click on a row, it display a popup with the right contents of the news. But I want to colorize the cell which are 'read' when the user clicked on it.

I use my own TableModel.

I hope I'm clear...

If I need to put some code, tell me what please...

Found this example of how to get the table cell on mouseClick: http://codeprogress.com/java/showSamples.php?index=52&key=JTableValueofSelectedCell

You can use this to get the selected row and column.

Then you need to create a custom TableCellRenderer, possibly as an inner class so that it can use the selected row and column data and set the background of the cell to your highlighted color

public class JTableTest extends JFrame {

    private JTable      table;
    private int         col;
    private int         rowz;


    /**
     * Create the frame.
     */
    public JTableTest() {
        initComponents();
    }

    private void initComponents() {
        /** any other components */

        table = new JTable();//create the table
        table.setDefaultRenderer(Object.class, new CustomModel());
        table.addMouseListener(new CustomListener());
    }

    public class CustomListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            super.mouseClicked(arg0);
            //get the clicked cell's row and column
            rowz = table.getSelectedRow();
            col = table.getSelectedColumn();

            // Repaints JTable
            table.repaint();
        }
    }

    public class CustomModel extends DefaultTableCellRenderer {


        private static final long   serialVersionUID    = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            Color c = Color.WHITE;//define the color you want
            if (isSelected && row == rowz & column == col)
                c = Color.GREEN;
            label.setBackground(c);
            return label;
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM