简体   繁体   中英

Cannot show JTable in JFrame

I am trying to show the results of an sql query "SELECT * FROM..." in a JFrame. After a bit of digging I made the below using and some code that I found in another post here. My problem is that it does not show the Jtable in my JFrame. I am complete newbie in this (this is my first try combining sql and java for gui) so any help would be really appreciated...

CODE for frame:

import java.awt.*;

import javax.swing.*;
import javax.swing.border.Border;

public class Frame  extends JFrame {

    public Frame() throws HeadlessException {
        super();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Border loweredetched = null;
        Font font = new Font("monospaced", Font.PLAIN, 11);

        JPanel panel = new JPanel(new BorderLayout());
        JPanel leftPanel = new JPanel();
        JPanel rightPanel = new JPanel();
        JPanel lowerPanel = new JPanel();
        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(rightPanel, BorderLayout.EAST);


        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));

        //JScrollPane scrollPane = new JScrollPane(GetSongs.table);


        /*JTextArea text = new JTextArea(15, 3);
        text.setMargin(new Insets(5, 5, 5, 5));
        text.setBackground(Color.darkGray);
        text.setForeground(Color.white);
        text.setFont(font);
        text.setEditable(false);*/

        JButton button = new JButton("Update");
        lowerPanel.add(button);

        leftPanel.setBorder(BorderFactory.createTitledBorder(loweredetched, "Songs"));
        leftPanel. add( new JScrollPane( GetSongs.table ), BorderLayout.CENTER );;
        leftPanel.add(lowerPanel);


        JTextArea textR = new JTextArea(1, 3);
        textR.setMargin(new Insets(5, 5, 5, 5));
        textR.setBackground(Color.darkGray);
        textR.setForeground(Color.white);
        textR.setFont(font);
        textR.setEditable(false);

        rightPanel.setBorder(BorderFactory.createTitledBorder(loweredetched, "ToBuy"));
        rightPanel.add(textR);


        getContentPane().add(panel, BorderLayout.NORTH);
        pack();
    }

    public static void main(String[] args){
        new Frame();
        }
}

CODE of class to connect to db and make query:

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

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

import java.awt.*;

public class GetSongs extends JFrame {

// MAKES A QUERY TAKES THE RESULT SET AND PRODUCES A JTABLE
    public static JTable table;

    public GetSongs() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
        String connectionURL = "jdbc:mysql://localhost:3306/songs";
        Connection connection = null;
        Statement statement = null;

        //do not use in production!!
        String dbuser = "root";
        String dbpass = "";

        ResultSet rs = null;

        Class.forName("com.mysql.jdbc.Driver").newInstance(); //
        connection = DriverManager.getConnection(connectionURL, dbuser, dbpass);
        statement = connection.createStatement();

        String query = "SELECT * FROM songs JOIN purchases WHERE id = song_id and user_id =2;";
        rs = statement.executeQuery(query);

        table = new JTable(buildTableModel(rs));
        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
    }

    public static DefaultTableModel buildTableModel(ResultSet rs)
            throws SQLException {

        ResultSetMetaData metaData = rs.getMetaData();

        // names of columns
        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        System.out.println(columnCount);
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }

        // data of the table
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                vector.add(rs.getObject(columnIndex));
            }
            data.add(vector);
        }

        return new DefaultTableModel(data, columnNames);
    }

}

As an alternative, you could use a SwingWorker.

You would retrieve all the database information in the doInBackground() method, and then you would populate your table in the done() method.

Since I can't explain it all to you, there is more information here:

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

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