JFrame not painting rectangle

谁说我不能喝 提交于 2019-12-12 04:43:04

问题


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);
    }
}


来源:https://stackoverflow.com/questions/20620144/jframe-not-painting-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!