我想使用2个jpanel作为面板和panel_1。我想使用jLabel自动将图像添加到面板并将jbutton添加到panel_1。
如何根据按钮上方的图像调整按钮的大小?
public class Testing extends JFrame {
public static void main(String[] args) throws Exception {
Testing frame = new Testing();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
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);
}
}
如果您的目标是将按钮放置在图像下方,并且按钮的宽度随图像扩展,则:
.setBounds(...)
的使用(这只是很好的一般建议)BorderLayout将允许中心组件填充该位置,并将展开PAGE_START和PAGE_END位置以填充必要的宽度。如果顶部和底部组件较宽,则这也会扩大容器的宽度。