如何在框架的东边设置两个面板

时间:2013-11-19 13:02:02

标签: java swing layout jframe jpanel

像这样,

image

如何在框架的东边设置两个面板并保持面板一和二的固定尺寸?

如何设置帧的图像BG?

3 个答案:

答案 0 :(得分:2)

通过嵌套布局。在BoxLayoutEAST上添加BoarderLayout。请参阅 Andrew Thompson this question的回答。

答案 1 :(得分:1)

如果您不介意一些手动修补,可以使用SpringLayout手动控制布局。使用这种方法,我根据你的图片进行了一些模拟。看一看,看看它是否有用。如果您也使用注释掉的行(替换它上面的行),它应该保持大小相同

public class SO{
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel1 = new JPanel();
    panel1.setBackground(java.awt.Color.RED);

    JPanel panel2 = new JPanel();
    JButton but1 = new JButton("Button 1");
    JButton but2 = new JButton("Button 2");
    panel2.setBackground(java.awt.Color.BLUE);
    panel2.add(but1);
    panel2.add(but2);

    SpringLayout layout = new SpringLayout();
    frame.setLayout(layout);

    frame.add(panel1);
    layout.putConstraint(SpringLayout.EAST, panel1, -5, SpringLayout.EAST, frame.getContentPane());
    layout.putConstraint(SpringLayout.WEST, panel1, -200, SpringLayout.EAST, frame.getContentPane());
    layout.putConstraint(SpringLayout.NORTH, panel1, 5, SpringLayout.NORTH, frame.getContentPane());
    layout.putConstraint(SpringLayout.SOUTH, panel1, -5, SpringLayout.NORTH, panel2);
    //layout.putConstraint(SpringLayout.SOUTH, panel1, 200, SpringLayout.NORTH, frame.getContentPane()); swap this for the above one to keep the sizes the same

    frame.add(panel2);
    layout.putConstraint(SpringLayout.EAST, panel2, -5, SpringLayout.EAST, frame.getContentPane());
    layout.putConstraint(SpringLayout.WEST, panel2, -200, SpringLayout.EAST, frame.getContentPane());
    layout.putConstraint(SpringLayout.NORTH, panel2, -100, SpringLayout.SOUTH, frame.getContentPane());
    layout.putConstraint(SpringLayout.SOUTH, panel2, -5, SpringLayout.SOUTH, frame.getContentPane());

    frame.setSize(400, 350);
    frame.setVisible(true);
   }
}
祝你好运!

答案 2 :(得分:0)

你做的是:

  • 制作一个新面板(此示例名为outerPanel)
  • 将您想要的2个面板添加到此outerPanel
  • 然后将此外部面板添加到框架