Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing - Is it possible to set the font color of 'specific' text within a JTable cell?

I have a JTable where one column displays values in the following format:

423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]

I am wondering if it is possible to display the values within square brackets in RED?

I have been googling around for the last few days and have found several examples showing how to set the 'background' of a cell but not really how to change the font of a cell especially not a specific part of the text.

public class myTableCellRenderer
       extends DefaultTableCellRenderer {
  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);

    if (column == 3) {
       c.setForeground(Color.YELLOW);
       c.setBackground(Color.RED);
    }
    return c;
  }

Is it really possible to change part of the text to be a different color (i.e. the text that is within the square brackets).

Edit

The text i showed as an example is the actual text shown in the table cell (the comma separators are not representing columns). The text displayed in the cell is a comma separated string that i display on the table in column 3.

As an example the table could look like this

product_id |product_name| invoice_numbers
12         |    Books   | 423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
323        |    Videos  | 423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
4434       |    Music   | 423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
like image 864
ziggy Avatar asked Jan 27 '13 11:01

ziggy


People also ask

How to change color of column in JTable in Java?

We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent () to implement it. Java Program to Change Color of Column in JTable:

How to set the font and color of jtextarea in Java?

To set the font and color of JTextArea we can use the setFont () and setForeground () methods of the JTextArea. To create a font we must define the font name, the font style and its size. For the colors we can uses the constant color values defined by the Color class.

How to set the font on Java Swing components?

Last updated: June 6, 2016 Here are a few examples of how to set the Font on Java Swing components, including JTextArea, JLabel, and JList: You can use code like the following Scala code to easily test different fonts. Modify however you need to, but it displays a JFrame with a JTextArea, and you can change the font on it:

What is a JTable in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces.


1 Answers

You must use a Cell renderer combined with HTML.

Here is a small demo example:

import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TestTable2 {

    class MyCellRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (value instanceof String) {
                String string = (String) value;
                if (string.indexOf('[') > -1) {
                    setText(getHTML(string));
                }
            }
            return tableCellRendererComponent;
        }

        private String getHTML(String string) {
            StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            int index = 0;
            while (index < string.length()) {
                int next = string.indexOf('[', index);
                if (next > -1) {
                    int end = string.indexOf(']', next);
                    if (end > -1) {
                        next++;
                        sb.append(string.substring(index, next));
                        sb.append("<span style=\"color: red;\">");
                        sb.append(string.substring(next, end));
                        sb.append("</span>");
                        index = end;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
            sb.append(string.substring(index, string.length()));
            sb.append("</html>");
            return sb.toString();
        }
    }

    protected void initUI() {
        DefaultTableModel model = new DefaultTableModel();
        for (int i = 0; i < 2; i++) {
            model.addColumn("Col-" + (i + 1));
        }
        for (int i = 0; i < 200; i++) {
            Vector<Object> row = new Vector<Object>();
            for (int j = 0; j < 5; j++) {
                row.add("423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]");
            }
            model.addRow(row);
        }
        JTable table = new JTable(model);
        table.setDefaultRenderer(Object.class, new MyCellRenderer());
        JFrame frame = new JFrame(TestTable2.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollpane = new JScrollPane(table);
        frame.add(scrollpane, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTable2().initUI();
            }
        });
    }

}

And the result:

Result

like image 187
Guillaume Polet Avatar answered Oct 23 '22 10:10

Guillaume Polet