有没有一种方法可以根据在文本字段中输入的数据来突出显示各表行或为其上色?

时间:2019-06-21 17:14:33

标签: java sql swing jtable tablecellrenderer

我要执行的操作将突出显示我从一盒物品中扫描的序列号。

所以当我扫描S / N时。我的想法是,包含框中项目的表格会更改其颜色。我的英语很烂,所以我认为图像可以更好地解释我的想法。

所以我的代码执行以下操作:

首先,我使用框1(“ Gaveta”)中的信息加载表格:

http://prntscr.com/o4ykdy

然后,当我过滤框中的项目的序列号时:

http://prntscr.com/o4yly4

面对我的问题,搜索绘制了正确的序列号,但它会损坏我的表模型。

我的代码:

数据搜索:

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

}  

表格渲染器:

公共类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;
    }

退回该商品

}  }

我想做的是绘制与进行搜索的textField“序列号”匹配的每个S / N。

类似这样的东西:

http://prntscr.com/o4ynui

因此,如果我搜索新的S / N,则在继续扫描S / N的同时获得一个标记,然后从表中删除未标记的S / N。

3 个答案:

答案 0 :(得分:1)

由于您没有给我们minimal-reproducible example,因此,我创建了自己的示例,以向您展示如何完成此操作。对JTable使用下划线会很棘手,因为(我认为)需要JTextPane。但是,通过突出显示表格单元格中的搜索文本,可以更轻松地实现类似目的。当然,要做到这一点,我们需要创建自己的自定义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);
        });

    }
}

预览:

enter image description here

答案 1 :(得分:0)

好吧,我实际上可以做我想做的事情,现在我必须细化一些细节。

首先是渲染器代码:

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

然后我将其应用于表格

nsrs.close();
                        stmnt.close();
                        tablaDiscosGaveta.setModel(ModeloTablaLista);
                        ClaseColor comp = new ClaseColor(0);                            
                        tablaDiscosGaveta.getColumnModel().getColumn(0).setCellRenderer(comp);

           }

与此匹配的是,我可以过滤并在匹配过滤器时将背景设置为绿色。

但是在过滤时它仅显示“零”,所以我需要修复它。

Filter is ok

It shows the background i wanted but not the serial i need

答案 2 :(得分:0)

最终更新,我解决了在以下行更改值的问题:

   Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, col, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);

        Component comp = super.getTableCellRendererComponent(tablaDiscosGaveta, value, rootPaneCheckingEnabled, rootPaneCheckingEnabled, row, col);

Finally !