【问题标题】:Java JTable inside a JFrame different classesJava JTable里面一个JFrame不同的类
【发布时间】:2020-03-17 21:23:23
【问题描述】:

我无法想象如何将我创建的引用 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 程序中可以有多个 public static void main(String[] args) 吗?我现在就是这样,但我确定这不是一个好习惯,有什么想法吗?

提前谢谢你。

【问题讨论】:

  • Passing Information to a Method or a Constructor 将是一个开始的地方。话虽如此,我会考虑将表模型或可用于创建表模型的数据传递给类,而不是尝试传递 ui 组件
  • 一般情况下,您会将 JTable 放在 JScrollPane 中。 JScrollPane 将进入 JPanel。 JPanel 将进入 JFrame。
  • 1) 请学习常见的 Java 命名法(命名约定 - 例如EachWordUpperCaseClassfirstWordLowerCaseMethod()firstWordLowerCaseAttribute,除非它是 UPPER_CASE_CONSTANT)并始终如一地使用它。 2) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
  • .. 3) 为了尽快获得更好的帮助,edit 添加minimal reproducible exampleShort, Self Contained, Correct Example。替换数据库的硬编码数据。

标签: java swing jframe jtable


【解决方案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) 的形式获取数据库查询,然后将其传递给 blobProcessor,该 blobProcessor 将查询结果设置为 Object[][] 数组并将其返回给我放入模型中。 然后模型进入表格......最后,而不是第一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2011-11-02
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多