所以我基本上不希望在我的 JTable 中排序时显示第二列,反之亦然。一张图片胜过千言万语,所以这里有一张图片向您展示我的意思。http://i48.tinypic.com/2rzpfe9.jpg 所以当我在我的 JTable 中搜索“apple”这个词时,你可以看到,第二列仍然存在,它不应该存在,因为第一列有这个词“苹果”,而不是第二列。那么我怎样才能使另一列不显示,反之亦然?
编辑:我已经编辑了下面的代码以匹配 MadProgrammer 所说的,但它仍然无法正常工作。新图片http://i48.tinypic.com/2rzpfe9.jpg 这次文字没有了,但专栏还在。这次我做错了什么?
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class sorter extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public sorter() {
initComponents();
panel.setLayout(null);
search.setBounds(30,10,400,25);
search_button.setBounds(430,10,30,25);
}
public class FilterEntry extends RowFilter.Entry<TableModel, Integer> {
private final TableModel model;
private final Object value;
private final int rowIndex;
public FilterEntry(TableModel model, Object value, int rowIndex) {
this.model = model;
this.value = value;
this.rowIndex = rowIndex;
}
@Override
public TableModel getModel() {
return model;
}
@Override
public int getValueCount() {
return getModel().getColumnCount();
}
@Override
public Object getValue(int index) {
return value;
}
@Override
public Integer getIdentifier() {
return rowIndex;
}
}
private void initComponents() {
panel = new JPanel();
logo = new JLabel();
pane = new JScrollPane();
search = new JTextField();
search_button = new JButton();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(255, 255, 204));
setResizable(false);
panel.setBackground(new Color(51, 51, 51));
panel.setPreferredSize(new Dimension(290, 40));
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addGap(198, 198, 198)
.addComponent(logo)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
.addContainerGap(0, Short.MAX_VALUE)
.addComponent(logo)
.addContainerGap())
);
search.setText("");
search.setToolTipText("");
search.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
search.setPreferredSize(new java.awt.Dimension(30, 15));
search_button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/search.JPG"))); // NOI18N
search_button.setAlignmentY(0.0F);
search_button.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
search_button.setContentAreaFilled(false);
search_button.setIconTextGap(1);
search_button.setMargin(new java.awt.Insets(1, 4, 1, 4));
search_button.setMaximumSize(new java.awt.Dimension(5, 30));
search_button.setMinimumSize(new java.awt.Dimension(5, 30));
search_button.setPreferredSize(new java.awt.Dimension(30, 20));
javax.swing.GroupLayout panelLayout1 = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout1);
panelLayout1.setHorizontalGroup(
panelLayout1.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout1.createSequentialGroup()
.addGroup(panelLayout1.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout1.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(search_button, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panelLayout1.createSequentialGroup()
.addGap(174, 174, 174)
.addComponent(logo)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelLayout1.setVerticalGroup(
panelLayout1.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout1.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(logo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelLayout1.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(search, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(search_button, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE))
.addContainerGap())
);
ImageIcon Icon1 = getImage("lemon.jpg");
ImageIcon Icon2 = getImage("az.jpg");
ImageIcon Icon3 = getImage("aaa.jpg");
ImageIcon Icon4 = getImage("ba.jpg");
ImageIcon Icon5 = getImage("bas.jpg");
ImageIcon Icon6 = getImage("cookies.jpg");
String[] columnNames = {"A", "Section 1","B", "Section 2"};
Object[][] data =
{
{Icon1, "Lemon", Icon2, "Grapes"},
{Icon3, "Apple", Icon4, "Banana"},
{Icon5, "Orange", Icon6, "Cookies"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
/**
*
*/
private static final long serialVersionUID = 1L;
@SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
public boolean isCellEditable(int row, int col) {
return false;
}
};
class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
public MultiLineCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
RowFilter rowFilter = ((TableRowSorter) table.getRowSorter()).getRowFilter();
if (rowFilter != null) {
if (!rowFilter.include(new FilterEntry(table.getModel(), value, row))) {
value = null;
}
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setFont(table.getFont());
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, column)) {
setForeground(UIManager.getColor("Table.focusCellForeground"));
setBackground(UIManager.getColor("Table.focusCellBackground"));
}
} else {
setBorder(new EmptyBorder(1, 2, 1, 2));
}
setText((value == null) ? "" : value.toString());
return this;
}
}
// Sorter Code.
table = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
search_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = search.getText();
if (text.length() == 0) {
sorter.setRowFilter(null);
} else {
sorter.setRowFilter(RowFilter.regexFilter("(?i)"+ text));
}
}
});
// sorter code ends here.
table.setRowHeight(50);
pane.setViewportView(table);
table.setBackground(new Color(255, 255, 204));
table.setDefaultRenderer(String.class, new MultiLineCellRenderer());
table.getColumnModel().getColumn(1).setCellRenderer(new MultiLineCellRenderer());
table.getColumnModel().getColumn(3).setCellRenderer(new MultiLineCellRenderer());
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(1).setResizable(false);
table.getColumnModel().getColumn(2).setResizable(false);
table.getColumnModel().getColumn(3).setResizable(false);
table.setFocusable(false);
table.setRowSelectionAllowed(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 33;
col.setPreferredWidth(width);
int vColIndex1 = 1;
TableColumn col1 = table.getColumnModel().getColumn(vColIndex1);
int width1 = 216;
col1.setPreferredWidth(width1);
int vColIndex11 = 2;
TableColumn col11 = table.getColumnModel().getColumn(vColIndex11);
int width11 = 33;
col11.setPreferredWidth(width11);
int vColIndex111 = 3;
TableColumn col111 = table.getColumnModel().getColumn(vColIndex111);
int width111 = 216;
col111.setPreferredWidth(width111);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
.addComponent(pane)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(pane, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}
private ImageIcon getImage(String path)
{
java.net.URL url = getClass().getResource(path);
if (url != null)
return (new ImageIcon(url));
else
{
System.out.println(url);
return null;
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(sorter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(sorter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(sorter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(sorter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new sorter().setVisible(true);
}
});
}
private JLabel logo;
private JScrollPane pane;
private JPanel panel;
private JTextField search;
private JButton search_button;
}