5

我有一个 JTable,其中一列以以下格式显示值:

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

我想知道是否可以在 RED 中显示方括号内的值?

在过去的几天里,我一直在谷歌上搜索,发现了几个例子,展示了如何设置单元格的“背景”,但没有真正改变单元格的字体,尤其是文本的特定部分。

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

是否真的可以将部分文本更改为不同的颜色(即方括号内的文本)。

编辑

我作为示例显示的文本是表格单元格中显示的实际文本(逗号分隔符不代表列)。单元格中显示的文本是一个逗号分隔的字符串,我显示在第 3 列的表格中。

例如,表格可能如下所示

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)]
4

4 回答 4

5

您必须使用结合 HTML 的单元格渲染器。

这是一个小演示示例:

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

}

结果:

结果

于 2013-01-27T12:04:44.680 回答
2

这就是您要寻找的单元格渲染

如何进行:

  1. getTableCellRendererComponent()使用具有适当参数的函数获取默认单元格渲染组件 。

  2. 解析单元格的文本并使用setForeground()函数应用您的格式。

于 2013-01-27T11:57:19.700 回答
2
Is it really possible to change part of the text to be a different color

是的,因为

  • 简单的荧光笔可以使用JTextField/JTextArea asRenderers component

  • 多个必须Highlighter寻找JTextPaneRenderers component

  • (更简单的方法)您可以使用Html(todays Java up to Html3.2)来格式化单元格

于 2013-01-27T12:00:33.987 回答
0

对的,这是可能的。
编辑
首先,您需要创建一个DefaultTableCellRenderer覆盖getTableCellRendererComponent方法的子类,以根据您的需要呈现所需的列。然后通过DefaultTableCellRenderer.
这是实现此任务的示例:

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

}
于 2013-01-27T11:57:36.053 回答