[英]How do I draw a circle and rectangle with specified radius?
I am trying to draw a circle of a radius 60 centerd in the lower right quarter of the frame, and a square of radius 50 centered in the upper half of the frame. 我正在尝试绘制一个半径为60的圆,以框的右下四分之一为中心,并绘制一个半径为50的圆,以该框的上半部为中心。
The frame size is 300 x 300. I've done this till now. 画面尺寸为300 x300。到目前为止,我已经做到了。
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Test {
public static void main ( String[] args){
JFrameTest5 frame = new JFrameTest5();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setTitle("Test");
}
}
class JFrameTest5 extends JFrame {
public JFrameTest5()
{
setLocation(0,0);
setSize(300,300);
PanelTest1 panel = new PanelTest1();
add(panel);
}
}
class PanelTest1 extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Ellipse2D circle = new Ellipse2D.Double(250, 225, 120,120);
g2.draw(circle);
Rectangle2D rect = new Rectangle2D.Double(75,0,100,100);
g2.draw(rect);
}
}
The problem is the circle and the rectangle don't seem to be right , are there another methods to set the exact radius ? 问题是圆形和矩形似乎不正确,是否还有另一种方法来设置确切的半径?
The example below includes several important changes: 下面的示例包括几个重要的更改:
Use constants wherever possible. 尽可能使用常量。
Use panel-relative geometry. 使用面板相对几何。
Use initial threads correctly. 正确使用初始线程 。
Use pack()
to size the enclosing frame. 使用
pack()
调整封闭框架的大小。
Code: 码:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/a/10255685/230513 */
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrameTest frame = new JFrameTest();
}
});
}
}
class JFrameTest extends JFrame {
public JFrameTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test");
this.add(new JPanelTest());
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
}
class JPanelTest extends JPanel {
private static final int R = 60;
private static final int D = 2 * R;
private static final int W = 50;
private static final int E = 2 * W;
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(
getWidth() - D, getHeight() - D, D, D);
g2.draw(circle);
Rectangle2D rect = new Rectangle2D.Double(0, 0, E, E);
g2.draw(rect);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.