簡體   English   中英

從另一個函數訪問jframe並將jpanel添加到其中-Java Swing

[英]Access jframe from another function and add jpanel into it - java swing

我正在嘗試實現特定的GUI,但是我無法將JPanel插入到在另一個函數中初始化的jframe中,怎么做呢?

這是我的代碼:

public class CDRTable {
    int totalRecords;
    private final String[] columnNames = { "Year", "String", "Comment" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI() throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }

        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        JPanel p = new JPanel(new BorderLayout());
        p.add(box, BorderLayout.NORTH);
        p.add(new JScrollPane(table));
        return p;
    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI());
        f.setBounds(30, 50, 1300, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }


}

當我嘗試從public JComponent makeUI()訪問createAndShowGUI()初始化的public JComponent makeUI() ,顯示錯誤

f無法解決

我是JAVA的新手,所以如果您對我的問題感到惱火,請忽略:)

不知何故,我達到了想要的目標,所以我認為我應該把自己的答案放在這里。

public class CDRTable {
    //JFrame f;
    int totalRecords;
    private final String[] columnNames = { "ANUMBER", "BNUMBER", "DATETIME" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI(Container f) throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }
        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        UIManager.put("TabbedPane.selected", Color.lightGray);
        JTabbedPane tabbedPane = new JTabbedPane();
        f.add(tabbedPane);

        JPanel panel = new JPanel();
        tabbedPane.addTab("TABLE", null, panel, null);
        panel.setBackground(Color.white);

        JPanel panel_1 = new JPanel();
        tabbedPane.addTab("GRAPH", null, panel_1, null);
        panel_1.setBackground(Color.white);

        JScrollPane scrollpane = new JScrollPane();
        panel.add(scrollpane, BorderLayout.SOUTH);
        scrollpane.setViewportView(table);

        table.getTableHeader().setBackground(new Color(26,82,118));
        table.getTableHeader().setForeground(Color.white);
        table.getTableHeader().setPreferredSize(new Dimension(100, 40));
        table.setRowHeight(30);

        first.setBackground(new Color(84, 153, 199));
        prev.setBackground(new Color(84, 153, 199));
        next.setBackground(new Color(84, 153, 199));
        last.setBackground(new Color(84, 153, 199));

        first.setForeground(Color.white);
        prev.setForeground(Color.white);
        next.setForeground(Color.white);
        last.setForeground(Color.white);

        panel.add(box);
        panel.add(new JScrollPane(table));
        return scrollpane;

    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame("CDR TABLE");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI(f));
        f.setBounds(30, 50, 1300, 600);
        f.setLayout(new GridLayout(0, 2));
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }


}

暫無
暫無

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

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