简体   繁体   中英

JTable gets displayed only once for search query in JFrame

So, after giving a layout to my controls, I find that my table doesn't seem to display. Label (l1), the combobox and the submit button gets displayed in my desired manner, even the console messages workk fine. Just that the Jtable that should appear after the search doesn't get displayed.

Where could the error lie and how should it be corrected. This is my code:-


import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class r_search_2 extends JFrame implements ActionListener {

    JFrame frame1;
    JLabel l0, l1, l2;
    JComboBox c1;
    JButton b1;
    Connection con;
    ResultSet rs, rs1;
    Statement st, st1;
    PreparedStatement pst;
    String ids;
    static JTable table  = new JTable();;
    String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
    String from;
    Vector v = new Vector();
    JMenuBar menu = new JMenuBar();


    JPanel mainPanel = new JPanel(new BorderLayout());
    JPanel topPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 60,25));


    r_search_2() 
    {

        b1 = new JButton("submit");

        //l0.setBounds(100, 50, 350, 40);
        l1.setBounds(75, 110, 75, 20);
        b1.setBounds(150, 150, 150, 20);
        b1.addActionListener(this);

        topPanel.add(l1);

        try 
        {

            File dbFile = new File("executive_db.accdb");
            String path = dbFile.getAbsolutePath();
            con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            st = con.createStatement();
            rs = st.executeQuery("select index_name from Index1");
           while (rs.next())
           {
                ids = rs.getString(1);
                v.add(ids);

            }
            c1 = new JComboBox(v);
            c1.setEditable(true);c1.setSelectedItem("");
            c1.setBounds(150, 110, 150, 20);


            topPanel.add(c1);
            topPanel.add(b1);
            mainPanel.add(topPanel, BorderLayout.PAGE_START);

            st.close();
            rs.close();
        } catch (Exception e) {
        }
       // setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b1) {
            showTableData();
        }
     }

    public void showTableData()
    {

        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);

        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        from = (String) c1.getSelectedItem();

        String section_name = "";
        String report_name = "";
        String contact_name = "";
        String link = "";


        try
        {

        pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
                        + "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID )  LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID  "
                        + " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
            ResultSet rs = pst.executeQuery();
            int i = 0;
            while (rs.next()) {
                section_name = rs.getString("Section_Name");
                report_name = rs.getString("Report_Name");
                contact_name = rs.getString("Contact_Name");
                link = rs.getString("Link");
                model.addRow(new Object[]{section_name, report_name, contact_name, link});
                i++;
            }
            if (i < 1) {
                JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (i == 1) {
                System.out.println(i + " Record Found");
            } else {
                System.out.println(i + " Records Found");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        mainPanel.add(scroll);
        mainPanel.revalidate();
        mainPanel.repaint();

    }

    public static void main(String args[]) {


        r_search_2 s=new r_search_2();
        //new r_search_2();
        JFrame fr=new JFrame("Search Executive Reports");
        //fr.add(s.getUI());
        fr.add(s.mainPanel);
        fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        fr.setLocationByPlatform(true);
        fr.setSize(1000, 400);
        //fr.pack();
        fr.setVisible(true);

      //  new r_search_2();
    }
}

General comments:

  1. Use reasonable variable names if you want people to take the time to read your code. "b1", "l1" mean nothing.
  2. Get rid of all the setBounds() statements. Your panel uses a FlowLayout and the FlowLayout will determine the size/location of the components.

It doesn't appear the next time I type anything to search.

You are adding the table to the CENTER of the BorderLayout. So you now have two tables displayed in the CENTER. Swing paints the tables in reverse order to how the table were added. So the second table gets painted first, and the first table added gets painted second. So the first table is painted on top of the second table.

So you would need to remove the old scollpane first before adding the second scrollpane.

However there is an easier solution. As Sergiy has already suggested just create a new TableModel and replace the TableModel in the existing table:

table.setModel( theNewModel );

So really you should create the JTable and scrollpane and add it to your frame when you create the initial GUI. Then your search logic will just create a new DefaultTableModel and you update the table with the code from above.

Edit:

In the constructor where you create all the Swing components the basic code might be something like:

mainPanel.add(topPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(table); // added
mainPanel.add(scrollPane, BorderLayout.CENTER); // added

Now you have created and added an empty table to your GUI. The model is empty so there is nothing to display.

Now in your showTableData() method you don't need to create any more Swing components, So delete all those line of code that create the scrollpane and add the scrollpane to the frame.

The remaining code creates the model and adds it to the table and then adds data to the model so it should work as is. Although to be more efficient, you may want to move the table.setModel(...) statement to the end of the method so the table is only updated once after all the data has been loaded into the model.

It's a bad practice, but you can do following

    mainPanel.add(scroll);
    mainPanel.revalidate()
    mainPanel.repaint();

Good practice is to use CardLayout with empty panel when no search results must be shown.

Just a quick redesign of what you have done

Improvements: I quickly tried to divide the interface from the code bit, hope this help

public class r_search_2 extends JFrame implements ActionListener {

r_search_2(String Title) 
{
    super(Title);

    init();
}

private void init(){
    b1 = new JButton("submit");
    b1.addActionListener(this);


    c1 = new JComboBox(v);
    c1.setEditable(true);c1.setSelectedItem("");
    c1.setBounds(150, 110, 150, 20);

    topPanel.add(c1);
    topPanel.add(b1);
    mainPanel.add(topPanel, BorderLayout.PAGE_START);

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(columnNames);

    table.setModel(model);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFillsViewportHeight(true);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    from = (String) c1.getSelectedItem();

    String section_name = "";
    String report_name = "";
    String contact_name = "";
    String link = "";

    mainPanel.add(scroll);
    this.add(mainPanel);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.setLocationByPlatform(true);
    this.setSize(1000, 400);
    this.setVisible(true);

}   


public static void main(String args[]) {


    r_search_2 s=new r_search_2("Search Executive Reports");

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM