java - 在 JPanel 下添加 JLabel 不起作用(JAVA)
问题描述
我正在设计一个长的注册页面作为对一些 java 项目的测试,并且在尝试将 JLabel 附加到现有面板下时,文本没有显示。
这是代码:
//Setting Panel Color
int r1 = 172;
int g1 = 50;
int b1 = 50;
Color myFgColor = new Color(r1,g1,b1);
JPanel panel = new JPanel();
panel.setBounds(750,60,375,420);
panel.setBackground(myFgColor);
//Login and Sign Up Text
JLabel label = new JLabel("LOGIN");
label.setFont(new Font("Serif", Font.PLAIN, 14));
label.setForeground(Color.white);
panel.add(label);
gui.getContentPane().add(panel);
解决方案
这是你想要看到的吗?
我没有改变任何东西,我只是创建了一个新的 JFrame 并放置了你的组件......我看到的区别是 JFrame 创建了 contentPane,而你没有:
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1200, 575);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//Setting Panel Color
Color myFgColor = new Color(172,50,50);
JPanel panel = new JPanel();
panel.setBounds(750,60,375,420);
panel.setBackground(myFgColor);
//Login and Sign Up Text
JLabel label = new JLabel("LOGIN");
label.setFont(new Font("Serif", Font.PLAIN, 14));
label.setForeground(Color.white);
panel.add(label);
getContentPane().add(panel);
//Setting Background Color
Color myBgColor = new Color(30,30,30);
getContentPane().setBackground(myBgColor);
//Centering Window
setLocationRelativeTo(null);
}
我建议你使用 WindowBuilder 来创建框架,它是一个可视化设计器,它让它变得非常简单