如何在BoxLayout中将位置设置为JComponent



我想使用2个JPanel作为panelpanel_1。我想使用JLabel自动将图像添加到面板并且还将CCD_ 5添加到CCD_。

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

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);
}
}

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

  • 取消使用null布局和.setBounds(...)(这只是一个很好的一般建议(
  • 将带有图像的JLabel放入使用BorderLayout的JPanel中,JLabel位于BorderLayout.CENTER位置
  • 使用BorderLayout.PAGE_START位置将JLabel上方的按钮放在同一JPanel中
  • 然后将JPanel放在GUI中任何需要的地方,嵌套JPanel,每个JPanel都使用自己的布局管理器

BorderLayout将允许中心组件填充该位置,并将展开PAGE_START和PAGE_END位置以填充所需的宽度。如果顶部和底部组件较宽,则这也将扩大容器的宽度。

最新更新