简体   繁体   English

Swing - 是否可以在JTable单元格中设置“特定”文本的字体颜色?

[英]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: 我有一个JTable,其中一列显示以下格式的值:

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? 我想知道是否可以在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 (ie 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. 单元格中显示的文本是逗号分隔的字符串,我在第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)]

You must use a Cell renderer combined with HTML. 您必须使用与HTML结合的Cell渲染器。

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: 结果如下:

结果

Is it really possible to change part of the text to be a different color

yes is possible, for 是的可能,因为

  • simple highlighter is possible with JTextField/JTextArea as Renderers component 使用JTextField/JTextArea作为Renderers component可以使用简单的荧光笔

  • multiple of the Highlighter have to look for JTextPane as Renderers component Highlighter多个必须查找JTextPane作为Renderers component

  • (easier of ways) you can to formatting cell by using Html (todays Java up to Html3.2 ) (更简单的方法)你可以使用Html格式化单元格(今天的Java up to Html3.2

This is what you are looking for Cell render 这就是您正在寻找Cell渲染

How to proceed: 如何进行:

  1. get the default cell render component using getTableCellRendererComponent() function with the appropriate parameters. 使用带有适当参数的getTableCellRendererComponent()函数获取默认的单元格渲染组件。

  2. parse the text of the cell and apply your formatting using setForeground() function. 解析单元格的文本并使用setForeground()函数应用您的格式。

Yes It is possible. 对的,这是可能的。
EDIT 编辑
First you need to create a subclass of DefaultTableCellRenderer where you override getTableCellRendererComponent method to render the desired column according to your need. 首先,您需要创建DefaultTableCellRenderer的子类,您可以在其中覆盖getTableCellRendererComponent方法,以根据需要呈现所需的列。 And then change the renderer for that column by the subclass of DefaultTableCellRenderer . 然后通过DefaultTableCellRenderer的子类更改该列的渲染器。
Here is the example to achieve this task: 以下是实现此任务的示例:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
public class TableExample extends JFrame
{
    JTable myTable ;
    Object[][] data= {
                    {"34","[56],987,[(56)]"},
                    {"5098","345,([{78}])"},
                    {"567","4312"}
                };
    Object[] col = {"First","Second"};
    public TableExample()
    {
        super("CellRendererExample");
    }
    public void prepareAndShowGUI()
    {
        myTable = new JTable(data,col);
        myTable.getColumnModel().getColumn(1).setCellRenderer(new MyTableCellRenderer());
        JScrollPane jsp = new JScrollPane(myTable);
        getContentPane().add(jsp);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
    public class MyTableCellRenderer extends DefaultTableCellRenderer 
    {
        public Component getTableCellRendererComponent(JTable table,Object oValue, boolean isSelected, boolean hasFocus, int row, int column) 
        {
            Component c = super.getTableCellRendererComponent(table, oValue,isSelected, hasFocus,row, column);
            String value = (String)oValue;
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append("<HTML><BODY>");
            StringTokenizer tokenizer = new StringTokenizer(value,",");
            while (tokenizer.hasMoreTokens())
            {
                String token = tokenizer.nextToken();
                int index = token.indexOf("[");
                if (index != -1)
                {
                    sBuilder.append(token.substring(0,index));
                    int lastIndex = token.lastIndexOf(']');
                    String subValue = token.substring(index + 1,lastIndex);
                    sBuilder.append("[<FONT color = red>"+subValue+"</FONT>]");
                    if (lastIndex < token.length() -1)
                    {
                        sBuilder.append(token.substring(lastIndex+1,token.length()));
                    }
                    sBuilder.append(",");
                }
                else
                {
                    sBuilder.append(token+",");
                }
            }
            if (sBuilder.lastIndexOf(",") == sBuilder.length() - 1)
            {
                sBuilder.deleteCharAt(sBuilder.length() - 1 );
            }
            sBuilder.append("</BODY></HTML>");
            value = sBuilder.toString(); ;
            JLabel label =(JLabel)c;
            label.setText(value);
            return label;
        }
    }
    public static void main(String st[])
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                TableExample tae = new TableExample();
                tae.prepareAndShowGUI();
            }
        });
    }

}

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

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