提问者:小点点

JavaJTable内一个JFrame不同的类


我无法想象如何将我制作的表引用sqlite数据库到JTable中,然后将该JTable放入存在于不同类中的JFrame中。

我希望SearchBooks中的表被传递给UserInterface类。我认为SearchBooks中的showTableData方法可以加载到UserInterface类中存在的JFrame(UIFrame)中。-事实上,这就是我正在尝试做的。它似乎不像仅仅调用showTableData类那么简单,或者我可能缺少一些关键元素。

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();
    }
}

这是我的用户接口类(包含我需要显示表信息的UIFrame框架)。

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);
    }
}

另外,在一个java程序中有多个公共静态void main(String[]args)可以吗?我现在就是这样,但我肯定这不是好的做法,有什么想法吗?

提前谢谢你。


共1个答案

匿名用户

要尝试的事情是首先填充您的模型,然后将其传递给JTable。您首先将模型传递给表,然后操作数据。我反过来做…像这样:

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

我使用相同的表,但每次显示某些内容时都会创建一个新模型,填充它,然后在填充模型后将其传递给JTable。

你们都在一个地方,所以只需等待,然后将模型传递给Table,而不是之前。

我将在我的代码中添加它,我将在那里获取一个数据库查询作为列表(expenseList),然后将其传递给一个blobProcess,该处理器将查询结果设置为Object[][]数组并将其返回给我以放入模型中。然后模型进入表…最后,而不是第一个。