[英]Strange rendering issue with Java Swing libaray
Background I want to create a GUI application using the java swing library.背景我想使用java swing库创建一个 GUI 应用程序。 For layout I require it to be a GridLayout as the program outline requires this.
对于布局,我要求它是一个 GridLayout,因为程序大纲需要它。
Aim To render a panel with text inside it.旨在渲染一个面板,其中包含文本。
What I have tired我有什么累
Code代码
public class MainPanel extends JPanel {
public MainPanel(JFrame frame) {
setBounds(40,40,200,200);
setBackground(Color.BLUE);
JLabel label = new JLabel("Hello World", SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.PLAIN, 25));
label.setVisible(true);
add(label);
setLayout(new GridLayout(1, 1));
}
}
Conclusion As you can see, the panel does render (the blue square), however there is no text inside of it.结论如您所见,面板确实呈现(蓝色方块),但是其中没有文本。 I'm rather confused as code very similar to this has worked on aother project, and there is no obvious reason this shouldn't work.
我很困惑,因为与此非常相似的代码已经在另一个项目中使用过,并且没有明显的理由表明它不起作用。
Your code is essentially OK with the provisos I mentioned.您的代码基本上可以满足我提到的条件。 Proof: (obviously you can separate out your own class as a top level one later):
证明:(显然你可以分离出你自己的class作为后面的顶级):
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class F extends JFrame {
private void setGui() {
try {
setLocation(0, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new MainPanel());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
EventQueue.invokeAndWait(() -> {
F f = new F();
f.setGui();
f.setSize(200, 200);
f.setVisible(true);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MainPanel extends JPanel {
public MainPanel() {
setLayout(new GridLayout(1, 1));
setBounds(40,40,200,200);
setBackground(Color.BLUE);
JLabel label = new JLabel("Hello World", SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.PLAIN, 25));
add(label);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.