简体   繁体   English

将JLabel添加到JPanel,并将JPanel添加到JFrame

[英]Adding a JLabel to a JPanel, and a JPanel to a JFrame

New to Java Here. Java的新功能。

I looked on the Internet and I used examples I found. 我浏览了Internet,并使用了发现的示例。 But they did not work and I can't find out why. 但是他们没有用,我找不到原因。 I also made searches on the oracle website and on stackoverflow. 我也在oracle网站和stackoverflow上进行了搜索。

I get these errors I can't resolve. 我收到了我无法解决的错误。

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


 public class HelloWorld {

  public static void main(String[] args) {

   JLabel label = new JLabel("This is a label");

   JPanel panel = new JPanel();

   JFrame frame = new JFrame("Window Title");
   frame.setSize(800, 500);
   frame.setResizable(true);
   frame.setLocationRelativeTo(null);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   frame.add(panel);    
   panel.add(label);

   frame.setVisible(true); 
  }

}

Here are the errrors: 这是错误:

The project was not built since its build path is incomplete. Cannot find the class file for javax.swing.JComponent. Fix the build path then try building this project
The type javax.swing.JComponent cannot be resolved. It is indirectly referenced from required .class files

They appear at these lines: 它们出现在以下行:

frame.add(panel);    
panel.add(label);

I can't add the label to the panel, and the panel to the frame. 我不能将标签添加到面板上,也不能将面板添加到框架上。

Your problem is not with your code, but with your project setup, somehow. 您的问题不在于代码,而在于项目设置。

I just ran your code and it works fine 我刚运行了您的代码,效果很好

Make sure you've got something like this in your package explorer for the project. 确保项目的程序包浏览器中有类似的内容。

在此处输入图片说明

EDIT: I assumed you were using an IDE of some sort, but I suppose its possible you're not. 编辑:我假设您正在使用某种类型的IDE,但我想您可能没有。 Make sure you have Java installed, and that you have the JDK installed. 确保已安装Java,并且已安装JDK。

Can you execute a Hello World? 您可以执行Hello World吗? If not, what error messages do you get? 如果没有,您会得到什么错误消息?

Probably the easiest solution will be for you to reinstall your IDE (I'm assuming its Eclipse because of probability). 可能最简单的解决方案是重新安装IDE(出于可能,我假设它是Eclipse)。 Get eclipse here. 在这里蚀。

If the problem persists after that, try reinstalling Java (make sure you get the JDK). 如果在此之后问题仍然存在,请尝试重新安装Java(确保获得JDK)。 Get it here. 在这里获取。 It it offers to uninstall older versions of Java, let it. 它提供了卸载旧版本的Java的功能。 You don't need 3 versions of Java cluttering up the system. 您不需要使系统混乱的3个Java版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM