Question

So, my requirement was to Display Records From Database Using JTable in Java. I referred the this link. But the error is that when I run it in Eclipse, I can't see the combobox as it should ideally appear. How to fix it ?

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

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

    public class DisplayEmpData 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;
        String[] columnNames = {"User name", "Email", "Password", "Country"};
        String from;

        DisplayEmpData() {

            l0 = new JLabel("Fatching Employee Information");
            l0.setForeground(Color.red);
            l0.setFont(new Font("Serif", Font.BOLD, 20));
            l1 = new JLabel("Select name");
            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);

            setTitle("Fetching Student Info From DataBase");
            setLayout(null);
            setVisible(true);
            setSize(500, 500);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

            add(l0);
            add(l1);;
            add(b1);
            try {

                String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\emp_details.accdb";
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                con=DriverManager.getConnection(url,"","");
                /*con = DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe", "sandeep", "welcome");*/
                st = con.createStatement();
                rs = st.executeQuery("select uname from emp");
                Vector v = new Vector();
                while (rs.next()) {
                    ids = rs.getString(1);
                    v.add(ids);
                }
                c1 = new JComboBox(v);
                c1.setBounds(150, 110, 150, 20);

                add(c1);
                st.close();
                rs.close();
            } catch (Exception e) {
            }
        }

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

        }

        public void showTableData() {

            frame1 = new JFrame("Database Search Result");
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame1.setLayout(new BorderLayout());
    //TableModel tm = new TableModel();
            DefaultTableModel model = new DefaultTableModel();
            model.setColumnIdentifiers(columnNames);
    //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
    //table = new JTable(model);
            table = new JTable();
            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 textvalue = textbox.getText();
            String uname = "";
            String email = "";
            String pass = "";
            String cou = "";

            try {
                pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");
                ResultSet rs = pst.executeQuery();
                int i = 0;
                if (rs.next()) {
                    uname = rs.getString("uname");
                    email = rs.getString("umail");
                    pass = rs.getString("upass");
                    cou = rs.getString("ucountry");
                    model.addRow(new Object[]{uname, email, pass, cou});
                    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);
            }
            frame1.add(scroll);
            frame1.setVisible(true);
            frame1.setSize(400, 300);
        }

        public static void main(String args[]) {
            new DisplayEmpData();
        }
    }
Was it helpful?

Solution 2

The problem in your code is you adding combobox after setting frame's visibily=true. Please add all the components before setting frame's visibilty. I changed your constructor. Please note that using a null layout is not a good habbit (I think so) use any of LayoutManagers

DisplayEmpData() {

        l0 = new JLabel("Fatching Employee Information");
        l0.setForeground(Color.red);
        l0.setFont(new Font("Serif", Font.BOLD, 20));
        l1 = new JLabel("Select name");
        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);

        setTitle("Fetching Student Info From DataBase");
        setLayout(null);

        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(l0);
        add(l1);;
        add(b1);
        try {

            Vector v = new Vector();

            String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\emp_details.accdb";
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection(url,"","");
            /*con = DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe", "sandeep", "welcome");*/
            st = con.createStatement();
            rs = st.executeQuery("select uname from emp");

            while (rs.next()) {
                ids = rs.getString(1);
                v.add(ids);
            }
            c1 = new JComboBox(v);
            c1.setBounds(150, 110, 150, 20);

            add(c1);
            st.close();
            rs.close();
        } catch (Exception e) {
        }

        setVisible(true);
    }

OTHER TIPS

First of all, my advice is to use more meaningful names for methods and fields in your code: it may look crisp clear to you now, but for both an external reader and yourself in a couple of month what the code does won't be apparent at all.

That said, you are probably better off using a LayoutManager, that ensures correct Component placement and visibility along platforms (as @Andrew Thompson pointed out already).

Basically speaking, first step is to create a JPanel and add it to your JFrame:

JPanel framePanel;
framePanel = new JPanel();
this.add(framePanel);

When no arguments are specified in the JPanel() constructor, the layout is automatically set as a BorderLayout. This layout has 5 areas you can place a component in: North, South, West, East, Center.

You can now add other JPanels to your framePanel like so:

JPanel northPanel;
JPanel southPanel;
JPanel westPanel;
JPanel eastPanel;
JPanel centerPanel;

northPanel = new JPanel();
southPanel = new JPanel();
westPanel = new JPanel();
eastPanel = new JPanel();
centerPanel = new JPanel();

framePanel.add(northPanel, BorderLayout.NORTH);
framePanel.add(southPanel, BorderLayout.SOUTH);
framePanel.add(westPanel, BorderLayout.WEST);
framePanel.add(eastPanel, BorderLayout.EAST);
framePanel.add(centerPanel, BorderLayout.CENTER);

Each panel may contain another JPanel or one of your components. One of the most useful and basic LayoutManager you can use to lay multiple components is GridLayout, that lets you specify a grid size (number of rows and columns): every time you add a component, it is placed in the first free slot starting from the upper left hand corner.

If you were to add 3 components to your northPanel you would code

northPanel.setLayout(new GridLayout(1, 3));

northPanel.add(component1);
northPanel.add(component2);
northPanel.add(component3);

These are just examples, you can find more info in the Java API's if you search for LayoutManager. Just some quick tips:

  • You can specify a Layout directly in the JPanel constructor:

    JPanel testPanel = new JPanel(new GridLayout(rows, columns));

  • You can add white spaces by inserting an empty JPanel in your grid places:

    JPanel whiteSpacePanel = new JPanel();   
    
    testPanel.add(component1);
    testPanel.add(whiteSpacePanel);
    testPanel.add(component2);
    
  • You can specify some basic borders between Components in the Layout constructor

    JPanel panelWithBorders = new JPanel(new GridLayout(rows, columns, xBorder, yBorder));

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top