有没有一种方法可以根据在文本字段中输入的数据突出显示或着色各种 table 行?
Is there a way that i can highlight or colour various table rows based on data entered in textfield?
我想做的是突出显示我从一箱物品中扫描的序列号。
所以当我扫描 S/N 时。我的想法是 table,其中包含框中的项目,改变它们的颜色。我的英语很烂,所以我认为图片可以更好地解释我的想法。
所以我的代码执行以下操作:
首先,我使用框 1 ("Gaveta") 中的信息加载 table:
http://prntscr.com/o4ykdy
然后当我过滤框中项目的 S/N 时:
http://prntscr.com/o4yly4
我遇到了我的问题,搜索绘制了正确的 S/N 但它损坏了我的 table 模型。
我的代码:
资料搜索:
public void buscarNumeroSerie (String 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);
}
}
Table 渲染器:
public class ClaseColor 扩展了 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;
}
return这个;
}
}
我想要做的是绘制每个 S/N 与执行搜索的文本字段 "Serial Number" 匹配的每个 S/N。
像这样:
http://prntscr.com/o4ynui
所以我搜索任何新的S/N,在我继续扫描的同时得到一个标记S/N,然后没有标记的S/N从[=67=中被淘汰].
因为你没有给我们 minimal-reproducible example i have created my own example in order to show you how this could be done. Using underline to a JTable
would be tricky since (I think) JTextPane is required. However, it is easier to achieve something similar by highlighting the search text in the cell of the table. Of course in order to do that we need to create our own custom TableCellRenderer。
代码:
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;}
然后我将它应用到 table
nsrs.close();
stmnt.close();
tablaDiscosGaveta.setModel(ModeloTablaLista);
ClaseColor comp = new ClaseColor(0);
tablaDiscosGaveta.getColumnModel().getColumn(0).setCellRenderer(comp);
}
有了这个我可以过滤并在匹配过滤器时将背景设置为绿色。
但过滤时只显示 "zeroes",所以我需要解决这个问题。
Filter is ok
It shows the background i wanted but not the serial i need
最后一次更新,我解决了我在以下行更改值的问题:
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, col, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
为了
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, value, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
Finally !
我想做的是突出显示我从一箱物品中扫描的序列号。
所以当我扫描 S/N 时。我的想法是 table,其中包含框中的项目,改变它们的颜色。我的英语很烂,所以我认为图片可以更好地解释我的想法。
所以我的代码执行以下操作:
首先,我使用框 1 ("Gaveta") 中的信息加载 table:
http://prntscr.com/o4ykdy
然后当我过滤框中项目的 S/N 时:
http://prntscr.com/o4yly4
我遇到了我的问题,搜索绘制了正确的 S/N 但它损坏了我的 table 模型。
我的代码:
资料搜索:
public void buscarNumeroSerie (String 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);
}
}
Table 渲染器:
public class ClaseColor 扩展了 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;
}
return这个;
} }
我想要做的是绘制每个 S/N 与执行搜索的文本字段 "Serial Number" 匹配的每个 S/N。
像这样:
http://prntscr.com/o4ynui
所以我搜索任何新的S/N,在我继续扫描的同时得到一个标记S/N,然后没有标记的S/N从[=67=中被淘汰].
因为你没有给我们 minimal-reproducible example i have created my own example in order to show you how this could be done. Using underline to a JTable
would be tricky since (I think) JTextPane is required. However, it is easier to achieve something similar by highlighting the search text in the cell of the table. Of course in order to do that we need to create our own custom TableCellRenderer。
代码:
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;}
然后我将它应用到 table
nsrs.close();
stmnt.close();
tablaDiscosGaveta.setModel(ModeloTablaLista);
ClaseColor comp = new ClaseColor(0);
tablaDiscosGaveta.getColumnModel().getColumn(0).setCellRenderer(comp);
}
有了这个我可以过滤并在匹配过滤器时将背景设置为绿色。
但过滤时只显示 "zeroes",所以我需要解决这个问题。
Filter is ok
It shows the background i wanted but not the serial i need
最后一次更新,我解决了我在以下行更改值的问题:
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, col, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
为了
Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, value, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);
Finally !