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:
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);
}
}
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?
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());
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);
}
}
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.