简单的 Java 2D 图形:绘制一个矩形? [英] Simple Java 2D graphics: draw a rectangle?
本文介绍了简单的 Java 2D 图形:绘制一个矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试让 Java 2D 图形hello world"运行起来,但我发现它出奇地困难(即,我在谷歌上搜索java hello world 示例"的变体,结果却是空的).任何人都可以帮助我提供一个最小的地狱世界示例吗?
I'm trying to get a Java 2D graphics "hello world" going, and am finding it strangely difficult (ie, I'm Googling variations of "java hello world example" and coming up empty). Can anyone help me with a minimal hellow world example?
编辑
这是一个很好的起点,"Java 教程:执行自定义绘画".
This is a good starting point though, "The Java Tutorials: Performing Custom Painting".
推荐答案
要在 Swing 中绘制矩形,您应该:
To draw a rectangle in Swing you should:
- 首先,切勿直接在 JFrame 或其他顶级窗口中绘制.
- 改为绘制 JPanel、JComponent 或其他最终从 JComponent 扩展的类.
- 您应该覆盖
paintComponent(Graphics g)
方法. - 一定要调用超级方法
- 您应该使用 JVM 提供给该方法的 Graphics 对象绘制矩形.
- 您应该阅读 Swing 教程中的绘画.
清楚了吗?
例如
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class DrawRect extends JPanel {
private static final int RECT_X = 20;
private static final int RECT_Y = RECT_X;
private static final int RECT_WIDTH = 100;
private static final int RECT_HEIGHT = RECT_WIDTH;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the rectangle here
g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT);
}
@Override
public Dimension getPreferredSize() {
// so that our GUI is big enough
return new Dimension(RECT_WIDTH + 2 * RECT_X, RECT_HEIGHT + 2 * RECT_Y);
}
// create the GUI explicitly on the Swing event thread
private static void createAndShowGui() {
DrawRect mainPanel = new DrawRect();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
这篇关于简单的 Java 2D 图形:绘制一个矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文