我将帧分为三个部分,例如粉红色背景中的水平部分和黄色和蓝色背景中的垂直部分,如图像中使用GridBagConstraints,enter image description here
我使用以下代码执行此操作,
public Main()
{
JFrame maFrame = new JFrame("The main screen"); //creating main Jframe
maFrame.setSize(1000, 700);
Container container = maFrame.getContentPane();
container.setLayout(new GridBagLayout()); //setting layout of main frame
GridBagConstraints cns = new GridBagConstraints(); //creating constraint
JPanel headPanel = new JPanel(); //creating the header panel
cns.gridx = 0;
cns.gridy = 1;
cns.weightx = 0.3;
cns.weighty = 0.7;
cns.anchor = GridBagConstraints.FIRST_LINE_START;
cns.fill = GridBagConstraints.BOTH;
maFrame.setLocationRelativeTo(null); //centering frame
headPanel.setBackground(Color.YELLOW);
container.add(headPanel, cns);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
cns.gridx = 1;
cns.gridy = 1;
cns.weightx = 0.7;
cns.weighty = 0.7;
cns.anchor = GridBagConstraints.PAGE_START;
cns.fill = GridBagConstraints.BOTH;
container.add(panel, cns);
JPanel panel1 = new JPanel();
panel1.setBackground(Color.PINK);
cns.gridx = 0;
cns.gridy = 0;
cns.gridwidth = 2;
cns.weightx = 1.0;
cns.weighty = 0.3;
cns.anchor = GridBagConstraints.LAST_LINE_START;
cns.fill = GridBagConstraints.BOTH;
container.add(panel1, cns);
maFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
maFrame.pack();
maFrame.setVisible(true); //making the frame visible
}
我想将粉红色的背景部分分成3个部分,将黄色背景分成两部分。我试过这样做。但它不适合我。我不想使用splitpane来做到这一点。是否可以使用GridBagConstraints实现它?你能建议我这样做吗?提前谢谢。
答案 0 :(得分:1)
使用GridLayout
执行此操作的简单方法,将contentPane
分为两行,然后将底行分为两列。
import javax.swing.*;
import java.awt.*;
class JpanelSplit {
JFrame frame;
JPanel contentPane;
JPanel pinkPanel;
JPanel yellowPanel;
JPanel bluePanel;
JPanel twoPanelContainer;
public JpanelSplit() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel(new GridLayout(2,1));
pinkPanel = new JPanel();
pinkPanel.setBackground(Color.PINK);
yellowPanel = new JPanel();
yellowPanel.setBackground(Color.YELLOW);
bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
twoPanelContainer = new JPanel(new GridLayout(1,2));
twoPanelContainer.add(yellowPanel);
twoPanelContainer.add(bluePanel);
contentPane.add(pinkPanel);
contentPane.add(twoPanelContainer);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new JpanelSplit();
}
}