Java swing,滚动条不适用于绝对布局 [英] Java swing, scrollbar does not working with absolute layout
问题描述
我想有一个固定大小的jpanel,而jscrollpane中也没有布局管理器(这也将没有布局管理器).我不能使用任何布局管理器,因为我需要在用户点击的位置创建一个矩形/圆形(并允许所有创建的润饰剂进行拖放)
I want to have a jpanel with fixed size without layout manager in jscrollpane (which will be also without layout manager). I cant use any layout manager because i need to create an rectangle/circle at a location where user clicks (and allow drag & drop for all the created emelents)
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;
}
滚动条将永远不会弹出.
Scrollbar will never pop up.
推荐答案
我不能使用任何布局管理器,因为我需要在用户点击的位置创建一个矩形/圆形(并允许所有创建的润饰剂进行拖放)
I cant use any layout manager because i need to create an rectangle/circle at a location where user clicks (and allow drag & drop for all the created emelents)
好吧,您不能使用JDK中的标准布局管理器,但是是的,您应该使用布局管理器,因为布局管理器不仅可以设置组件的位置.
Well, you can't use a standard layout manager from the JDK, but yes you SHOULD be using a layout manager because a layout manager does more than just set the location of a component.
滚动条将永远不会弹出.
Scrollbar will never pop up.
无法进行滚动,因为基于添加到面板的组件,面板没有合适的首选尺寸.
Your scrolling doesn't work because the panel doesn't have a proper preferred size based on the components added to the panel.
查看拖动版式,这是一个设计的版式管理器以此目的.它可以随机放置,但仍可以计算出首选大小,因此可以滚动.
Check out the Drag Layout which is a layout manager designed for this purpose. It allows random placement but it still calculates a preferred size so scrolling will work.
这篇关于Java swing,滚动条不适用于绝对布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!