我想创建一个应用程序,其中我有一个没有默认布局的JPanel。我希望能够使用菜单中的选项更改布局。例如,如果我有一个控件将三个图像图标添加到JPanel,这些图标的大小和位置应由框架的当前布局管理器确定。 因此,如果我将3个图像图标添加到边框布局(在南,东和中心位置添加它们),则将布局切换为流布局应使它们按从右到左的顺序显示,而不调整大小。
我很困惑如何去做。有没有办法像这样在同一个JPanel中切换布局?
答案 0 :(得分:0)
要在每个菜单操作后动态更改布局,请使用其约束设置新布局并调用revalidate()方法。检查下面代码的actionPerformed()方法。
public class LayoutController extends JFrame implements ActionListener {
JMenuItem flowLayout;
JMenuItem borderLayout;
JMenuItem gridLayout;
JPanel panel;
JButton button1;
JButton button2;
JButton button3;
public LayoutController() {
setSize(600, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null); // no default layout
panel.setSize(600, 600);
flowLayout = new JMenuItem("Flow Layout");
flowLayout.addActionListener(this);
borderLayout = new JMenuItem("Border Layout");
borderLayout.addActionListener(this);
gridLayout = new JMenuItem("Grid Layout");
gridLayout.addActionListener(this);
// menu to change layout dynamically
JMenu fileMenu = new JMenu("Layout");
fileMenu.add(flowLayout);
fileMenu.add(borderLayout);
fileMenu.add(gridLayout);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Customize your components
button1 = new JButton("IMAGE1");
button2 = new JButton("IMAGE2");
button3 = new JButton("IMAGE3");
panel.add(button1);
panel.add(button2);
panel.add(button3);
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LayoutController().setVisible(true);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
//Customize your code here
if (e.getSource() == flowLayout) {
//flow layout with right alignment
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
} else if (e.getSource() == borderLayout) {
// border layout with constraints
BorderLayout layout = new BorderLayout();
layout.addLayoutComponent(button1, BorderLayout.SOUTH);
layout.addLayoutComponent(button2, BorderLayout.EAST);
layout.addLayoutComponent(button3, BorderLayout.CENTER);
panel.setLayout(layout);
} else if (e.getSource() == gridLayout) {
// grid layout with 2 rows and 2 columns
panel.setLayout(new GridLayout(2, 2));
}
panel.revalidate();
}
}