为什么 给jpanel加jscrollpane 后 滚动条 不能动
import java.awt.Color;
import java.awt.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.*;
public class test extends JFrame{
private JPanel pan=new JPanel();
JScrollPane scroll=new JScrollPane(pan);
private JButton btn=new JButton("test");
Container pane=getContentPane();
public test()
{
pane.setLayout( new BoxLayout( pane, BoxLayout.Y_AXIS ) );
pan.setSize(1000,700);
pan.setBackground(Color.yellow);
scroll.setViewportView(pan);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setSize(300,200);
pan.setLayout(null);
pan.add(btn);
btn.setLocation(20, 650);
btn.setSize(40,20);
pane.add(scroll);
setSize(800,600);
setVisible(true);
}
public static void main(String args[])
{
new test();
}
} 展开
这是修改后的程序,已经很好地解决了你的两个问题。相信你看了后,应该明白问题出在哪儿了,如果还不清楚,可以参考:
http://zhidao.baidu.com/question/88735050.html?fr=qrl&cid=197&index=1&fr2=query
和java的api文档。
import java.awt.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class test extends JFrame {
private JPanel pan = new JPanel();
JScrollPane scroll = new JScrollPane(pan);
private JButton btn = new JButton("test");
Container pane = getContentPane();
public test() {
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
// pan.setSize(1000, 700);
pan.setPreferredSize(new Dimension(1000, 700));
pan.setBackground(Color.yellow);
scroll.setViewportView(pan);
scroll
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setSize(300, 200);
pan.setLayout(null);
pan.add(btn);
btn.setLocation(20, 100);// btn.setLocation(20, 650);
btn.setSize(40, 20);
pane.add(scroll);
setSize(800, 600);
setVisible(true);
}
public static void main(String args[]) {
new test();
}
}
另外,再给个建议,写java程序的时候,一定要记得写窗口关闭部分,不然在程序多运行几次后,打开任务管理器,会发现有许多个javaw.exe进程。对系统不好。
参考资料: http://zhidao.baidu.com/question/88735050.html?fr=qrl&cid=197&index=1&fr2=query