简体   繁体   中英

Why can't I paint to my JPanel?

When I run this program all I see is a blank JFrame. I have no idea why the paintComponent method isn't working. Here's my code:

package com.drawing;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPaint extends JPanel {

    private void go() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setVisible(true);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillRect(50, 50, 100, 100);
    }

    public static void main(String[] args) {
        My paintTester = new MyPaint();
        paintTester.go();
    }
}

You have to do this

private void go() {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(this);
        frame.pack();
        frame.setVisible(true);
    }

But i would refactor your class and separate responsabilities..

go() shouldn't be declared in this class

public class MyPaint extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillRect(50, 50, 100, 100);
    }

}

And in another class

// In another class 
public static void main(String[] args) {
    JPanel paintTester = new MyPaint();
    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.add(paintTester);
    frame.pack();
    frame.setVisible(true);
}

Or if you only gonna use this panel in one site you can take approach of anonymous classes

     JFrame frame = new JFrame();
     frame.add(new JPanel(){
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            g.fillRect(50, 50, 100, 100);
        }

     });

You're adding a plain JPanel to your JFrame which does not contain your custom paint logic. Remove

JPanel panel = new JPanel();

and add

frame.add(this);

but better to maintain 2 classes: a main class and a custom JPanel with paint logic for separation of concerns .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM