【问题标题】:JAVA - How to change JTable row color after clicking on it?JAVA - 单击后如何更改 JTable 行颜色?
【发布时间】:2015-08-19 14:43:58
【问题描述】:

我是 Java 初学者。 我创建了一个带有 JTable 的应用程序,该 JTable 填充了一个数据库。 在我的数据库中,我有一些“新闻”。在我的 JTable 中,我显示“新闻”的标题,当用户单击一行时,它会显示一个包含正确新闻内容的弹出窗口。 但是我想在用户点击它时为“读取”的单元格着色。

我使用自己的 TableModel。

我希望我很清楚......

如果我需要输入一些代码,请告诉我...

【问题讨论】:

  • 欢迎来到 SO!发布必要的最少代码,以解决您试图解决的困惑(即有人可以准确地看到您需要帮助的地方)。
  • 实现表格单元格渲染器并更改用于渲染的组件的颜色。

标签: java colors jtable


【解决方案1】:
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;
        }
    }

}

【讨论】:

    【解决方案2】:

    找到了如何在 mouseClick 上获取表格单元格的示例:http://codeprogress.com/java/showSamples.php?index=52&key=JTableValueofSelectedCell

    您可以使用它来获取选定的行和列。

    然后您需要创建一个自定义的 TableCellRenderer,可能作为一个内部类,以便它可以使用选定的行和列数据并将单元格的背景设置为您突出显示的颜色

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 2013-02-23
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多