出于某种原因,即使我已经在代码中实现了验证方法,并将 JPanel 添加到了 JFrame 中。我还试图让我的 JLabel 具有 Comic Sans 字体,并使其位于屏幕中央。为什么我的 JLabel 没有显示在我的 JPane 上
package math_program;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Canvas
{
Images obj = new Images();
public void paintFrame()
{
//Instantiation of objects
Random gen = new Random();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//Text
JLabel problem = new JLabel();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //Make frame actually closeable
frame.setTitle("Math Owl: Alpha V:0.1 (coded by John)");
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.add(panel); //Add JPanel to JFrame
panel.setVisible(true);
panel.setLayout(null);
panel.setBackground(Color.WHITE); //To see if text is even appearing
//Adding Components
problem.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
problem.setLocation(400,250);
problem.setText(gen.nextInt(11) + " + " + gen.nextInt(11));
panel.add(problem);
panel.validate();
}
}
最佳答案
正如copeg所说,使用合适的布局管理器。即使是默认的布局管理器(流布局)也可以使用。只需删除 panel.setLayout(null);
,您的 JLabel 就会显示出来。
此外,当我尝试您的代码片段时,Images obj = new Images();
也出现问题,我假设您已经在包中以某种方式定义了 Images 类。
`
关于java - JLabel 未显示在 JPanel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30400983/