使用null布局将JPanel添加到JApplet

时间:2012-05-24 11:57:46

标签: java swing

我想将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) ; 

3 个答案:

答案 0 :(得分:6)

  • this.setVisible(true)必须是GUI构造函数中的最后一行代码

  • 正确使用Using Java Naming Conventions,然后Panel1应为panel1 e.i。

  • 不扩展JFrameJApplet,使用与Panel1相同的方式将其创建为本地变量

  • 请勿使用NullLayout,请使用正确的LayoutManager,在这种情况下可能使用GridLayout,否则JFrames内容无法使用{{1 }}

enter image description here

JFrame

答案 1 :(得分:3)

你应该这样做:
panelx.setOpaque(true)它应该有效

答案 2 :(得分:2)

首先:你需要JPanel.setOpaque(true)面板才能看到背景颜色。

第二:背景颜色属性对不同平台有不同的影响。例如:如果设置JButton的背景,您将看到Win7中的按钮颜色,但WinXP中没有颜色(不确定,它是如何在其他操作系统下)。这至少是我的经历......