Java Swing: add jlabel to JPanel

I just want to add jlabel to the existing JPanel It looks simple. I searched everywhere I think this is right, but the label doesn't appear on my panel Who saw what I missed? thank you!

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

}

Editor: in response to the instant reply below, I agree that this seems to be a complete overkill I followed this path because the following code did not cause jlabel to be added to my JPanel:

JLabel myLabel = new JLabel("test"); 
pnlResults.add(myLabel);

I'd rather use this code, so if you think it's more likely to work (with some modifications, of course), feel free to comment Thanks again!

Solution

This seems to be skipping basketball in order 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 for a class to extend JPanel and include a JPanel; If a class extends JPanel, to get the JPanel instance, just use it (so addlabel will execute this. Setlayout (blah)) instead) However, of course, there is no need to subclass JPanel into something as simple as adding jlabel

In general, this is 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>