我想使用gridbaglayout
(包含6 JPanels
)+使用从右到左的方向创建可调整大小的框架。在添加第5个和第6个JPanel
预期对齐后,它的工作状态一直持续到JPanel
。
请指导我进行预期的调整。
预期输出
import java.awt.*;
import javax.swing.*;
public class FrameGUI {
public static void addComponentsToPane(Container pane){
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JPanel blackPanel,bluePanel,greenPanel,orangePanel,pinkPanel,redPanel;
pane.setLayout(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
c.fill=GridBagConstraints.BOTH;
pane.setPreferredSize(new Dimension(600,660));
//################################################## BLACK JPanel
blackPanel=new JPanel(new GridBagLayout());
c.weightx=0.8;
c.weighty=0.3;
c.fill=GridBagConstraints.BOTH;
c.gridwidth=2;
c.gridheight=1;
c.gridx=0;
c.gridy=0;
blackPanel.setBackground(Color.black);
pane.add(blackPanel, c);
//################################################## BLUE JPanel
bluePanel=new JPanel(new GridBagLayout());
c.fill=GridBagConstraints.BOTH;
c.weightx=0.8;
c.weighty=0.1;
c.gridheight=1;
c.gridwidth=2;
c.gridx=0;
c.gridy=1;
bluePanel.setBackground(Color.blue);
pane.add(bluePanel, c);
//################################################## GREEN JPanel
greenPanel=new JPanel(new GridBagLayout());
c.fill=GridBagConstraints.BOTH;
c.weightx=0.2;
c.weighty=0.4;
c.gridwidth=1;
c.gridheight=2;
c.gridx=2;
c.gridy=0;
greenPanel.setBackground(Color.green);
pane.add(greenPanel, c);
//################################################## ORANGE JPanel
orangePanel=new JPanel(new GridBagLayout());
c.fill=GridBagConstraints.BOTH;
c.weightx=1.0;
c.weighty=0.2;
c.gridheight=1;
c.gridwidth=3;
c.gridx=0;
c.gridy=2;
orangePanel.setBackground(Color.orange);
pane.add(orangePanel, c);
//################################################## PINK JPanel
pinkPanel=new JPanel(new GridBagLayout());
c.fill=GridBagConstraints.BOTH;
c.weightx=0.2;
c.weighty=0.4;
c.gridheight=1;
c.gridwidth=1;
c.gridx=0;
c.gridy=3;
pinkPanel.setBackground(Color.pink);
pane.add(pinkPanel, c);
//################################################## RED JPanel
redPanel=new JPanel(new GridBagLayout());
c.fill=GridBagConstraints.BOTH;
c.weightx=0.8;
c.weighty=0.4;
c.gridheight=1;
c.gridwidth=2;
c.gridx=1;
c.gridy=3;
redPanel.setBackground(Color.red);
pane.add(redPanel, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}