从另一个函数访问jframe并将jpanel添加到其中 - java swing

时间:2017-07-06 06:46:23

标签: java swing jframe jpanel

我正在尝试实现一个特定的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);
    }


}

当我尝试从createAndShowGUI()访问public JComponent makeUI()中初始化的jframe时,显示错误

  

f无法解决

我对JAVA很新,所以如果你对我的问题感到恼火,请不要理会:)

1 个答案:

答案 0 :(得分:0)

不知何故,我实现了我想要的,所以我想我应该把答案放在这里。

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


}