Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically selecting every other row in a JTable

Tags:

java

swing

jtable

I'm trying to create a table where every other row is selected (for looks, mainly).

I'm also wondering if there's a way to change the selection color to black, instead of the default, which seems to be blue.

Here's what I'm using now:

public class Statistics {

    private JFrame frame;
    private JPanel contentPane;

    public static void main(String[] arguments) {
        new Statistics().construct();
    }

    public void construct() {
        frame = new JFrame("Statistics");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setResizable(false);
        frame.add(getComponents());
        frame.pack();
        frame.setVisible(true);
    }

    public JPanel getComponents() {
        contentPane = new JPanel(new FlowLayout());     
        String[] columnNames = { "Statistic name", "Statistic value" };
        Object[][] data = { { "Score", "0"}, {"Correct percentage", "100%" } };
        JTable table = new JTable(data, columnNames);       
        JScrollPane scrollPane = new JScrollPane(table);
        contentPane.add(scrollPane);        
        return contentPane;
    }
}

1 Answers

I think that easiest and confortable way for JTable would be to look for prepareRenderer, then there to override

if (isSelected) {
   setBackground(myTable.getBackground); // Color.white
} else {
   setBackground(whatever.Color);
}

sorry I can't resist, your code would be

import java.awt.*;
import javax.swing.*;

public class Statistics {

    private JFrame frame;
    private JPanel contentPane;
    private String[] columnNames = {"Statistic name", "Statistic value"};
    private Object[][] data = {{"Score", "0"}, {"Correct percentage", "100%"}};
    private JTable table = new JTable(data, columnNames);
    private JScrollPane scrollPane = new JScrollPane(table);

    public Statistics() {
        frame = new JFrame("Statistics");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(getComponents());
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel getComponents() {
        contentPane = new JPanel(new BorderLayout(10, 10));        
        table.getColumnModel().getColumn(0).setPreferredWidth(150);
        table.getColumnModel().getColumn(1).setPreferredWidth(100);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        contentPane.add(scrollPane, BorderLayout.CENTER);
        return contentPane;
    }

    public static void main(String[] arguments) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Statistics statistics = new Statistics();
            }
        });
    }
}
like image 55
mKorbel Avatar answered Feb 14 '26 12:02

mKorbel