Adding jlabel to a jframe using components(使用组件将 jlabel 添加到 jframe)
问题描述
我有两节课,
我的主类创建了一个框架,我希望另一个类向它添加内容.一点阅读 arroudn 告诉我我应该使用组件来执行此操作,但是当我运行我的代码时,框架是空的.
My main class creates a frame and I want another class to add content to it. A bit of reading arroudn told me I should use components to do this however when I run my code the frame is empty.
public static void main(String[] args)
{
// create frame
JFrame frame = new JFrame();
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
// set frame attributes
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("My Frame");
frame.setVisible(true);
Component1 Com = new Component1();
Component add = frame.add(Com);
}
我的组件类创建一个 JLabel
My Component class creates a JLabel
public class Component1 extends JComponent {
public void paintComponent()
{
JLabel label = new JLabel("<html>Some Text</html>");
}
}
我没有收到任何编译错误,但是我的 JFrame 中没有收到任何文本.
I don't get any compile errors, however I dont get any text in my JFrame.
谁能解释我做错了什么?
Can anyone explain what I'm doing wrong?
克里斯
推荐答案
您需要添加 JLabel.最好扩展 JPanel 而不是 JComponent 因为它有一个默认的 布局管理器 并且将显示任何添加的组件,而无需设置组件大小.paintComponent 用于自定义绘画顺便说一句.
You need to add the JLabel. Also better to extend JPanel instead of JComponent as it has a default layout manager and will make any added components appear without the need to set component sizes. paintComponent is used for custom painting BTW.
public class Component1 extends JPanel {
Component1() {
JLabel label = new JLabel("<html>Some Text</html>");
add(label);
}
}
这篇关于使用组件将 jlabel 添加到 jframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用组件将 jlabel 添加到 jframe
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
