【发布时间】:2014-12-15 06:54:18
【问题描述】:
我想在 jscrollpane 中拥有一个没有布局管理器的固定大小的 jpanel(这也将没有布局管理器)。我不能使用任何布局管理器,因为我需要在用户单击的位置创建一个矩形/圆形(并允许拖放所有创建的元素)
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;
}
滚动条永远不会弹出。
【问题讨论】:
-
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
我无法使用布局管理器。我正在尝试编写一个与一些图形化 uml/er 建模器非常相似的工具,基本上用户可以在工作空间(jpanel)上创建对象,将对象连接到其他对象等......
-
这不是问题。实现拖放并将组件动态添加到您要使用的任何布局管理器。使用 null 布局,您可能会不工作。要绘制形状,请使用与布局无关的图形对象。
-
"我不能使用布局管理器" 任何用于布局容器的逻辑都可以在自定义布局 ..而且你已经证明没有一个你就无法让它工作。
标签: java swing jpanel jscrollpane absolutelayout