自动选择JTable中的每隔一行

时间:2011-11-04 22:32:04

标签: java swing jtable

我正在尝试创建一个表,其中每个其他行都被选中(主要用于外观)。

我也想知道是否有办法将选择颜色更改为黑色,而不是默认值,这似乎是蓝色。

以下是我现在正在使用的内容:

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 个答案:

答案 0 :(得分:2)

我认为JTable的最简单,最舒适的方法是查找prepareRenderer,然后覆盖

if (isSelected) {
   setBackground(myTable.getBackground); // Color.white
} else {
   setBackground(whatever.Color);
}
抱歉,我无法抗拒,你的代码将是

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();
            }
        });
    }
}