简体   繁体   English

使用秋千在画布上绘制椭圆

[英]Drawing oval in canvas using swing

I am new to Java and I have a problem with drawing an oval using paintComponent method. 我是Java新手,使用paintComponent方法绘制椭圆形时遇到问题。 I found many similar threads, but none of the soultions worked. 我发现了许多类似的线程,但是所有的灵魂都不起作用。 My code: 我的代码:

RacerMain.java 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 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? 为什么它不起作用以及如何使此代码起作用?

JPanel uses FlowLayout which respects preferred sizes but the default size of the Dot component is too small to be seen. JPanel使用FlowLayout遵循首选大小,但是Dot组件的默认大小太小而看不到。 You need to use a layout manager that uses the maximum area available or override getPreferredSize . 您需要使用使用最大可用面积的布局管理器,或者覆盖getPreferredSize Remember to call pack before calling JFrame#setVisible 记住在调用JFrame#setVisible之前先调用pack

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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