<分区>
我正在尝试运行 Java 2D 图形“hello world”,但发现它异常困难(即,我在谷歌上搜索“java hello world example”的变体,结果是空的)。谁能帮我举一个最小的 hell 世界示例?
编辑
虽然这是一个很好的起点,"The Java Tutorials: Performing Custom Painting" .
<分区>
我正在尝试运行 Java 2D 图形“hello world”,但发现它异常困难(即,我在谷歌上搜索“java hello world example”的变体,结果是空的)。谁能帮我举一个最小的 hell 世界示例?
编辑
虽然这是一个很好的起点,"The Java Tutorials: Performing Custom Painting" .
最佳答案
要在 Swing 中绘制矩形,您应该:
paintComponent(Graphics g)
方法。清楚了吗?
例如,
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 - 简单的 Java 2D 图形 : draw a rectangle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21964768/