【问题标题】:Edit on JTable cell has no effect编辑 JTable 单元格无效
【发布时间】:2019-04-30 10:20:57
【问题描述】:

我想突出显示JTable 中的某些单元格并进行了必要的更改,但程序看不到它们。

当我调试代码时,我注意到程序渲染了表格,但它没有进入 if 语句。

如果有人能告诉我出了什么问题,那就太好了。

    public class Frame extends JFrame {

        private JPanel contentPane;
        private static JTable table;
        final DefaultTableModel model;

    String data[][] = { {"E","S","M","I","S","T","P","G","L","E","I","C","H","Y","M"},
        {"G","H","J","K","F","K","N","F","Z","I","G","W","X","Z","T"} };

        String[] columns =  "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    public static void main(String[] args) {
        try {
            Frame frame = new Frame();
            centerWindow(frame);
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        } }
//build the frame
        public Frame() {
        model = new DefaultTableModel();
        setBackground(Color.LIGHT_GRAY);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 570, 570);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

//build the table               
        table = new JTable();
        JTable table = new JTable(data, columns);
        table.setBackground(Color.LIGHT_GRAY);
        table.setFont(new Font("Verdana", Font.PLAIN, 14));
        table.setSize(800, 400);
        table.setRowHeight(30);
        table.setForeground(Color.WHITE);
        contentPane.add(table, BorderLayout.CENTER);

        //in this part, the program should change the color of certain cells ... but it does not :-(
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
//highlight the cells with the value "s"
                    if (value instanceof String) {
                        if (value.equals("s")){
                            System.out.println(row + " " + column);
                            cell.setBackground(Color.BLUE);} else {
                            cell.setBackground(Color.WHITE);}  }  
            return cell;
            }  
        });  
    }  

【问题讨论】:

    标签: java swing jtable cell background-color


    【解决方案1】:

    换行:

    if (value.equals("s")){
    

    if (value.equals("S")){
    

    Equals 区分大小写。

    【讨论】:

    • 感谢 Andrew Thompson 的回复。但它也不起作用。正如我所说,程序一直运行到 table.setDefaultRenderer 然后跳过 if 语句
    猜你喜欢
    • 1970-01-01
    • 2011-09-27
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2010-12-07
    • 2014-01-01
    相关资源
    最近更新 更多