java—如何在jpanel类中使用gridbagconstraints

wlsrxk51  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(430)

我试图在扩展jpanel的类中使用gridbagconstraints,但在将代码放在如下位置之后:

import java.awt.Insets;
    import java.awt.Toolkit;

    import javax.swing.JLabel;
    import javax.swing.JPanel;

    public class RightPanel extends JPanel {

private static final long serialVersionUID = 2L;

JLabel start;
JLabel first;

GridBagConstraints c;

public RightPanel() {

    setVisible(true);

    c = new GridBagConstraints();
    c.insets = new Insets(10 ,10, 10, 10);

    start = new JLabel("Start");
    start.setFont(new Font("comic sans ms", Font.PLAIN, 20));
    start.setForeground (new Color(111,0,0));

    c.gridx = 0;
    c.gridy = 5;

    add(start, c);

    first = new JLabel("About");
    first.setFont(new Font("comic sans ms", Font.PLAIN, 20));
    first.setForeground (new Color(111,0,0));

    c.gridx = 0;
    c.gridy = 5;
    add(first ,c);
}

public void paint(Graphics g) {
    Image a = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\rightside.PNG");
    g.drawImage(a, 0, 0, getSize().width, getSize().height, this);
    super.paint(g);
}

    }

现在的问题是如何在jpanel构造函数中添加声明代码,即rightpanel rp=newrightpanel(newgridbaglayout());,但是新的gridbaglayout()不起作用,请帮忙

cl25kdpy

cl25kdpy1#

RightPanel rp = new RightPanel(new GridBagLayout());

上面的代码将不起作用,因为构造函数中没有任何参数。。

public class RightPanel extends JPanel

//codes...

public RightPanel() //You don't have any parameter in your constructor

如果你试图设置你的类的布局,请使用

setLayout(new GridBagLayout())

相关问题