java 如何在 JFrame 中创建画布并绘制一些基本形状?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12139307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:45:06  来源:igfitidea点击:

How to create a canvas inside JFrame and draw a few basic shapes?

javaswing

提问by Denis Marson

I am new to java and created my own window frame. Now i just need to draw few graphics shapes into it.

我是 Java 新手并创建了自己的窗口框架。现在我只需要在其中绘制一些图形形状。

import javax.swing.JFrame;

public class run {

public static void main(String[] args) {

    JFrame frame = new JFrame();

int resx = 400,resy = 400;

frame.setSize(resx,resy);
frame.setLocationRelativeTo(null);
frame.setTitle("Mover");
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}
}

回答by MadProgrammer

Well, you could start with 2D Graphcs Trail

好吧,你可以从2D Graphcs Trail开始

I'd also use a JComponentor JPanelinstead of Canvas

我也会使用JComponentJPanel代替Canvas

回答by Vinay

Find more about paint here.

在此处了解有关油漆的更多信息。

A simple example is below.

下面是一个简单的例子。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SimpleDrawing extends JFrame {

public SimpleDrawing() {

    setSize(new Dimension(500, 500));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
}

public void paint(Graphics g) {

    g.setColor(Color.red);
    g.fillOval(20, 50, 100, 100);
    g.setColor(Color.blue);
    g.fillRect(100, 100, 100, 200);
}

public static void main(String arg[]) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            new SimpleDrawing();
        }
    });
}

}

Go through the paint method in the code.

遍历代码中的paint方法。