如何突出jtable单元格的文本?

时间:2014-08-27 19:06:26

标签: java swing jtable

我有一个包含一些数据的表。当我在textField中搜索文本时,表格的外观,更改和textFields消失。我不知道为什么,我不知道如果我做得对

enter image description here

enter image description here

这是我的整个代码..

package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.text.BadLocationException;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.RowFilter;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class test3 extends JFrame {

private JPanel contentPane;
private JTable table;

private TableModel tableModel;
private JTextField textField;
private String textForSearch;
private TableRowSorter<TableModel> sorter;
/**
 * Launch the application.
 */
public static void main(String[] args) {

/**
 * Create the frame.
 */
public test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 346);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(63, 52, 305, 191);
    contentPane.add(scrollPane);

    String columns [] = {
             "First Name", "Last Name", "Middle Name"   
        };
    String data[][] = new String [3][3];
    data [0][0] = "denise";
    data [0][1] = "alyson";
    data [0][2] = "berania";
    data [1][0] = "denden";
    data [1][1] = "pelesco";
    data [1][2] = "pogi";
    data [2][0] = "ryan";
    data [2][1] = "ewan";
    data [2][2] = "santos";

    tableModel = new DefaultTableModel(data, columns);

    table = new JTable(tableModel);
    scrollPane.setViewportView(table);

    sorter = new TableRowSorter<TableModel>(tableModel);
    table.setRowSorter(sorter);
    textField = new JTextField();
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            textForSearch = textField.getText();
            if(textForSearch.length()==0){
                sorter.setRowFilter(null);
            }else{
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + textForSearch));
            }

            for(int i =0;i<table.getColumnCount();i++){
                table.getColumnModel().getColumn(i).setCellRenderer(getRenderer());
            }
        }
    });
    textField.setBounds(262, 21, 86, 20);
    contentPane.add(textField);
    textField.setColumns(10);
}

   private TableCellRenderer getRenderer() {
        return new TableCellRenderer() {


            @Override
            public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
                if(arg1 != null){
                    textField.setText(arg1.toString());
                    String string = arg1.toString();
                    if(string.contains(textForSearch)){
                        int indexOf = string.indexOf(textForSearch);
                        try {
                            textField.getHighlighter().addHighlight(indexOf,indexOf+textForSearch.length(),new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.RED));
                        } catch (BadLocationException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    textField.setText("");
                    textField.getHighlighter().removeAllHighlights();
                }
                return textField;
            }
        };
    }
}

2 个答案:

答案 0 :(得分:2)

  1. 您正在使用搜索文本字段作为表格单元格渲染器。这使得所有单元格看起来像文本字段,并且搜索文本字段从其原始位置消失。
  2. 您正在ActionListener中设置单元格渲染器ActionListener。这使得#1在你尝试搜索之后就会发生。

答案 1 :(得分:2)

我强烈建议采用略有不同的方法:

而不是getRender()返回一个匿名的TableCellRender(),扩展你的代码以扩展一个JLable以便返回,这样你就可以更自由地自由更改setBackground(),setForeground()等属性。

在这里,您可以找到更多信息:http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableCellRenderer.html

public class DefaultTableCellRenderer extends JLabel implements TableCellRenderer {

}

以下是JList的完整示例,它通过更改为适当的接口将相同的内容应用于JTable :(专注于最后两个if - else)

public class ThumbnailCellRenderer extends JLabel implements ListCellRenderer {

    private static final Color HIGHLIGHT_COLOR = new Color(0,0,128);

    public ThumbnailCellRenderer() {
        this.setOpaque(true);
        this.setIconTextGap(12);
    }
    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        // COMPLETE BODY
        Photo photo = (Photo)value;
        ImageIcon thumbnail = photo.getThumbnail();
        if(thumbnail != null) {
            this.setToolTipText("Double Click for Slideshow - "+photo.getName());
            this.setIcon(thumbnail);
            this.setText(photo.getCaption()+" - "+Utilities.getReadableDateAndTime(photo.getTime()));
        } else {
            this.setIcon(Icons.IMAGEREMOVED_ICON.get());
            this.setText(photo.getCaption()+" - "+Utilities.getReadableDateAndTime(photo.getTime())+" - Physical Image Removed");
        }
        if(isSelected) {
            setBackground(HIGHLIGHT_COLOR);
            setForeground(Color.WHITE);
        } else {
            setBackground(Color.WHITE);
            setForeground(Color.black);
        }
        return this;
    }

}

最后,您只需添加渲染器,就像在MainFrame代码中一样。

我希望有所帮助。