JFrame not painting rectangle

2019-09-06 02:40发布

问题:

Have a very simple issue which I haven't come across before. I used a similar layout before when doing a project.

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

class q1
{
    public static void main (String Args [])
    {
        q1Window showMe = new q1Window();
    }
}

class q1Window
{
    q1Window()
    {
        JFrame window = new JFrame("Tutorial 1");
        window.setSize(600,600);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint (Graphics back)
    {
        back.setColor(Color.black);
        back.fillRect(30,30,100,200);           
    }
}

Now I can't seem to print anything however the JFrame shows.

回答1:

You can't just add a paint() method to any class. Only Swing components have painting methods.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

Quick summary is that you need to override the paintComponent() method of a JPanel and then add the panel to the frame.



回答2:

As camickr pointed out, you need a Swing component to do what you want, which in this case, is to override paint(), although you should be overriding paintComponent() instead.

Try this:

class q1 {

    public static void main(String Args[]) {
        q1Window showMe = new q1Window();
    }
}

class q1Window extends JFrame {

    q1Window() {
        setTitle("Tutorial 1");
        setSize(600, 600);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics back) {
        back.setColor(Color.black);
        back.fillRect(30, 30, 100, 200);
    }
}