我需要Java帮助,我不能在一个具有不同和首选大小的帧中插入2 JPanel
,这是代码:
public class canvas extends JFrame {
public final String TITLE = "test"; /* Game's title */
public static int wWIDTH = 800; /* WIDTH of the window's games */
public static int wHEIGHT = 600; /* HEIGHT of the window's game */
/* => GAME ENGINEERING ATTRIBUTES <= */
private Dimension WINDOW_SIZE;
private Container c;
private rightpane rightpane;
private leftpane leftpane;
public canvas() {
Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
WINDOW_SIZE = new Dimension(wWIDTH, wHEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle(TITLE);
this.setUndecorated(false);
this.setSize(WINDOW_SIZE);
this.setResizable(false);
this.setLocation(((SCREEN_SIZE.width / 2) - (wWIDTH / 2)),
((SCREEN_SIZE.height / 2) - (wHEIGHT / 2)));
leftpane = new leftpane();
rightpane = new rightpane();
//leftpane.setPreferredSize(leftpane_dim);
this.add(rightpane,BorderLayout.EAST);
this.add(leftpane,BorderLayout.WEST);
this.setVisible(true);
}
和rightpane
以及leftpane
类:
public class rightpane extends JPanel {
public JLabel lb;
public rightpane() {
this.setBackground(Color.YELLOW);
lb = new JLabel();
lb.setText("right paneeeeeeeee");
this.add(lb);
}
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
}
public class leftpane extends JPanel {
public JLabel lb;
public leftpane() {
this.setBackground(Color.BLACK);
lb = new JLabel();
lb.setText("left pane");
this.add(lb);
}
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
}
这是结果:
我尝试了GridBagLayout
:
GridBagLayout gl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
this.setLayout(gl);
c.ipadx = 200;
c.gridwidth = 2;
c.gridx = c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.gridheight = 3;
gl.setConstraints(leftpane, c);
this.add(new leftpane());
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 3;
c.anchor = GridBagConstraints.EAST;
gl.setConstraints(rightpane, c);
this.add(new rightpane());
在网络中找到的其他解决方案但仍无效。任何人都可以帮助我吗?
答案 0 :(得分:0)
您的GridBagLayout中存在一些问题。这是固定版本
GridBagLayout gl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
this.setLayout(gl);
c.fill = GridBagConstraints.BOTH; // <== need to set fill
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.weightx = 1; // <== need to set weight
c.weighty = 1; // <== need to set weight
// gl.setConstraints(leftpane, c); // <== constraints get overridden by your add() call...
this.add(new leftpane(), c); // pass constraints in here
c.gridx = 1;
c.weightx = 3; <== need to set weight, note different value, space shared in ratio 1:3
c.anchor = GridBagConstraints.EAST; // pass constraints in here
照片