I'm simply trying to add a JLabel to an existing JPanel. This seems really simple, and I've searched all around. I think that this is right, but the label is not appearing on my panel. Anybody see what I am missing? Thanks!
ResultsPanel myPanel = new ResultsPanel(pnlResults); //pnlResults is an existing JPanel
myPanel.addLabel(pnlResults);
public class ResultsPanel extends JPanel {
JPanel myPanel;
public ResultsPanel(JPanel thisPanel) {
myPanel = thisPanel;
}
public void addLabel(JPanel myResults) {
JLabel myLabel = new JLabel("test", JLabel.LEFT);
myPanel.setLayout(new FlowLayout());
add(myLabel);
}
}
EDIT: In response to the immediate replies below, I agree that this seems to be total overkill. I went down this path because the following code also does not result in a JLabel being added to my JPanel:
JLabel myLabel = new JLabel("test");
pnlResults.add(myLabel);
I would much rather use this code, so feel free to comment on this if you think it is more likely to work (with some modifications, of course). Thanks again!
解决方案
This seems to be jumping through hoops just to do a basic thing; simply call
JLabel label = new JLabel("Test text");//initialize the label
//do some stuff with label here maybe...
panel.add(label);//now add it
There is no need to make a class extends JPanel, and contain a JPanel; if a class extends JPanel, to get the JPanel instance, simply use this (so addLabel would instead do this.setLayout(blah)). But of course there is no need to even subclass JPanel for something as simple as adding a JLabel
Overall, here's pretty much the simplest swing application:
JFrame frame = new JFrame("Basic Swing");//Make a frame
frame.setSize(300, 300);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Make it go away on close
JPanel panel = new JPanel();//Make a panel
frame.add(panel);//Add it to your frame
JLabel label = new JLabel("Hello StackOverflow!");//Make a label
panel.add(label);//Add it to the panel (which is on the frame)
frame.setVisible(true);//Show the frame