Java swing、scrollbar不能使用绝对布局
我想要一个在jscrollpane中没有布局管理器的固定大小的jpanel(也将没有布局管理器)。我不能使用任何布局管理器,因为我需要在用户单击的位置创建一个矩形/圆形(并允许对所有创建的eMelent进行拖放)
setLocationRelativeTo(null);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setName("dnd test");
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll = new JScrollPane(panel,v,h);
scroll.setLayout(null);
scroll.setPreferredSize(new Dimension(1000, 1000));
scroll.setBounds(0, 0, 1000, 1000);
panel = buildComponentOnAbsoluteLayout(new JPanel(),scroll,0,0,500,500);
panel.setBackground(Color.darkGray);
panel.setSize(350,350);
panel.setLayout(null);
buildComponentOnAbsoluteLayout(new JButton("button 1"),panel,10,10,120,30);
buildComponentOnAbsoluteLayout(new JButton("button 1"),panel,50,50,120,30);
add(scroll);
setVisible(true);
public static <T extends JComponent> T buildComponentOnAbsoluteLayout(T t,Container holder,int x, int y,int width, int heigth){
t.setBounds(x,y,width,heigth);
holder.add(t);
return t;
}
滚动条永远不会弹出
# 1 楼答案
嗯,你不能使用JDK的标准布局管理器,但是你应该使用布局管理器,因为布局管理器不仅仅是设置组件的位置
您的滚动不起作用,因为根据添加到面板的组件,面板没有合适的首选大小
查看Drag Layout这是一个为此设计的布局管理器。它允许随机放置,但它仍然会计算出一个首选大小,这样滚动就可以了