下面这段代码直接在JFrame上add一个button,这样的话button是加在JFrame的哪个层次上的?为什么这样加的话两个按钮是重叠在一起的,如图所示。
[code="java"]
import javax.swing.*;
public class ButtonTest extends JFrame{
private JButton button1 = new JButton("确定");
private JButton button2 = new JButton("取消");
public ButtonTest(){
setSize(500,500);
add(button1);
add(button2);
}
public static void main(String[] args) {
ButtonTest f = new ButtonTest();
f.setVisible(true);
}
}
[/code]
而如果创建一个JPane对象panel1,将contentPane set为panel1,在panel1上添加就得到我想要的效果了,如图所示。
[code="java"]
import javax.swing.*;
public class ButtonTest extends JFrame{
private JButton button1 = new JButton("确定");
private JButton button2 = new JButton("取消");
private JPanel panel1 = new JPanel();
public ButtonTest(){
setSize(500,500);
setContentPane(panel1);
panel1.add(button1);
panel1.add(button2);
}
public static void main(String[] args) {
ButtonTest f = new ButtonTest();
f.setVisible(true);
}
}
请问这两种方式有什么区别?
相关分类