java - 更改单击的 JTable 单元格的背景颜色

标签 java swing colors jtable

我有两个问题

1.我想在鼠标单击时更改 JTable 单元格的颜色。我添加了一个监听器,比如在两种颜色之间切换,如果当前它是绿色,它应该在其他点击时转向吹气

String[][] data = new String[rows][columns];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
table.addMouseListener(new CellClickListener());

// Using following MouseListener

public class CellClickListener extends MouseAdapter{
  public void mouseClicked(MouseEvent e) {
    JTable target = (JTable)e.getSource();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    // How to getCell object here and change its background color to clicked cell
  }
}

2.如何设置不同的列宽,如firstColumn.setWidth(20), secondColumn.setWidth(40)。我已经禁用了自动调整大小 table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

最佳答案

您必须创建自己的 CellRenderer 并使用 MouseAdapter 这是一个 SSCCE 来阐明我的意思: 希望对您有所帮助 =)

public class JTableTest extends JFrame {

    private JPanel      contentPane;
    private JScrollPane scrollPane;
    private JTable      table;
    private int         col;
    private int         rowz;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    teste frame = new teste();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        table = new JTable();
        table.setModel(new DefaultTableModel(new Object[][] { { "", null, null, "" }, { null, null, null, null }, { null, null, null, "" },
                        { null, null, null, null }, }, new String[] { "Column 0", "Column 1", "Column 2", "Column 3" }));
        table.getColumnModel().getColumn(0).setMinWidth(200); // Here's how to
                                                                // change a
                                                                // column width
        scrollPane.setViewportView(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);
            // Select the current cell
            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;
            if (isSelected && row == rowz & column == col)
                c = Color.GREEN;
            label.setBackground(c);
            return label;
        }
    }

}

关于java - 更改单击的 JTable 单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226575/

相关文章:

java - 如何在使用注释的同时使用 mybatis 中的 hashmap 将值插入到行中?

java - 创建 Apache Tiles 简单应用程序时出现异常

java - JTable 在自动刷新方案上插入数据

java - 无法将数据填充/更新到另一个 JTable "B"onclick JTable "A"中的特定行

python - OpenCV Python equalizeHist 彩色图像

opencv - OpenCV 对其 RGB/BGR 颜色空间使用了哪些颜色匹配函数?

java - 如何解决JNA这个问题?

java - 应用程序仅在 Tomcat 重启后工作

java - 使用 jna.jar 和 platform.jar 出现 NoClassDefFoundError

ios - Storyboard全局色调在 Xcode 11.3.1 中未正确显示