简体   繁体   中英

Adding onto JPanel

I was wondering if it was possible to add dropdown menus to a main JPanel from a different class instead of calling it from that class itself. Mainly because a friend and I are working on a personal project trying to create different programs in different tabs.

Here's our main GUI:

public class GUI extends JFrame {

    public GUI() {
        setTitle("Andy and Jack's favorite programs");
        JTabbedPane jtp = new JTabbedPane();
        getContentPane().add(jtp);

        JPanel jp1 = new JPanel();
        JLabel label1 = new JLabel();

        JPanel jp2 = new JPanel();
        JLabel label2 = new JLabel();

        jp1.add(label1);
        jtp.addTab("Andy - Encryption Program");
        jp2.add(label2);
        jtp.addTab("Andy - Hello World Program");
   }

   public static void main(String[] args) {
       GUI tp = new GUI();
       tp.setVisible(true);
       tp.setMinimumSize(new Dimension(400, 400));
   }

Here's one of our tabs:

public class encryptionPrograms extends GUI {
    String[] options = new String[] { "XOR", "RSA" };
    ComboBox optionsList = new JComboBox(options);
    jp1.add(optionsList, BorderLayout.CENTER);
}

I'm not sure if I'm doing it correctly or not. Just got into Java and we've have been playing around with the GUI buttons and such.

There is a lot of "wrong" here and without you saying what your intention is with adding a comboBox to your jPanel it's hard to tell you the right way to do it but yes it can be done.

But first of: Always declare your variables before you initialize them so that you can access them for other methods in the class:

public class GUI extends JFrame{
    private JPanel jp1,jp2;
    private JLabel label1,label2;
    private JTabbedPane jtp;

    public GUI() {
        setTitle("Andy and Jack's favorite programs");
        jtp = new JTabbedPane();

        jp1 = new JPanel();
        label1 = new JLabel();

        jp2 = new JPanel();
        label2 = new JLabel();

        jp1.add(label1);
        jtp.addTab("Andy - Encryption Program", jp1);
        jp2.add(label2);
        jtp.addTab("Andy - Hello World Program",jp2);

        getContentPane().add(jtp);
   }

If you need to access a variable from another class you can write a get method for it.

For example:

public JPanel getMainJPanel(){
       return jp1;
}

Now you can call the getMainJPanel() from another class in order to, for instance, add components to it. Just remember to .revalidate() and .repaint() the main frame after adding more components.

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