尝试编写某种Gui并需要绘制嵌套的4096个椭圆并想要枚举它们(从1到4096)。但是,无法弄清楚drawOval方法是如何工作的(更具体地说,对于为此找到数学公式并在方法中使用坐标参数几乎没有问题)
这是我到目前为止所做的事情: 此代码绘制1个圆并试图减少参数,但没有成功。你能解释一下如何正确使用draw方法的参数以及如何为它做一个公式吗?
其次,我想给每个椭圆形一个数字,怎么做?
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D obj = (Graphics2D)g;
obj.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
obj.setColor(Color.black);
obj.drawOval(0,0, getWidth()+1, getHeight()+1);
}
private static void make() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new deneme2());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
make();
}
});
}
}
答案 0 :(得分:1)
这是示例提供here的补充说明,其中显示了如何绘制多个连续的圆圈并演示如何将文字呈现给他们......
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Circles {
public static void main(String[] args) {
new Circles();
}
public Circles() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
FontMetrics fm = g2d.getFontMetrics();
int padding = fm.getHeight() + 4;
int width = getWidth() - 1 - padding;
int height = getHeight() - 1 - padding;
int radius = Math.min(width, height);
int x = (padding + (width - radius)) / 2;
int y = (padding + (height - radius)) / 2;
g2d.drawOval(x, y, radius, radius);
String text = "This is a test";
int centerX = (padding + radius) / 2;
int centerY = (padding + radius) / 2;
x = (centerX - (fm.stringWidth(text)) / 2);
y = centerY - (radius / 2);
g2d.drawString(text, x, y);
x = centerX - (radius / 2);
g2d.drawString(text, x, centerY);
x = (centerX - (fm.stringWidth(text)) / 2);
y = centerY + (radius / 2);
g2d.drawString(text, x, y);
x = (centerX - (fm.stringWidth(text)) / 2);
y = centerY - (radius / 2);
g2d.rotate(Math.toRadians(90), getWidth() / 2, getHeight() / 2);
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}
我还建议您使用2D Graphics
进行农场自我培训