简体   繁体   English

在jtable中突出显示单元格

[英]highlight the cell in jtable

I have this code fom stackoverflow how to highlight multiple cells in jtable : 我有这个代码fom stackoverflow 如何在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;
    }
}

But when i use it for highlighting a cell , it gives wrong action like the whole data gets lost . 但是当我用它来突出显示一个单元格时,它会给出错误的操作,就像整个数据丢失一样。 Iam new to java swing. 我刚接触java swing。 Please help to make a cell gets highlighted on a button press action event. 请帮助在按钮按下操作事件中突出显示单元格。
UPDATE: adding my sample code: 更新:添加我的示例代码:

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

What i want is on clicking the button i want to highlight just the cell number-1 (Row1-Column1). 我想要的是单击按钮我想要突出显示单元格编号-1(Row1-Column1)。

I use this class to style JTables 我使用这个类来设置JTable的样式

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

create an instance of this class and apply it to the cells that you need to style. 创建此类的实例并将其应用于您需要设置样式的单元格。 You can use the isSelected parameter to edit the cell highlight color. 您可以使用isSelected参数编辑单元格高亮颜色。

EDIT 编辑

Thanks for your updated example, here is an example of a toggle button to change the cell renderer 感谢您的更新示例,以下是更改单元格渲染器的切换按钮的示例

First create a color style for the cell using a default table cell renderer 首先使用默认表格单元格渲染器为单元格创建颜色样式

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

Create your JFrame and add the JTable and button 创建您的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();
}

Hope this helps 希望这可以帮助

EDIT I added a repaint to clean up the last example. 编辑我添加了一个重绘清理最后一个例子。 If you only want to target a specific cell change the table cell renderer to only render the cell you need like this 如果您只想定位特定单元格,请将表格单元格渲染器更改为仅渲染所需的单元格

    @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;
}

There are multiple ways this might be achieved, in your, very, particular case, you want to highlight a particular row and column, you could use... 有多种方法可以实现,在您的,非常特殊的情况下,您想要突出显示特定的行和列,您可以使用...

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

Now, if you wanted to highlight the entire row, you would replace 现在,如果要突出显示整行,则需要替换

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

With

if (row == 0) {

One of the more difficult concepts to grasp with renderers, is the need to entirely reset the state of the component on each iteration. 使用渲染器掌握的一个更难的概念是需要在每次迭代时完全重置组件的状态。 Basically what this means, is not assuming that a property has been set correctly for the current iteration, and making sure to default values you have not used... 基本上这意味着,不是假设已经为当前迭代正确设置了属性,并确保您没有使用的默认值...

Take a look at Using Custom Renderers for more details... 有关更多详细信息,请参阅使用自定义渲染器 ...

You can try with this: 你可以尝试这个:

First, in the table code: 首先,在表格代码中:

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

Then: 然后:

public class HighlightCellRenderer extends DefaultTableCellRenderer { 公共类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;
}

} }

You could try a different approach instead of using a cell renderer you can manually select a JTable cell like this 您可以尝试不同的方法,而不是使用单元格渲染器,您可以手动选择这样的JTable单元格

    table.setCellSelectionEnabled(true); //Enable single cell selection

    table.addRowSelectionInterval(1, 1); // select rows
    table.setColumnSelectionInterval(1, 1); // select columns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM