对于一个问题,我必须在屏幕上画一个圆,中心位于坐标(280,300),半径为50.提示说:圆是一个宽度和高度相同的椭圆。该圆圈的中心位于此椭圆形NW角的右下方50像素和50像素处。
有TryoutPanel类:
import java.awt.*;
import javax.swing.*;
public class TryoutPanel extends JPanel{
private Color myColor;
public TryoutPanel(Color c){
myColor = c;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setForeground(myColor);
g.drawString("top",10,50);
g.drawLine(10,60, 200,60);
g.drawString("middle",10,80);
g.drawLine(10,90, 200,90);
g.drawString("bottom",10,110);
g.drawLine(10,120, 200,120);
g.drawRect(200,300,100,50);
g.drawOval(200,300,100,50);
for(int j = 0; j < 9; j++)
g.drawOval(50,200, 10 + 20*j, 210 - 20*j);
}
}
我必须填写以下代码:
public void paintComponent(Graphics g){
super.paintComponent(g);
setForeground(myColor);
//INSERT CODE HERE
我试过了:
g.drawOval(280,300,50,50);
但它说我使用了不正确的参数。我做错了什么。
答案 0 :(得分:4)
x
的{{1}} / y
参数是绘制椭圆的上/左角
为了能够在drawOval
处围绕中心点绘制圆,您需要从每个点中减去半径,然后生成双倍的宽度和高度(直径)... < / p>
230x300
因此,此示例基本围绕g.drawOval(230 - radius, 300 - radius, radius * 2, radius * 2);
的点绘制一个矩形,宽度/高度为230x300
(半径= 100),并通过此点绘制线条以说明椭圆的中心点然后关于......
200
哦,import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TryoutOval {
public static void main(String[] args) {
new TryoutOval();
}
public TryoutOval() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TryoutPanel(Color.RED));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TryoutPanel extends JPanel {
private Color myColor;
public TryoutPanel(Color c) {
myColor = c;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int centerX = 280;
int centerY = 300;
int radius = 50;
int diameter = radius * 2;
int x = centerX - radius;
int y = centerY - radius;
g.setColor(Color.BLACK);
g.drawRect(x, y, diameter, diameter);
g.drawLine(x, y, x + diameter, y + diameter);
g.drawLine(x + diameter, y, x, y + diameter);
g.setColor(myColor);
g.drawOval(x, y, diameter, diameter);
g.fillOval(centerX - 5, centerY - 5, 10, 10);
}
}
}
在任何setForeground(myColor);
方法中都是一个非常糟糕的主意,因为每次调用该方法时都会导致paint
事件被添加到事件队列中,将导致一个永无止境的重绘请求,最终消耗你的CPU