简体   繁体   中英

Java Swing JTabbedPane add JPanel to tab then modify it

I want to create a JTabbedPane, add a JPanel to everyone and then add something to the JPanel:

private void initTabbedPane(JTabbedPane tp)
{
    System.out.println("FestplattenreinigerGraphicalUserInterface::initTabbedPane()");

    // Init Tab-Names
    Vector<String> tabNames = new Vector<String>();
    tabNames.addElement("Startseite");
    tabNames.addElement("Konfiguration");
    tabNames.addElement("Hilfe");

    // Init Tabs
    tp = new JTabbedPane();
    JPanel tmpPanel;
    for(int i = 0; i < tabNames.size(); i++)
    {
        tmpPanel = new JPanel();
        tp.addTab(tabNames.elementAt(i), tmpPanel);
    }
    tp.setFont(new Font("Calibri", Font.BOLD, 11));
    initPanelsInTabbedPane(tp);
    this.getContentPane().add(tp, BorderLayout.CENTER);
}

private void initPanelsInTabbedPane(JTabbedPane tp)
{
    System.out.println("FestplattenreinigerGraphicalUserInterface::initPanelsInTabbedPane()");

    tp.getComponentAt(0).add(new JButton("HELLOSTUPIDJAVAIHATEU"));
}

Well it says: incompatible types found : java.awt.Component required: javax.swing.JPanel JPanel p = tp.getComponentAt(0);

But my book says that with, Component getComponentAt(int index), i can access it's content and i remember that JButton is a Component right? So wth?

If you take a look at Javadoc, you'll see that, indeed, JTabbedPane#getComponentAt(index) returns a Component . However, if you're sure it's a JPanel (which is more or less the case when accessing tabs of a JTabbedPane ), you can always cast it :

((JPanel) tp.getComponentAt(0)).add(new JButton("come on, Java is nice enough, no ?"));

Or, even better if you know some things about Swing

((JCompoonent) tp.getComponentAt(0)).add(new JButton("No, Java and Swing positively rock hard awesome !"));

indeed, JPanel is a subclass of JComponent , which is

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