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开发者_StackOverflow中文版 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 root class of all Swing components
- an awt Container
精彩评论