我目前正在使用 GUI 邁出第一步,現在我只是根據我的藝術作品嘗試JFrame用兩個容器制作一個:JPanel

我選擇了,GridBagLayout因為我希望它以后可以調整大小但保持給定的比例,但我很難理解所有這些是如何作業的。
我當前的代碼如下所示:
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame {
private JPanel contentPane;
public JPanel getContentPane() {
return contentPane;
}
public void setContentPane(JPanel contentPane) {
this.contentPane = contentPane;
}
public MyFrame (){
contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 3;
JPanel blue = new JPanel();
blue.setBackground(Color.BLUE);
contentPane.add(blue, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 3;
JPanel gruen = new JPanel();
gruen.setBackground(Color.green);
contentPane.add(gruen, gbc);
this.setPreferredSize(new Dimension(630, 650));
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setContentPane(contentPane);
}
public static void main(String[] args) {
new MyFrame();
}
}
這給了我這個空視窗:

如果有人能告訴我我做錯了什么,那就太好了。
uj5u.com熱心網友回復:
1.首先,你需要洗掉這個:
public JPanel getContentPane() {
return contentPane;
}
public void setContentPane(JPanel contentPane) {
this.contentPane = contentPane;
}
因為您基本上覆寫了 的基本邏輯JFrame,因此您可能(并且可能會)破壞某些東西。
2. 第二件事是,將組件放入帶有約束的網格單元格不會自動將它們拉伸到整個區域。如果要參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467669.html
