如何在BoxLayout中设置JComponent的位置?

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

我想使用2 JPanel作为panelpanel_1。我想使用JLabel自动将图像添加到面板并将JButton添加到panel_1

如何根据按钮上方的图像调整按钮的大小?

public class Testing extends JFrame {

    public Testing() {
        this.setSize(590, 327);
        this.setTitle("JFrame");
        getContentPane().setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(118, 136, 321, 89);
        getContentPane().add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        JLabel lblImage = new JLabel("image for button1");
        panel.add(lblImage);

        JLabel lblImage_1 = new JLabel("image for button2");
        panel.add(lblImage_1);

        JLabel lblImage_2 = new JLabel("image for button3");
        panel.add(lblImage_2);

        JPanel panel_1 = new JPanel();
        panel_1.setBounds(118, 30, 321, 77);
        getContentPane().add(panel_1);
        panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS));

        JButton btnNewButton = new JButton("New button 1");
        panel_1.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("New button 2");
        panel_1.add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("New button 3");
        panel_1.add(btnNewButton_2);
    }

    public static void main(String[] args) throws Exception {
        Testing frame = new Testing();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}
java swing layout-manager jcomponent boxlayout
1个回答
3
投票

如果您的目标是使按钮位于图像上方,并且按钮的宽度随图像扩展,则:

  • 摆脱对空布局和.setBounds(...)的使用(这只是很好的一般建议)
  • 将带有图像的JLabel放入使用BorderLayout且JLabel位于BorderLayout.CENTER位置的JPanel中,>
  • 使用BorderLayout.PAGE_START位置,将JLabel上方的按钮放在同一JPanel中。
  • 然后将JPanel放在GUI中需要的任何位置,嵌套JPanel,每个JPanel使用各自的布局管理器。
  • BorderLayout将允许中心组件填充该位置,并将展开PAGE_START和PAGE_END位置以填充必要的宽度。如果顶部和底部组件较宽,则这也会扩大容器的宽度。

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