Reputation: 3471
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?
Upvotes: 0
Views: 956
Reputation: 159864
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());
Upvotes: 2
Reputation: 8947
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);
}
}
Upvotes: -1