日期:2014-05-20  浏览次数:20690 次

JPanel的问题,求教!
package test;

import java.awt.Color;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ClickJButtonHideJPanel {
public static void main(String[]args){
JFrame jf = new JFrame("试试");
jf.setBounds(300, 300, 300, 300) ;
JPanel jp[] = new JPanel[2] ;
jp[0] = new JPanel() ;
jp[1] = new JPanel() ;
jp[0].setBounds(0, 0, 100, 100) ;
jp[1].setBounds(150, 150, 150, 150) ;//这是个怪地方!!!
jp[0].setBackground(Color.yellow) ;
jp[1].setBackground(Color.red) ;

JLabel jl[] = new JLabel[2] ;
jl[0] = new JLabel("000") ;
jl[0].setBackground(Color.BLUE) ;
jl[1] = new JLabel("111") ;
jl[0].setBackground(Color.gray) ;
jp[0].add(jl[0]) ;
jp[1].add(jl[1]) ;
jf.add(jp[0]) ;
jf.add(jp[1]) ;
jf.setVisible(true) ;
System.out.println("输入:");
Scanner sa = new Scanner(System.in);
int i = sa.nextInt();
if( 0 == i )
{
jp[0].setVisible(false) ;
}
else
{
jp[1].setVisible(false) ;
}
}
}


初学者问题:

1、为什么jp[0]和jp[1]都设置了坐标,jp[0]按照坐标规定的范围出现,而jp[1]覆盖了整个窗口范围(我在控制台输入0,,全是红色,所以我认为应该是jp[1]覆盖整个窗口,只不过其中一部分刚才被jp[0]覆盖,但我不知道为什么!!!)

2、朋友能否多添几笔,在我的代码基础上写一段代码(或者自己写),就是增添几个JButton,使得按jb[0],就隐藏jp[0],按一下jb[1],就隐藏jp[1]

初学者求教,谢谢!!!


------解决方案--------------------
final CardLayout cards = new CardLayout();
final JPanel container = new JPanel(cards);
container.add(c1, "first");
container.add(c2, "second");

button1.addActionListener(new ActionListener(){ 
    @Override public void actionPerformed(ActionEvent e){ 
        cards.show(container, "first");
    }
});
------解决方案--------------------
引用:
final CardLayout cards = new CardLayout();
final JPanel container = new JPanel(cards);
container.add(c1, "first");
container.add(c2, "second");

button1.addActionListener(new ActionL……

请问C1和C2是什么意思

引用:
引用:1 JFrame 默认使用BorderLayout布局管理器,add方法默认加到center,后添加的覆盖前面添加的。

2 切换显示使用CardLayout。
1、那为什么jp[0]还是会显示,而且在正确的坐标位置?
2、为什么jp[2]是覆盖整个窗口?你说center,也不应该全部覆盖啊!
3、我自己试了下CardLayo……

1不知
2如果你不加BorderLayout.North()之类的,确实是center是覆盖整个窗口的,不信将jp[0].add(jl[0]) ;去掉
3.楼上的解释是正确的,将所有的有颜色的panal都加到一个panel中,再将那个panel设置为CardLayout,
CardLayout作用如下
引用
A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.