开发者

Java making a 'dot/pixel' In swing/awt

I want to know how to make a dot/pixel at a certain x,y co-ordinate on my JFrame.

Anyone know some simple 开发者_开发知识库code for this?


I have created a small example program:

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

You could also use the update or paintComponents method which would be much nicer. But then you have to make sure, that it gets called. If you have problems and it does not get called you could use the following solution: Why is paint()/paintComponent() never called?


Best compromise between simplicity and usefulness would probably be to extend JPanel, and override paintComponent( Graphics ). Then place that panel in your JFrame (with an appropriate layout. There are some usage notes here: http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29


see

void update(Graphics g) 

method of JFrame class. graphics API ( like draw point, draw line, draw arc, etc ) are in Graphics class.

EDIT: http://www.javadb.com/drawing-a-line-using-java-2d-graphics-api


Ask yourself if your really want to extend JFrame or JPanel. If you decide that you don't then you could create a basic JComponent. You may have varying success with this depending on what layout manager you use.

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


Send the Graphics Reference and axis x and y to make a pixel:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜