user2565352
user2565352

Reputation: 1

Java JTable inside a JFrame different classes

I am having trouble picturing how to get a table I made that references a sqlite database into a JTable, then put that JTable into a JFrame that exists in a different class.

I want the table from SearchBooks to be passed to the UserInterface class. I am thinking that the showTableData method in SearchBooks could be loaded into the JFrame (UIFrame) that exists in UserInterface class. - In fact thats what I am trying to do. It doesn't seem as simple as just calling the showTableData class, or I may be missing some crucial element.

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

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

public class SearchBooks implements ActionListener {
    JFrame SBFrameCol, SBFrameDisplay;
    JTextField textbox;
    JLabel label;
    JButton button;
    JPanel panel;
    static JTable table;


    String driverName = "org.sqlite.JDBC";
    String url = "jdbc:sqlite:Library.db";
    //String userName = "root";
    //String password = "root";

    String[] columnNames = { "Book ID", "Book Name", "Book Author", "Quantity" };

    public void createUI() {
        SBFrameCol = new JFrame("Database Search Result");
        SBFrameCol.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SBFrameCol.setLayout(null);
        textbox = new JTextField();
        textbox.setBounds(400, 130, 250, 30);
        label = new JLabel("Enter A Book Name or Author Name");
        label.setBounds(100, 130, 300, 30);
        button = new JButton("search");
        button.setBounds(220, 200, 150, 20);
        button.addActionListener(this);

        SBFrameCol.add(textbox);
        SBFrameCol.add(label);
        SBFrameCol.add(button);
        SBFrameCol.setVisible(true);
        SBFrameCol.setSize(700, 400);
    }

    public void actionPerformed(ActionEvent ae) {
        button = (JButton) ae.getSource();
        System.out.println("Showing Table Data.......");
        showTableData();
    }

    public void showTableData() {

        SBFrameDisplay = new JFrame("Database Search Result");
        SBFrameDisplay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SBFrameDisplay.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);
        String textvalue = textbox.getText();
        String bID;
        String bName = "";
        String aName = "";
        String quantity;
        try {
            Class.forName(driverName);
            Connection con = DriverManager.getConnection(url);
            String sql = "SELECT * FROM Books WHERE (book_name LIKE '%" + textvalue + "%') OR (book_author LIKE '%" + textvalue + "%');";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            int i = 0;
            while (rs.next()) {
                bID = rs.getString("book_id");
                bName = rs.getString("book_name");
                aName = rs.getString("book_author");
                quantity= rs.getString("quantity");
                model.addRow(new Object[] { bID, bName, aName, quantity });
                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);
        }
        SBFrameDisplay.add(scroll);
        SBFrameDisplay.setVisible(true);
        SBFrameDisplay.setSize(400, 300);
    }

    public static void main(String args[]) {
        SearchBooks sr = new SearchBooks();
        sr.createUI();
    }
}

Here is my user Interface class (That contain the UIFrame frame I need to display the table information to).

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class UserInterface {

    public JFrame UIFrame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UserInterface window = new UserInterface();
                    window.UIFrame.setVisible(true);



                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public UserInterface() {
        initialize();
    }

    /**
     * Initialize the contents of the SBFrameCol.
     */
    private void initialize() {
        UIFrame = new JFrame();
        UIFrame.setTitle("Librarian Functions");
        UIFrame.setBounds(100, 100, 700, 800);
        UIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        UIFrame.getContentPane().setLayout(null);





        // When button clicked, we will go to the add book window
        JButton addBookButton = new JButton("Add Books");
        addBookButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                AddBook window = new AddBook();
                window.AddFrame.setVisible(true);
                UIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
        addBookButton.setBounds(40, 41, 117, 50);
        UIFrame.getContentPane().add(addBookButton);

         JButton SearchViewBooksButton = new JButton("Search/View Books");
//       JFrame window3 = new JFrame();

            SearchViewBooksButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    SearchBooks window = new SearchBooks();
                    window.createUI();
                    window.SBFrameCol.setVisible(true);

                    UIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
            });
            SearchViewBooksButton.setBounds(239, 130, 187, 61);
            UIFrame.getContentPane().add(SearchViewBooksButton);

        JButton viewAccountButton = new JButton("View Account");
        viewAccountButton.setBounds(45, 130, 146, 61);
        UIFrame.getContentPane().add(viewAccountButton);
    }
}

Also, is it ok for there to be multiple public static void main(String[] args) in a java program? I have it that way right now but I'm sure it is not good practice, any thoughts?

Thank you in advance.

Upvotes: 0

Views: 358

Answers (1)

Lotsa
Lotsa

Reputation: 412

Something to try, is fill your model first, and then pass it to the JTable. You are passing the model to the table first, and then manipulating the data after. I do it the other way around ... like this:

    final Object[][] dataBlob =
        blobProcessor.getOneBudgetExpensesDatabaseBlob( expenseList );
    final DefaultTableModel defTModel = new DefaultTableModel( dataBlob,
        new String [] { "Description", "Amount", "Source", "Date", "File" }
    );
    jTable1.setModel(defTModel);

I use the same table, but create a new model each time I show something, fill it, and then pass it to the JTable after filling the model.

You're all in one spot there, so just wait and pass the model to the Table after, instead of before.

I'll add that in my code, I'm getting a database query there as a list (expenseList) and then passing that to a blobProcessor that sets the query result into an Object[][] array and returns it to me to place into the model. Then the model goes into the table ... last, not first.

Upvotes: 1

Related Questions