Java 是否有一种方法可以根据在textfield中输入的数据突出显示或着色各种表格行?
我想做的是突出显示我从一盒物品中扫描的序列号 因此,当我扫描序列号时,我的想法是,包含框中项目的表格会改变它们的颜色。我的英语糟透了,所以我认为图像可以更好地解释我的想法 因此,我的代码执行以下操作: 首先,我用方框1(“Gaveta”)中的信息加载表格: 然后,当我过滤框中项目的序列号时: 我面对我的问题,搜索绘制了正确的序列号,但它损坏了我的tablemodel 我的代码: 数据搜索: 公共无效buscarNumeroSerie(字符串nserie) { 试一试{Java 是否有一种方法可以根据在textfield中输入的数据突出显示或着色各种表格行?,java,sql,swing,jtable,tablecellrenderer,Java,Sql,Swing,Jtable,Tablecellrenderer,我想做的是突出显示我从一盒物品中扫描的序列号 因此,当我扫描序列号时,我的想法是,包含框中项目的表格会改变它们的颜色。我的英语糟透了,所以我认为图像可以更好地解释我的想法 因此,我的代码执行以下操作: 首先,我用方框1(“Gaveta”)中的信息加载表格: 然后,当我过滤框中项目的序列号时: 我面对我的问题,搜索绘制了正确的序列号,但它损坏了我的tablemodel 我的代码: 数据搜索: 公共无效buscarNumeroSerie(字符串nserie) { 试一试{
String [] campos={"NUMERO_SERIE","MARCA","GAVETA"};
String filtroNS = nserie;
String NSSQL = "SELECT NUMERO_SERIE,MARCA,GAVETA FROM"
+ "(SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_wd "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_toshiba "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_seagate "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_samsung "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_hitachi )"
+ "AS TROUBLE WHERE NUMERO_SERIE LIKE '%"+filtroNS+"%'";
System.out.println(NSSQL);
nsconn = metodosPool.dataSource.getConnection();
//ModeloTablaLista = new DefaultTableModel(null, campos);
stmnt = nsconn.prepareStatement(NSSQL);
ResultSet nsrs = stmnt.executeQuery(NSSQL);
String [] nsfila = null;
//if(nsrs.next()== true){
// String [] nsfila = new String[3];
while (nsrs.next())
{
nsfila = new String[3];
nsfila[0]=nsrs.getString("Numero_Serie");
nsfila[1]=nsrs.getString("Marca");
nsfila[2]=nsrs.getString("Gaveta");
// ModeloTablaLista.addRow(nsfila);
}
if (nsfila == null)
{
Object[] opcionesPurga = {"Agregar Disco Hitachi",
"Agregar Disco Toshiba",
"Agregar Disco Seagate",
"Agregar Disco Samsung",
"Agregar Disco WD",
"Omitir"};
int sinDiscoEnTabla = JOptionPane.showOptionDialog
(rootPane,
"Disco no encontrado, ¿que desea hacer?:",
"Disco no encontrado",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
opcionesPurga,
opcionesPurga[1]);
System.out.println(sinDiscoEnTabla);
switch (sinDiscoEnTabla){
case 0:
sinDiscoAddHi.setVisible(true);
break;
case 1:
sinDiscoAddTo.setVisible(true);
break;
case 2:
sinDiscoAddSe.setVisible(true);
break;
case 3:
sinDiscoAddHi.setVisible(true);
break;
case 4:
sinDiscoAddWD.setVisible(true);
break;
case 5:
JOptionPane.showMessageDialog(null,"Por favor ingrese un nuevo disco:");
tfNumeroSeriePurga.setText("");
break;
}
}
nsrs.close();
stmnt.close();
// tablaDiscosGaveta.setModel(ModeloTablaLista);
ClaseColor colorear = new ClaseColor(0);
tablaDiscosGaveta.getColumnModel().getColumn(0).setCellRenderer(colorear);
}
//else
// {
// System.err.println("No existen datos asociados");
// JOptionPane.showMessageDialog(rootPane, "Disco no encontrado, quiere:");
// }
catch (SQLException nseerr)
{
System.err.println(""+nseerr.getSQLState());
JOptionPane.showMessageDialog(null, "Error al buscar \n"
+nseerr, "Error en la operacion ", JOptionPane.ERROR_MESSAGE);
}
}
表渲染器:
公共类ClasecColor扩展了DefaultTableCellRenderer{
private final int patron;
public ClaseColor(int patron) {
this.patron = patron;
}
@Override
public Component getTableCellRendererComponent
(JTable tablaDiscosGaveta,
Object value,
boolean Selected,
boolean hasFocus,
int row,
int col)
{
if (!tfNumeroSeriePurga.getText().equals(tablaDiscosGaveta.getValueAt(row, patron).toString()))
{
System.out.println("FramePurgar.PurgarDiscos1.ClaseColor.methodName()"+"no pille nada !");
}
else
{
setForeground(Color.RED);
//setFont(font);
//
super.getTableCellRendererComponent(tablaDiscosGaveta, value, Selected, hasFocus, row, col);
return this;
}
归还这个
}
}
我要做的是绘制每个序列号,它与执行搜索的文本字段“序列号”匹配
大概是这样的:
因此,我搜索任何新的序列号,在我不断扫描序列号的同时得到一个标记,然后将未标记的序列号从表中删除。由于您没有给我们一个新的序列号,我创建了我自己的示例,以向您展示如何做到这一点。在
JTable
中使用下划线将非常棘手,因为(我认为)JTextPane是必需的。但是,通过突出显示表单元格中的搜索文本,更容易实现类似的功能。当然,为了实现这一点,我们需要创建自己的自定义
代码:
public class TableExample extends JFrame {
private static final Color HIGHLIGHT_COLOR = Color.GREEN;
private JTextField textField;
TableExample() {
String data[][] = { { "101", "Mike", "17" }, { "102", "Thomas", "21" }, { "103", "Brian", "42" }, { "104", "George", "24" } };
String column[] = { "ID", "NAME", "AGE" };
JPanel inputpanel = new JPanel(new BorderLayout(10, 10));
JTable table = new JTable();
JScrollPane sp = new JScrollPane(table); // You were not adding the sp into your panel, take care that next time.
DefaultTableModel dtm = new DefaultTableModel(data, column); // Create the model with our data.
table.setModel(dtm);
table.setDefaultRenderer(Object.class, new CellHighlightRenderer());
textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
table.repaint();
}
@Override
public void insertUpdate(DocumentEvent e) {
table.repaint();
}
@Override
public void changedUpdate(DocumentEvent e) {
table.repaint();
}
});
inputpanel.add(textField, BorderLayout.PAGE_START);
inputpanel.add(sp);
add(inputpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLocationRelativeTo(null);
pack();
}
class CellHighlightRenderer extends JTextField implements TableCellRenderer {
public DefaultHighlighter high = new DefaultHighlighter();
public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(HIGHLIGHT_COLOR);
public CellHighlightRenderer() {
setBorder(BorderFactory.createEmptyBorder());
setHighlighter(high);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
setFont(table.getFont());
setValue(value);
int pos = 0;
String word = textField.getText();
word = word.toLowerCase();// In order to improve search?
String stringValue = value.toString();
stringValue = stringValue.toLowerCase(); // In order to improve search?
if (!word.isEmpty()) {
if ((pos = stringValue.indexOf(word, pos)) >= 0) {
try {
high.addHighlight(pos, pos + word.length(), highlight_painter);
pos += word.length();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return this;
}
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TableExample te = new TableExample();
te.setVisible(true);
});
}
}
预览:
public class TableExample extends JFrame {
private static final Color HIGHLIGHT_COLOR = Color.GREEN;
private JTextField textField;
TableExample() {
String data[][] = { { "101", "Mike", "17" }, { "102", "Thomas", "21" }, { "103", "Brian", "42" }, { "104", "George", "24" } };
String column[] = { "ID", "NAME", "AGE" };
JPanel inputpanel = new JPanel(new BorderLayout(10, 10));
JTable table = new JTable();
JScrollPane sp = new JScrollPane(table); // You were not adding the sp into your panel, take care that next time.
DefaultTableModel dtm = new DefaultTableModel(data, column); // Create the model with our data.
table.setModel(dtm);
table.setDefaultRenderer(Object.class, new CellHighlightRenderer());
textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
table.repaint();
}
@Override
public void insertUpdate(DocumentEvent e) {
table.repaint();
}
@Override
public void changedUpdate(DocumentEvent e) {
table.repaint();
}
});
inputpanel.add(textField, BorderLayout.PAGE_START);
inputpanel.add(sp);
add(inputpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLocationRelativeTo(null);
pack();
}
class CellHighlightRenderer extends JTextField implements TableCellRenderer {
public DefaultHighlighter high = new DefaultHighlighter();
public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(HIGHLIGHT_COLOR);
public CellHighlightRenderer() {
setBorder(BorderFactory.createEmptyBorder());
setHighlighter(high);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
setFont(table.getFont());
setValue(value);
int pos = 0;
String word = textField.getText();
word = word.toLowerCase();// In order to improve search?
String stringValue = value.toString();
stringValue = stringValue.toLowerCase(); // In order to improve search?
if (!word.isEmpty()) {
if ((pos = stringValue.indexOf(word, pos)) >= 0) {
try {
high.addHighlight(pos, pos + word.length(), highlight_painter);
pos += word.length();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return this;
}
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TableExample te = new TableExample();
te.setVisible(true);
});
}
}
实际上我可以做我想做的事情,现在我必须细化一些细节 首先是渲染器代码:
public class ClaseColor extends DefaultTableCellRenderer {
private final int patronSerie;
public ClaseColor(int patron) {
this.patronSerie = patron;
}
@Override
public Component getTableCellRendererComponent
(JTable tablaDiscosGaveta,
Object value,
boolean Selected,
boolean hasFocus,
int row,
int col)
{
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, col, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
for (int i = 0; i < tablaDiscosGaveta.getRowCount(); i++)
{
if(tablaDiscosGaveta.getValueAt(i, 0).toString().equals(tfNumeroSeriePurga.getText()))
{
System.out.println("El número si existe");
}
else
{
System.out.println("El número no existe");
}
if (!tablaDiscosGaveta.isRowSelected(row))
{
comp.setBackground(getBackground());
int modelRow = tablaDiscosGaveta.convertRowIndexToModel(row);
if(tablaDiscosGaveta.getValueAt(i, 0).toString().equals(tfNumeroSeriePurga.getText()))
{
comp.setBackground(Color.GREEN);
}
}}return this;}
有了这个,我可以过滤并在匹配过滤器时将背景设置为绿色
但它在过滤时只显示“零”,所以我需要修正它
最终更新此时,我修复了更改以下行的值时出现的问题:
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, col, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
为了
也许可以使用筛选器仅显示包含您正在搜索的测试的行。这样,您就不需要滚动整个表来查找突出显示的文本。请阅读Swing教程中的部分,例如,在文本字段中键入时进行筛选。这对我帮助很大,执行过程类似,因此我使用d那太感谢了!@AlexisAhumada我很高兴它帮助了你。但我认为你认为错误的答案是正确的。:P
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, value, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);