I'd like to draw pixels on a window with mouse input
I've done days of searching for a way to draw pixels to a window in java with mouse capture. I'm looking for some framework I can just plug in. It seems like it would be so simple... Any help will be greatly appreciated.
(EDIT) Here is some non-working code.
public class Base extends JPanel implements MouseMotionListener {
public static void main(String[] args) {
new Base();
}
final static int width = 800;
final static int height = 600;
BufferedImage img;
Base() {
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
JFrame frame = new JFrame();
frame.addMouseMotionListener(this);
frame.add(this);
frame.setSize(width, height);
frame.setEnabled(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
Graphics g = img.getGraphics();
g.drawRect(1, 1, width - 2, height - 2);
g.dispose();
repaint();
}
@Override
public void paintComponent(Gr开发者_StackOverflowaphics g) {
g.drawImage(img, 0, 0, null);
}
}
See comments in the code.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class Base extends JPanel implements MouseMotionListener {
public static void main(String[] args) {
new Base();
}
final static int width = 400;
final static int height = 300;
BufferedImage img;
Base() {
img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB_PRE);
// do in preference to setting the frame size..
setPreferredSize(new Dimension(width, height));
JFrame frame = new JFrame();
this.addMouseMotionListener(this); // INSTEAD OF THE FRAME
frame.add(this);
//frame.setSize(width, height); DO INSTEAD...
frame.pack();
//frame.setEnabled(true); REDUNDANT
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // good call!
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
Graphics g = img.getGraphics();
g.setColor(Color.RED); // SET A COLOR
g.drawRect(1, 1, width - 2, height - 2);
// DO SOMETHING UGLY
g.setColor(Color.blue);
Point p = e.getPoint();
g.fillOval(p.x,p.y,5,5);
g.dispose();
repaint();
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
Use a local BufferedImage on which you want to draw. Add a MouseMotionListener and implement the mouseDragged(MouseMotionEvent evt)
method. In that method draw onto the BufferedImage by doing something like this:
// Assume img is your BufferedImage
Graphics g = img.getGraphics();
g.drawRect(evt.getX()-1, evt.getY()-1, 3, 3);
g.dispose();
// repaint your swing component
repaint();
And in your overrided paintComponent(Graphics g)
method, draw like this:
g.drawImage(img, 0, 0, null);
Initialize your BufferedImage like this:
img = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
// Assuming `this` is your swing component
精彩评论