[英]JPanel won't show up in JFrame(main class) - Beginner Java
I'm just starting out swing in Java... I have this problem about creating a separate JPanel class to be put in the main class (the one with JFrame), that the JPanel won't show up in the main class. 我刚刚开始使用Java ...我有一个问题就是创建一个单独的JPanel类放在主类(带有JFrame的那个)中,JPanel不会出现在主类中。 The program can run but only the frame would show up. 程序可以运行但只显示框架。 I was hoping that I would see the panel with the 'hallo' label but no. 我希望我能看到带有'hallo'标签的面板,但没有。
I know I've been looking for the other solutions in this site, but I didn't really get some of it. 我知道我一直在寻找这个网站上的其他解决方案,但我并没有真正得到它的一些。
This is my JPanel class: 这是我的JPanel类:
import javax.swing.*;
public class CreatePanel extends JPanel
{
private JPanel panel = new JPanel();
private JLabel narrate;
public void setNarrate(String label)
{
narrate = new JLabel(label);
panel.add(narrate);
panel.setVisible(true);
}
public JPanel getPanel()
{
return panel;
}
}
This is the main class with the JFrame: 这是JFrame的主类:
import javax.swing.*;
public class Maine extends JFrame
{
private static JFrame frame = new JFrame();
public static void main(String[] args)
{
new Maine();
CreatePanel panel1 = new CreatePanel();
panel1.setNarrate("Hallo");
panel1.getPanel();
frame.add(panel1);
}
public Maine()
{
frame.setTitle("Detective Game");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setIconImage(new ImageIcon("agent.png").getImage());
}
}
You're confusing inheritance and composition. 你的继承和构成令人困惑。 Your CreatePanel class extends JPanel. 您的CreatePanel类扩展了JPanel。 So it is a JPanel. 所以这是一个JPanel。 But you don't have any component inside this panel, because what you did is create another JPanel and add a label to this other JPanel. 但是你在这个面板中没有任何组件,因为你所做的是创建另一个JPanel并为另一个JPanel添加一个标签。
In short, your CreatePanel class should be: 简而言之,您的CreatePanel类应该是:
public class CreatePanel extends JPanel {
private JLabel narrate;
public CreatePanel(String label) {
narrate = new JLabel(label);
this.add(narrate);
}
}
That said, using a panel to only contain a label is useless. 也就是说,使用面板只包含标签是没用的。 You could add the label to the frame directly. 您可以直接将标签添加到框架中。
You are calling panel1.getPanel()
, but that doesn't do anything except take up memory. 你正在调用panel1.getPanel()
,但除了占用内存之外什么都不做。 Doing frame.add(panel1.getPanel())
, you are getting the panel and then adding it. 执行frame.add(panel1.getPanel())
,您将获得该面板,然后添加它。 In your code you are getting the panel but not assigning it to anything. 在您的代码中,您将获得面板,但不会将其分配给任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.