Java SWING GUI - 根据滚动条对齐 JScrollPane 的内部

问题描述 投票:0回答:1

图形界面:

这个JScrollPane是这样定义的:(我们不关心右边的黄色平面,只关心左边的) 边框 [BorderLayout]

-JPlane panelLeft(blue)[BorderLayout]

--JScrollPane滚动(绿色)

---JPLane panelLeftChild(绿色) [FlowLayout]

----JPlane vbd(洋红色) [BoxLayout]

public MyFrame(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(700,500);
        this.setLayout((new BorderLayout(10,10)));


        JPanel panelLeft = new JPanel(new BorderLayout());
        JPanel panelLeftChild = new JPanel(new FlowLayout());
        JPanel panelRight = new JPanel(new BorderLayout());
        //
        panelLeft.setBackground(Color.blue);
        panelLeftChild.setBackground(Color.green);
        panelRight.setBackground(Color.yellow);
        //
        panelLeft.setPreferredSize(new Dimension(200,100));
        panelLeftChild.setPreferredSize(new Dimension(200,2000));
        panelRight.setPreferredSize(new Dimension(200,500));
        //
        JScrollPane scroll = new JScrollPane(panelLeftChild, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setPreferredSize(new Dimension(200,400));
        //
        panelLeftChild.add(new vbd(12312415));
        panelLeftChild.add(new vbd(567890));
        panelLeftChild.add(new vbd(94623745));
        panelLeftChild.add(new vbd(451654));
        panelLeftChild.add(new vbd(213121));
        //
        this.add(panelLeft, BorderLayout.WEST);
        this.add(panelRight, BorderLayout.EAST);
        panelLeft.add(scroll, BorderLayout.NORTH);
        //
        this.setVisible(true);
    }

我希望根据滚动条对齐组件,因此它看起来不会“偏离中心”,而且滚动条确实进入组件中一点点,使其可能更难与之交互。

我尝试了与此类似的代码,目的是将每个组件向左偏移,使其看起来更靠滚动条居中:

JButton button = new JButton();
JSlider slider = new JSlider();
JTextField text = new JTextField();
JComboBox combo = new JComboBox();

button.setAlignmentX(0.40f);
slider.setAlignmentX(0.40f);
text.setAlignmentX(0.40f);
combo.setAlignmentX(0.40f);

但是实际上只有按钮会轻微偏移: Button offset picture

我还尝试设置滑块的首选大小,但这会重塑整个盒子的形状,这是不希望的。 (只需将此添加到上面的代码中)

instanceSlider.setPreferredSize(new Dimension(150,10))

设置尺寸图片:

java swing user-interface
1个回答
0
投票
  1. 不要使用 setPreferredSize()。每个组件都有责任确定自己的首选尺寸。

  2. 组合框的大小将被允许增长以填充可用的水平空间。将所有项目添加到组合框后,您可以使用:

    comboBox.setMaximumSize( comboBox.getPreferredSize() );
    来限制增长。

  3. button.setAlignmentX(0.40f); - 如果您希望组件居中,为什么要使用“0.4f”?使用“0.5f”。您需要为所有组件设置对齐方式以确保它们居中。

© www.soinside.com 2019 - 2024. All rights reserved.