0

我不明白为什么我的代码不起作用,试图在我JFramef.add(p);.

import javax.swing.*;
import java.awt.*;

public class SPEL{

    public void paintComponent(Graphics g){
        g.drawRect(50,75,100,50);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();

        f.setSize(400, 300);
        f.setLocation(100,100);
        f.setTitle("SPEL");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SPEL p = new SPEL();
        f.add(p);//error
        f.setVisible(true);
    }
}
4

2 回答 2

3

You forgot to extends something, for example:

public class SPEL extends JPanel {

You can add @Override to reduce the chance of this kind of mistake

@Override
public void paintComponent(Graphics g){
于 2013-05-17T10:20:40.830 回答
1

尝试这个!:

import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial")
public class SPEL extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(Color.red);
        Rectangle b = new Rectangle(50, 75, 100, 50);
        g2d.draw(b);
        g2d.fill(b);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();

        f.setSize(400, 300);
        f.setLocation(100, 100);
        f.setTitle("SPEL");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SPEL p = new SPEL();
        f.add(p);
        f.setVisible(true);
    }
}
  • extends JPanle
  • @Override
  • Using Graphics2D
  • g2d.fill(Shape s)
于 2013-05-17T11:01:15.980 回答