我想知道如何在我的JFrame中的特定x,y坐标处绘制一个点/像素。
有人知道一些简单的代码吗?
我创建了一个小的示例程序:
public class Test extends JFrame {
public Test() {
this.setPreferredSize(new Dimension(400, 400));
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
// define the position
int locX = 200;
int locY = 200;
// draw a line (there is no drawPoint..)
g.drawLine(locX, locY, locX, locY);
}
public static void main(String[] args) {
Test test = new Test();
}
}
您也可以使用更新或paintComponents方法,这将更加美观。但是您必须确保它被调用。如果出现问题并且未被调用,则可以使用以下解决方案:为什么paint()/ paintComponent()从未被调用?
在简单性和实用性之间取得最佳折衷可能是扩展JPanel,并覆盖paintComponent(Graphics)方法。然后将该面板放置在您的JFrame中(使用适当的布局)。这里有一些使用说明:http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29
看
void update(Graphics g)
JFrame类的方法。Graphics API(如绘制点、绘制线、绘制弧等)在Graphics类中。
编辑:http://www.javadb.com/drawing-a-line-using-java-2d-graphics-api
问问自己是否真的想要扩展 JFrame
或 JPanel
。如果你决定不这样做,那么你可以创建一个基本的 JComponent
。这取决于你使用的布局管理器,你可能会有不同的成功。
public class PixelComponent extends JComponent
{
private Color color;
public PixelComponent(Color color)
{
super();
this.color = color;
}
public PixelComponent()
{
this(Color.BLACK);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, 1, 1);
}
}
发送图形参考和x轴、y轴以制作像素:
private void doPixel(Graphics g, int x, int y){
g.fillRect(x, y, 1, 1);
}