我想将 4 个 JPanel 添加到我的 JApplet 中,并为它们中的每一个指定不同的颜色。但是没有显示任何颜色——我的意思是我看不到输出。完全没有颜色。以下代码在 init()
方法中。
this.setSize(1400, 780);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setLayout(null) ;
setLayout(null) ;
Panel1 = new JPanel() ;
Panel2 = new JPanel () ;
Panel3 = new JPanel() ;
Panel4 = new JPanel() ;
Label1 = new JLabel ("Label1") ;
Label2 = new JLabel ("Label2") ;
Label3 = new JLabel ("Label3") ;
Label4 = new JLabel ("Label4") ;
Panel1.add(Label1) ;
Panel2.add(Label2) ;
Panel3.add(Label3) ;
Panel4.add(Label4) ;
// Panel 1 "About Me"
Panel1.setSize(140,390) ;
Panel1.setLocation(0,0) ;
Panel1.setBackground(Color.red) ;
Panel1.setVisible(true) ;
this.add(Panel1) ;
// Panel 2 "MyHoppies"
Panel2.setSize(140,390) ;
Panel2.setLocation(0,700) ;
Panel2.setBackground(Color.yellow) ;
this.add(Panel2) ;
// Panel 3 "Photo Gallery"
Panel3.setSize(140,390) ;
Panel3.setLocation(390,0) ;
Panel3.setBackground(Color.black) ;
this.add(Panel3) ;
// Panel 4 "Happey face"
Panel4.setSize(140,390) ;
Panel4.setLocation(390,700) ;
Panel4.setBackground(Color.pink) ;
this.add(Panel4) ;
最佳答案
this.setVisible(true)
必须是 GUI 构造函数中的最后一行代码使用 Using Java Naming Conventions那么
Panel1
应该是panel1
e.i.不要扩展
JFrame
或JApplet
,使用与Panel1
相同的方式将其创建为局部变量不要使用
NullLayout
,而是使用适当的LayoutManager
,在这种情况下可能是GridLayout
,否则JFrames
内容无法使用JFrame
调整大小
代码
import java.awt.*;
import javax.swing.*;
public class ColorongPanels {
private JFrame frame = new JFrame("ColorongPanels");
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JPanel panel3 = new JPanel();
private JPanel panel4 = new JPanel();
private JLabel label1 = new JLabel("Label1");
private JLabel label2 = new JLabel("Label2");
private JLabel label3 = new JLabel("Label3");
private JLabel label4 = new JLabel("Label4");
public ColorongPanels() {
frame.setLayout(new GridLayout(2, 2, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1.setBackground(Color.red);
panel1.setLayout(new BorderLayout());
panel1.add(label1, BorderLayout.CENTER);
panel2.setBackground(Color.yellow);
panel2.setLayout(new BorderLayout());
panel2.add(label2, BorderLayout.CENTER);
panel3.setBackground(Color.black);
panel3.setLayout(new BorderLayout());
panel3.add(label3, BorderLayout.CENTER);
panel4.setBackground(Color.pink);
panel4.setLayout(new BorderLayout());
panel4.add(label4, BorderLayout.CENTER);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ColorongPanels();
}
});
}
}
关于java - 使用空布局将 JPanel 添加到 JApplet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10737054/