Java Swing:在JPanels中添加标签

时间:2013-02-22 20:50:50

标签: java swing jpanel jtabbedpane

我有一系列标签,但我想在其显示的面板中添加更多标签,就像复制功能区菜单一样。我大致知道需要做什么(更改makeTextPanel函数的返回类型),但不知道如何提供任何帮助。

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

                });
        }
}

由于

1 个答案:

答案 0 :(得分:0)

为什么需要更改返回类型?

而不是这个

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

使用

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

如需更多标签,您可以再次在该面板中添加JTabbedPane