ScrollBar in a JTable

0

I added a JTable that updates the data as the client is typing in a JTextField field. However, when the client search returns multiple rows, I would like JTable to have a scroll so that the client can see all the results.

I tried some things but I did not succeed, follow the code for evaluation.

JTable Code:

table = new JTable();

table.addMouseListener(new MouseAdapter() {
 @Override
 public void mousePressed(MouseEvent e) {
  if (e.getClickCount() == 1) {
   String selectedData = null;

   JTable target = (JTable) e.getSource();

   int selectedRow = target.getSelectedRow();
   int selectedColumn = target.getSelectedColumn();

   System.out.println("Selected row " + " " + selectedRow);
   System.out.println("Selected column" + " " + selectedColumn);

   Object selectedCellValue = target.getValueAt(selectedRow, selectedColumn);
   System.out.println("selectedCellValue " + " " + selectedCellValue);
  }
 }
});
table.setBounds(10, 44, 0, 0);
getContentPane().add(table);
}

{
 {
  table.setBounds(10, 11, 560, 311);

 }

Full Code

package matheus.arruda.lab.wn.tratermik;

import java.awt.BorderLayout;

public class abrirospop extends JDialog {
    private JTable table;
    private JTextField txtpesquisar;

    Vector originalTableModel;

    /**
    * Launch the application.
    */
    public static void main(String[] args) {
        try {
            abrirospop dialog = new abrirospop();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
            } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * Create the dialog.
    * @throws ClassNotFoundException
    */
    public abrirospop() throws ClassNotFoundException {
        setIconImage(Toolkit.getDefaultToolkit().getImage(abrirospop.class.getResource("/matheus/arruda/lab/wn/tratermik/icones/Application-Form-Magnify.png")));
        setTitle("Abrir OS");
        setBounds(100, 100, 596, 420);
        getContentPane().setLayout(null);
        {
            table = new JTable();

            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    if (e.getClickCount() == 1)
                    {
                        String selectedData = null;

                        JTable target = (JTable)e.getSource();

                        int selectedRow = target.getSelectedRow();
                        int selectedColumn = target.getSelectedColumn();

                        System.out.println("Selected row "+ " "+ selectedRow);
                        System.out.println("Selected column"+ " "+ selectedColumn);

                        Object selectedCellValue=target.getValueAt(selectedRow, selectedColumn);
                        System.out.println("selectedCellValue "+" "+selectedCellValue);
                    }
                }
            });
            table.setBounds(10, 44, 0, 0);
            getContentPane().add(table);

        }

        {
            {
                table.setBounds(10, 11, 560, 311);

            }

            txtpesquisar = new JTextField();

            txtpesquisar.getDocument().addDocumentListener(new DocumentListener() {
                public void changedUpdate(DocumentEvent e) {
                    try {
                        warn();
                        } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                public void removeUpdate(DocumentEvent e) {
                    try {
                        warn();
                        } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                public void insertUpdate(DocumentEvent e) {
                    try {
                        warn();
                        } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }


                public void warn() throws ClassNotFoundException {
                    String valor = txtpesquisar.getText();

                    String colunas[] = {"OS #N","Cliente","Responsável","Data O.S","Prazo de Entrega"};

                    try {
                        Class.forName("org.sqlite.JDBC");
                        Connection con = DriverManager.getConnection("jdbc:sqlite:C:\Tratermikos\banco de dados\tratermik.db");
                        Statement stat = con.createStatement();

                        ResultSet rs;

                        rs = stat.executeQuery("select _id,cliente,responsavel_relatorio,data_inicio,data_fim from tratermik where cliente like ""+valor+"%"+""");

                        ResultSetMetaData rsmd = rs.getMetaData();
                        int columnCount = rsmd.getColumnCount();

                        DefaultTableModel tm = (DefaultTableModel) table.getModel();
                        tm.setColumnCount(0);

                        for(int i = 1; i <= columnCount; i++) {
                            tm.addColumn(rsmd.getColumnName(i));

                        }
                        tm.setRowCount(0);
                        tm.addRow(colunas);
                        while(rs.next()) {
                            String[] a = new String[columnCount];
                            for(int i = 0; i < columnCount; i++) {
                                a[i] = rs.getString(i+1);

                            }

                            tm.addRow(a);
                        }
                        tm.fireTableDataChanged();

                        rs.close();
                        con.close();
                        } catch (SQLException sqle) {
                        JOptionPane.showMessageDialog(new JFrame(), sqle + "n"+"Por favor contate o desenvolvedor ou o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

                        sqle.printStackTrace();
                    }

            }});

            txtpesquisar.setBounds(10, 350, 161, 20);
            getContentPane().add(txtpesquisar);
            txtpesquisar.setColumns(10);

            JLabel lblFiltrarPorCliente = new JLabel("Filtrar por Cliente");
            lblFiltrarPorCliente.setBounds(38, 333, 99, 17);
            getContentPane().add(lblFiltrarPorCliente);
            String colunas[] = {"OS #N","Cliente","Responsável","Data O.S","Prazo de Entrega"};

            table.setPreferredScrollableViewportSize(Toolkit.getDefaultToolkit().getScreenSize());
            try {
                Class.forName("org.sqlite.JDBC");
                Connection con = DriverManager.getConnection("jdbc:sqlite:C:\Tratermikos\banco de dados\tratermik.db");
                Statement stat = con.createStatement();

                ResultSet rs;

                //rs = stat.executeQuery("select _id,cliente,  responsavel_relatorio,data_inicio,data_fim from tratermik");
                rs = stat.executeQuery("select * from clientes");
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();

                DefaultTableModel tm = (DefaultTableModel) table.getModel();
                tm.setColumnCount(0);

                for(int i = 1; i <= columnCount; i++) {
                    tm.addColumn(rsmd.getColumnName(i));

                }
                tm.setRowCount(0);
                tm.addRow(colunas);
                while(rs.next()) {
                    String[] a = new String[columnCount];
                    for(int i = 0; i < columnCount; i++) {
                        a[i] = rs.getString(i+1);

                    }

                    tm.addRow(a);
                }
                tm.fireTableDataChanged();

                rs.close();
                con.close();
                } catch (SQLException sqle) {
                JOptionPane.showMessageDialog(new JFrame(), sqle + "n"+"Por favor contate o desenvolvedor ou o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

                sqle.printStackTrace();
            }

        }

    }

    private class HighlightRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            // everything as usual
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            // added behavior
            if(row == table.getSelectedRow()) {

                // this will customize that kind of border that will be use to highlight a row
                setBorder(BorderFactory.createMatteBorder(2, 1, 2, 1, Color.BLACK));
            }

            return this;
        }
    }
}
    
asked by anonymous 23.04.2016 / 19:07

1 answer

1

Add the JTable to a ScrollPane , this container which is responsible for providing scroll when the table needs, and also display the table header correctly:

table.setBounds(10, 44, 0, 0);
ScrollPane scroll new ScrollPane();
scroll.add(table);
getContentPane().add(scroll);
    
23.04.2016 / 19:11