2010-11-18 48 views

回答

7

我创建了一个小例子程序:

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(); 
    } 
} 

你也可以使用update或paintComponents方法,这会更好。但是,你必须确保它被调用。如果你有问题,它不会被调用,你可以采用如下方案:Why is paint()/paintComponent() never called?

+0

整齐的小例子感谢。我不得不添加进口来运行:import javax.swing。*; import java.awt.Graphics; import java.awt.Dimension; – strainer 2010-11-18 17:57:36

+0

谢谢,你知道如何设置线/点/点的颜色吗? :) – 2010-11-18 22:31:40

+0

如何做双打而不是整数? – 2018-01-14 10:28:10

0

问问自己,如果你真的延长JFrameJPanel。如果您决定不这样做,那么您可以创建一个基本的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); 
    } 
} 
0

发送图形和参考轴x和y使一个像素:

private void doPixel(Graphics g, int x, int y){ g.fillRect(x, y, 1, 1); }