简体   繁体   中英

Java Swing: Add tabs into JPanels

I have a series of tabs, but I want to then add further tabs within the panel it displays, as if to replicate a ribbon menu. I roughly know what needs to be done (changing the return type of the makeTextPanel function) but don't know how to so any help would be appreciated.

package components;

import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;

public class ribbonMenu extends JPanel {
        public ribbonMenu() {
                super(new GridLayout(1,1));

                JTabbedPane tabbedPane = new JTabbedPane();

                JTabbedPane tabbedPane2 = new JTabbedPane();

                JComponent panel1 = makeTextPanel("Panel #1");
                tabbedPane.addTab("Tab 1", panel1);
                panel1.setPreferredSize(new Dimension(600, 400));

                JComponent panel2 = makeTextPanel("Panel #2");
                tabbedPane.addTab("Tab 2", panel2);

                JComponent panel3 = makeTextPanel("Panel #3");
                tabbedPane.addTab("Tab 3", panel3);

                add(tabbedPane);

                tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);           
        }

        protected JComponent makeTextPanel (String text) {
                JPanel panel = new JPanel(false);
                JLabel filler = new JLabel(text);
                filler.setHorizontalAlignment(JLabel.CENTER);
                panel.setLayout (new GridLayout(1,1));
                panel.add(filler);
                return panel;
        }

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

            frame.add(new ribbonMenu(), BorderLayout.CENTER);

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

        public static void main(String[] args) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        UIManager.put("swing.boldmetal", Boolean.FALSE);
                        createAndShowGUI();
                    }

                });
        }
}

Thanks

Why You need to change the return type?

Instead of this

JComponent panel1 = makeTextPanel("Panel #1");

use

JPanel panel1 = (JPanel)makeTextPanel("Panel #1");

And for further tabs You can again add JTabbedPane in that panel

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