【发布时间】:2012-02-01 07:16:24
【问题描述】:
请看下面的代码块
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class test extends JFrame {
public test(){
this.setBounds(0,0,300,700);
JPanel pnltemp= new JPanel();
//pnltemp.setBounds(0,0,400,1000);
pnltemp.setPreferredSize(new Dimension(400,1000));
JScrollPane scrtemp= new JScrollPane();
scrtemp.getViewport().add(pnltemp);
this.getContentPane().add(scrtemp);
this.getContentPane().add(scrtemp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String args[]){
new test();
}
}
- 当我们通过注释“pnltemp.setBounds(0,0,400,1000);”运行上述代码时并将其替换为“pnltemp.setPreferredSize(new Dimension(400,1000));”窗口显示水平和垂直滚动条。 但是当我们通过注释“pnltemp.setPreferredSize(new Dimension(400,1000));”来运行相同的程序时并用“pnltemp.setBounds(0,0,400,1000)”替换它,窗口不显示水平和垂直滚动条。
为什么同一个程序通过改变 setBounds 和 setPreferredSize 方法会有不同的行为;因为这两种方法在行为上看起来相同。
或者是这样的,当我们使用 JScrollPane 来获取滚动条时,我们必须使用 setPreferredSize();我们要在 JScrollPane 中添加的组件的方法。
- 我的第二个问题是当我们将 pnltemp 添加到 scrtemp 时,即 JPanel 直接添加到 JScrollPane 然后当我们说时它不会给出错误的意思
scrtemp.add(pnltemp);
它没有给出任何错误,但它也没有在 scrtemp 中显示 pnltemp 和滚动条。 但是当我们输入 scrtemp.getViewPort.add(pnltemp);
它没有给出任何错误,但它还在 scrtemp 中显示 pnltemp 和滚动条。
我通过将背景颜色分配给 JPanel 和 JScrollPane 来检查这一点。
谁能解释一下?
谢谢!
【问题讨论】:
标签: java swing jpanel jscrollpane