JTable cell text color changing

不打扰是莪最后的温柔 提交于 2020-01-30 06:34:27

问题


I´m rather new to Java and programming itself, so excuse me for the question. What I´m trying to do is the following:

I´m making a bookkeeping program. On the column where the income/outcome is displayed, I want it so when the user enters a negative number (eg. -1.150€), the number turns red( or any color really, but red is what most bookkeeping programs use). only that specific cell on that column only. I have not started with a code yet so I cannot input one here. I also do not need it to be right-aligned since I have already done that.

PS. Sorry if this post/question already exists, I searched but I found nothing that could help me much.


回答1:


A small example with double values in a single column. This version uses JTable.setDefaultRenderer for Double.class.

You can also set colors

  • From an override of JTable.prepareRenderer
  • From a renderer set individually for columns by calling TableColumn.setCellRenderer; TableColumn instances can be retrieved from the TableColumnModel
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;

@SuppressWarnings("serial")
public class TableWithColors {
    protected static JTable createTable() {
        Object[][] rows = new Object[][] {{1.23d},{-20.5d},{5.87d},{2.23d},{-7.8d},{-8.99d},{9d},{16.25d},{4.23d},{-26.22d},{-14.14d}};
        Object[] cols = new Object[]{"Balance"};
        JTable t = new JTable(rows,cols) {
            @Override
            public Class<?> getColumnClass(int column) {
                if(convertColumnIndexToModel(column)==0) return Double.class;
                return super.getColumnClass(column);
            }
        };
        t.setDefaultRenderer(Double.class, new DefaultTableCellRenderer(){
            @Override
            public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
                Component c = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
                c.setForeground(((Double) value)>0 ? Color.BLUE : Color.RED);
                return c;
            }
        });
        return t;
    }

    private static JFrame createFrame() {
        JFrame f = new JFrame("Table with colors");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new BorderLayout());
        f.add(new JScrollPane(createTable()),BorderLayout.CENTER);
        f.setSize(new Dimension(60,255));
        return f;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createFrame().setVisible(true);
            }
        });
    }
}

Goes like:



来源:https://stackoverflow.com/questions/35431232/jtable-cell-text-color-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!