关于设置jpanel为null后所有组件都不显示的问题

《问》在Java的GUI编程中,对于没有使用布局的容器(即布局为null的)其中的组件必须通过setSize设置其尺寸,setLocation设置其位置,当然也可以用setBounds同时进行设置。在你的代码中由于没有通过这些方法进行设置,导致一些组件的尺寸为0 X 0,自然是无法被看见的。

《答》我的代码里,有5句 setBounds,已经设置好了那几个组件了,那为何还是不行呢

《问》你对5个JPanel setBounds 但是没有对JLabel setBounds,真正的内容都在JLabel上不是么?
 
《答》对一个容器设置尺寸并不会导致其内容自动填充该组件(除非你用了布局管理器)

《问》嗯,根据你所说的,我给每个想要显示得组件都用了setBounds,分别是name,image,l[i],p[i]这些我都设置了,但依旧还是空白一片的

《答》设置偏移量的时候太大了,每个组件的位置是相对于其所在容器的,你的p0相对于整个JFrame已经偏移了一定的值,p0里面的组件又相对于p0偏移了一定的值,超出你的显示范围了。

import java.awt.Container;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AutoCandy extends JFrame implements ActionListener
{
JPanel cont,jpan,jpan1;
JButton jb1,jb2,jb3,jb4;
JButton candy,chips,chewing,cookie;
TextField tf1;
public AutoCandy()
{
super("Candy");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cont=new JPanel(null);
jpan = new JPanel(null);
jpan1 = new JPanel(null);
cont.add(jpan);
add(cont);
jb1 = new JButton("购买糖果");
jb2 = new JButton("查看存货");
jb3 = new JButton("查看销量");
jb4 = new JButton("查看利润");
candy=new JButton("糖果");
chips=new JButton("薯片");
chewing=new JButton("口香糖");
cookie=new JButton("小甜饼");
jt1=new TextField("");
jb1.setBounds(200,20,100,80);
jb2.setBounds(200,140,100,80);
jb3.setBounds(200,260,100,80);
jb4.setBounds(200,380,100,80);
candy.setBounds(200,20,100,80);
chips.setBounds(200,140,100,80);
chewing.setBounds(200,260,100,80);
cookie.setBounds(200,380,100,80);
//jt1.setBounds(100,100,200,50);
jpan.add(jb1);
jpan.add(jb2);
jpan.add(jb3);
jpan.add(jb4);
jpan1.add(candy);
jpan1.add(chips);
jpan1.add(chewing);
jpan1.add(cookie);
//jpan1.add(jt1);
jpan.setBackground(Color.blue);
jpan1.setBackground(Color.red);
jb1.addActionListener(this);
cont.setBounds(0,0,500,500);
jpan.setBounds(0,0,500,500);
jpan1.setBounds(0,0,500,500);
setBounds(100,100,500,500);
setContentPane(cont);
setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==jb1)
{
cont.remove(jpan);
cont.add(jpan1);
cont.revalidate();
cont.repaint();
}
}

public static void main(String args[])
{
AutoCandy candymachine=new AutoCandy();
}
}

 
posted @ 2014-03-23 16:06  圣婴  阅读(1921)  评论(0编辑  收藏  举报