代码之家  ›  专栏  ›  技术社区  ›  sneha nambiar

突出显示jtable中的单元格

  •  2
  • sneha nambiar  · 技术社区  · 10 年前

    我有stackoverflow的代码 how to highlight multiple cells in jtable :

    private static class CellHighlighterRenderer extends JLabel implements TableCellRenderer {
    
        public CellHighlighterRenderer() {
            setOpaque(true); // Or color won't be displayed!
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            String val = (String)value;
            Color c;
            if (val.matches(".*MIN.*")) // Add a method to configure the regexpr
                c = Color.YELLOW; // Add a method to configure color
            else
                c = UIManager.getColor("Table.background");
            setBackground(c);
            setText(val);
            return this;
        }
    }
    

    但当我使用它来突出显示一个单元格时,它会给出错误的操作,就像整个数据丢失一样。我对java swing很陌生。请帮助在按钮按下操作事件中突出显示单元格。
    更新:添加示例代码:

    package myPackage;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    import javax.swing.table.TableCellRenderer;
    
    public class JTableCreatingDemo {
        public static void main(String args[]) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        Object rowData[][] = { { "Row1-Column1"},
            { "Row2-Column1" } ,{ "Row3-Column1"},{ "Row4-Column1"},};
        Object columnNames[] = { "Column One" };
        final JTable table = new JTable(rowData, columnNames);
        JButton button = new JButton("Highlight cell-1");
        //Add action listener to button
        button.addActionListener(new ActionListener() {
    
                @Override
            public void actionPerformed(ActionEvent arg0) {
             table.setDefaultRenderer(Object.class, new CellHighlighterRenderer()); 
            }
        });    
        JPanel pnl = new JPanel();
        pnl.add(button);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(pnl,BorderLayout.SOUTH);
        frame.setSize(300, 150);
        frame.setVisible(true);
    
      }
    }
    
    class CellHighlighterRenderer extends JLabel implements TableCellRenderer {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        public CellHighlighterRenderer() {
            setOpaque(true); // Or color won't be displayed!
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            String val = (String)value;
            Color c;
            if (isSelected) // Add a method to configure the regexpr
                c = Color.YELLOW; // Add a method to configure color
            else
                c = UIManager.getColor("Table.background");
            setBackground(c);
            setText(val);
            return this;
        }
    }
    

    我想要的是单击按钮,只突出显示单元格编号-1(第1行第1列)。

    4 回复  |  直到 7 年前
        1
  •  3
  •   Zyion    10 年前

    我使用这个类来设置JTables的样式

    public class CellRenderer extends DefaultTableCellRenderer {
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
    
        if (isSelected)
            cell.setBackground(Color.YELLOW);
        else if (column == 0)
            cell.setBackground(new Color(0xDDDDD));
        else 
            cell.setBackground(new Color(0xFFFFFF));
    
        return cell;
    }
    

    创建此类的实例,并将其应用于需要设置样式的单元格。 可以使用isSelected参数编辑单元格高亮显示颜色。

    编辑

    感谢您的更新示例,这里是一个切换按钮的示例,用于更改单元格渲染器

    首先使用默认表格单元格渲染器为单元格创建颜色样式

    public class CellHighlighterRenderer extends DefaultTableCellRenderer {
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object obj,
            boolean isSelected, boolean hasFocus, int row, int column) {
    
        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
    
        cell.setBackground(Color.YELLOW);
    
        return cell;
    }
    

    创建JFrame并添加JTable和按钮

    public class Main extends JFrame {
    
    public Main() {
        super("Table Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300, 300));
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
    
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnCount(5);
        model.setRowCount(5);
    
        JTable table = new JTable();
        table.setModel(model);
    
        //Get an instance of the column and the style to apply and hold a default style instance
        final TableColumn column = table.getColumnModel().getColumn(1);
        final CellHighlighterRenderer cellRenderer = new CellHighlighterRenderer();
        final TableCellRenderer defaultRenderer = column.getCellRenderer();
    
        //Now in your button listener you can toggle between the styles 
        JButton button = new JButton("Click!");
        button.addActionListener(new ActionListener() {
            private boolean clicked = false;
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
                if (clicked) {
                    column.setCellRenderer(cellRenderer);
                    clicked = false;
                } else {
                    column.setCellRenderer(defaultRenderer);
                    clicked = true;
                }
                repaint(); //edit
            }
        });
    
        getContentPane().add(table, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.NORTH);
        pack();
        setVisible(true);
    }
    
    public static void main(String[] args) {
         new Main();
    }
    

    希望这有帮助

    编辑 我添加了一个重新绘制来清理最后一个示例。如果只想以特定单元格为目标,请将表单元格渲染器更改为只渲染所需的单元格,如下所示

        @Override
    public Component getTableCellRendererComponent(JTable table, Object obj,
            boolean isSelected, boolean hasFocus, int row, int column) {
    
        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
    
        //add condition for desired cell
        if (row == 1 && column == 1)
            cell.setBackground(Color.YELLOW);
    
        return cell;
    }
    
        2
  •  2
  •   MadProgrammer    10 年前

    有多种方法可以实现这一点,在您非常特殊的情况下,您希望突出显示特定的行和列,可以使用。。。

    class CellHighlighterRenderer extends DefaultTableCellRenderer {
    
        private static final long serialVersionUID = 1L;
    
        public CellHighlighterRenderer() {
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (row == 0 && column == 0) {
                setBackground(Color.YELLOW);
                setOpaque(true);
            } else {
                setBackground(table.getBackground());
                setOpaque(isSelected);
            }
            return this;
        }
    }
    

    现在,如果要突出显示整个行,可以替换

    if (row == 0 && column == 0) {
    

    具有

    if (row == 0) {
    

    渲染器更难掌握的概念之一是需要在每次迭代时完全重置组件的状态。基本上,这意味着不假设为当前迭代正确设置了属性,并确保默认值未使用。。。

    看看 Using Custom Renderers 有关详细信息。。。

        3
  •  1
  •   Juan Rodriguez    8 年前

    你可以试试这个:

    首先,在表代码中:

    HighlightCellRenderer renderer = new HighlightCellRenderer();
    table.setDefaultRenderer(String.class, renderer);
    table.setDefaultRenderer(Number.class, renderer);
    table.setDefaultRenderer(Boolean.class, renderer);
    table.setDefaultRenderer(Character.class, renderer);
    

    然后:

    公共类HighlightCellRenderer扩展了DefaultTableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus,
            int row, int column) {
        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
    
        if (row == table.getSelectedRow()) {
            if (column == table.getSelectedColumn()) {
                // special color
                cell.setBackground(Color.GREEN);
            } else {
                // The selected row color in "com.jtattoo.plaf.aero.AeroLookAndFeel"                
                cell.setBackground(new Color(176, 196, 222)); 
            }
        } else {
            // Other rows
            cell.setBackground(Color.WHITE);
        }
    
        return cell;
    }
    

    }

        4
  •  0
  •   Zyion    10 年前

    您可以尝试一种不同的方法,而不是使用单元格渲染器,您可以像这样手动选择JTable单元格

        table.setCellSelectionEnabled(true); //Enable single cell selection
    
        table.addRowSelectionInterval(1, 1); // select rows
        table.setColumnSelectionInterval(1, 1); // select columns