Java图形AWT

问题描述 投票:0回答:1

运行以下代码时,我看不到红色的背景色。它显示默认值。我需要在这些行中添加任何内容吗?

enter code here
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class gfix extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.setColor(Color.red);
       g.fillRect(80, 100, 150, 75);
    }
    public static void main(String[] args){
       gfix gg=new gfix();
       JFrame frame = new JFrame("RISK");
       frame.setSize(800, 600);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       JPanel panel = new JPanel();
       panel.setLayout(null);
       frame.add(panel);
       JButton button = new JButton("test");
       button.setBounds(100, 100, 150, 150);
       panel.add(button);
       frame.setVisible(true);
    }
}
java swing awt
1个回答
0
投票

您正在覆盖painGraphics()类中的gfix,因此将gfix类对象添加到框架中,而不是Java提供的JPanel类对象。

       gfix gg=new gfix();
       JFrame frame = new JFrame("RISK");
       frame.setSize(800, 600);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //JPanel panel = new JPanel();      Not needed
       //panel.setLayout(null);
       frame.add(gg);
       JButton button = new JButton("test");
       button.setBounds(100, 100, 150, 150);
       gg.add(button);
       frame.setVisible(true);
© www.soinside.com 2019 - 2024. All rights reserved.