简体   繁体   中英

Adding several Components to a Jpanel

I want to add several components to a JPanel and then add the panel to a JFrame.

Here is a short sample program:

public class Test extends JPanel {

    private static final long serialVersionUID = -5616883761578620198L;

    static JPanel jpanel;
    private static JLabel jLabel;

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //adding everything to the jpanel
        jpanel = new JPanel();
        jpanel.add(addLabel());
        jpanel.add(addTable());

        //adding the jpanel to the frame
        frame.add(jpanel);

        frame.pack();
        frame.setVisible(true);
    }

    public static Component addTable() {

        jLabel = new JLabel("Test");

        String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
        "Vegetarian"};

        Object[][] data = {
                {"Kathy", "Smith",
                    "Snowboarding", new Integer(5), new Boolean(false)},
                    {"John", "Doe",
                        "Rowing", new Integer(3), new Boolean(true)},
                        {"Sue", "Black",
                            "Knitting", new Integer(2), new Boolean(false)},
                            {"Jane", "White",
                                "Speed reading", new Integer(20), new Boolean(true)},
                                {"Joe", "Brown",
                                    "Pool", new Integer(10), new Boolean(false)}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(table);

        table.add(scrollPane);

        return this; //do not know how to return the whole component?
    }

    public static Component addLabel() {

        jLabel = new JLabel("Test1");

        return jLabel;
    }


    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

However, I am getting the exception:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding container's parent to itself

Any suggestions how to fix that?

cause of this line return this; //do not know how to return the whole component? return this; //do not know how to return the whole component?

you are returning THIS --> this is a JPanel, cause you inherit your class from JPanel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM