Java Swing:将JLabel添加到JPanel [英] Java Swing: Adding a JLabel to a JPanel

查看:590
本文介绍了Java Swing:将JLabel添加到JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想将JLabel添加到现有的JPanel中。这看起来很简单,我四处寻找。我认为这是对的,但标签没有出现在我的面板上。有谁看到我错过了什么?谢谢!

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

}

编辑:回应立即回复下面,我同意这似乎是完全矫枉过正。我走了这条路,因为以下代码也没有导致JLabel被添加到我的JPanel:

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

没有必要让一个类扩展JPanel,并包含一个JPanel;如果一个类扩展了JPanel,要获取JPanel实例,只需使用它(因此addLabel会改为执行this.setLayout(blah))。但是当然没有必要甚至将JPanel子类化为添加JLabel这样简单的东西

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

总的来说,这里几乎是最简单的swing应用程序:

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

这篇关于Java Swing:将JLabel添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆