我一直在尝试学习如何在Java中使用布局管理,我有以下代码尝试添加类“ StartButton”,startbutton只是扩展JButton的类

当我运行代码时,我的JFrame已正确加载并创建了JPanel,我还向printItems()添加了打印内容,以确保函数被调用。

这是我的JPannel代码;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JPanel;

public class menuPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    private static final Color BG_COLOR = new Color(0xfaf8ef);


    private startButton startbutton;

    public menuPanel(){
        this.setOpaque(false);
        this.setPreferredSize(new Dimension(300, 400));
        this.setBackground(new Color(107, 106, 104));
        this.setVisible(true);
        setLayout(new GridBagLayout());

        startbutton = new startButton();

        layoutItems();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(BG_COLOR);
        g.fillRect(0, 0, this.getSize().width, this.getSize().height);
    }


    public void layoutItems(){
        GridBagConstraints c = new GridBagConstraints();
        System.out.println("lol");
        c.weightx = 0.25;
        c.weighty = 0.175;
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 6;
        this.add(startbutton, c);
    }
}

最佳答案

覆盖paint而不是paintComponent会导致为所有Swing组件绘制组件的方式发生不可预测的行为。

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    ...
}


实际上,覆盖paintComponent是不必要的,因为setBackground(BG_COLOR)将给出等效的结果

10-06 06:01