Domanda

I am new to Java and I have a problem with drawing an oval using paintComponent method. I found many similar threads, but none of the soultions worked. My code:

RacerMain.java

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

public class RacerMain {
    public static void main (String[]args) {
        //MainFrame mf = new MainFrame();
        JFrame jframe = new JFrame();
        JPanel jpanel = new JPanel();
        jframe.setSize(480,640);
        jframe.add(jpanel);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jpanel.add(new Dot());
        jframe.setVisible(true);
    }

}

Dot.java

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

public class Dot extends JComponent{
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.BLUE);
        g2d.fillOval(20, 20, 20, 20);
    }
}

Why it does not work and how to get this code working?

È stato utile?

Soluzione

JPanel uses FlowLayout which respects preferred sizes but the default size of the Dot component is too small to be seen. You need to use a layout manager that uses the maximum area available or override getPreferredSize. Remember to call pack before calling JFrame#setVisible

jpanel.setLayout(new BorderLayout());

Altri suggerimenti

Or you can set preferred size in constructor:

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

public class Dot extends JComponent {
    public Dot() {
        setPreferredSize(new Dimension(480, 640));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);
        g2d.fillOval(20, 20, 20, 20);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top