簡體   English   中英

如何正確地從類中調用JFrame?

[英]How can I properly call a JFrame from a class?

我試圖實例化一個JFrame實例,但是每次引用該類時,都會顯示一個新的JFrame。

我的代碼的目標是從菜單欄中選擇一個選項,然后我的數據庫模板/表將顯示在框架中,在該框架中,它還會在過程中創建另外兩個JFrame,我相信我已經找到了問題; 我只是不知道如何解決上述問題。

如上所述,每次我要引用我的JFrame類向框架中添加模板時,由於我的類的設置方式,它都會創建一個額外的JFrame,如何改善我的代碼以免發生這種情況?

這是我的代碼:

當我從JFrame的菜單欄中選擇一個項目時,將調用tigerActionPerformed()方法。

public class MenuActionListener implements ActionListener {

    public void tigerActionPerformed() {

        MyFrame frame = new MyFrame();
        frame.getDatabasePanel();

    @Override
    public void actionPerformed(final ActionEvent e) {
        String command = e.getActionCommand();

        switch (command) {

            case "tiger":
                tigerActionPerformed();
                break;

            default:
        }
    }
}

然后調用frame類將數據庫添加到JFrame。

public class MyFrame{

    private JFrame frame;

    public MyFrame() {

        MenuBar menuBarInstance = new MenuBar();

        frame = new JFrame();
        frame.setTitle("Stock Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setPreferredSize(new Dimension(720, 480));
        frame.setJMenuBar(menuBarInstance.getMenuBar());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public void getDatabasePanel() {

        //Add database test
        acp.addDatabaseTemplate(frame);

    }

}

此類將數據庫模板添加到面板中,並且該面板已添加到JFrame中。

public class AddComponentsToPane {

    public void addDatabaseTemplate(Container pane) {

        //We need to have a new class to fill the database table
        StockApplication stockApp = new StockApplication();

        JTable tigerTable = new JTable();
        tigerTable.setModel(new DefaultTableModel(0, 3));

        stockApp.FillTable(tigerTable, "SELECT * FROM TIGER_INFO");

        JPanel centerPanel = new JPanel(new GridBagLayout());

        //We need center panel to add a JTable
        //centerPanel.add(tigerTable, new GridBagConstraints());

        GridBagConstraints c = new GridBagConstraints();

        c.weightx = 1.0;
        c.weighty = 1.0;
        c.insets = new Insets(6, 6, 6, 6);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.FIRST_LINE_START;
        centerPanel.add(tigerTable, c);

        pane.add(centerPanel, BorderLayout.CENTER);

    }

}

每次調用getDatabasePanel()時,您都在創建一個新的JFrame()。

MyFrame frame = new MyFrame();
frame.getDatabasePanel();

因為您已經在代碼頂部創建了JFrame frame ,所以您不需要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM