2010-11-18 42 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); }