如何使用java.awt.Graphics绘制圆



我只是尝试使用 drawOval() 方法绘制圆,当我运行程序时它只显示小正方形。我试图将构造函数添加到 Surface 类中,但它也没有很好地工作。这是我编写的代码:

    package swing22;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.*;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    public class MyFrame {
        JFrame frame = new JFrame(" Test Frame ");
        JPanel panel = new JPanel();
        JButton button = new JButton("CLICK");
        JLabel label = new JLabel(" 33 ");
        public MyFrame(){
            gui();
        }
        public void gui(){
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
            panel.setBackground(Color.GREEN);
            panel.add(button);
            panel.add(label);
            panel.add(new Surface());
            frame.add(panel, BorderLayout.CENTER);
            button.addActionListener(new Action());
            frame.pack();
            frame.setSize(300,300);
            frame.setVisible(true);
            frame.setResizable(false);
        }

        class Action implements ActionListener{
            @Override
            public void actionPerformed(ActionEvent arg0) {
                label.setText("new value");
            }
        }
    }

    class Surface extends JPanel {

            private void doDrawing(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                    g.setColor(Color.red);
                    g.drawOval(80, 80, 30, 30);
                    g.fillArc(140, 140, 30, 30, 0, 90);
            }
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                doDrawing(g);
            }
        }

您没有设置组件大小,因此组件太小而无法显示圆圈。

调整组件大小,圆圈将正确显示

public void gui(){
    ....
    Surface s = new Surface();
    s.setPreferredSize(new Dimension(200, 200));
    panel.add(new Surface());
    ...
}

您可以通过设置组合或覆盖其getPrefferedSize()-methode 来获取组合物

use this class (Graphiic) and it's method (Draw_Circle)
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Graphiic
{   
    public Graphics GClass;
    public Graphics2D G2D;
    public  void Draw_Circle(JFrame jf,int radius , int  xLocation, int             yLocation)
    {
        GClass = jf.getGraphics();
        GClass.setPaintMode();
        GClass.setColor(Color.MAGENTA);
        GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360);           
    }

相关内容

  • 没有找到相关文章