Re: Simple Java Question
adric22 wrote:
However, I'm having the most difficult time finding information on how
to do what I want to do. I would rather program using the command-
line compiler if at all possible because the program I want to write
is a game and will essentially only be needing to plot pixels on the
screen and read input from the keyboard and mouse. Granted, I may
eventually want to write text on the screen or some basic shapes, but
most of what I'm going to be doing will just be plotting a screen-full
of pixels.
if anyone can point me in the right direction of a web page, or some
modern source code that just shows how to open a window of a specified
size and plot a pixel at x,y coordinates in whatever color I want...
that would be great!
Try the program below. It is rather useless in itself, but should
show something anyway.
Arne
=============================
package october;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawingFun extends JFrame {
private DrawingField df;
public DrawingFun() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
setTitle("Use arrows to move and R G B to change color");
df = new DrawingField();
addKeyListener(df);
getContentPane().add(df);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new DrawingFun();
f.setVisible(true);
}
});
}
}
class DrawingField extends JPanel implements KeyListener {
private final static int W = 640;
private final static int H = 480;
private BufferedImage img;
private int x;
private int y;
private Color color;
public DrawingField() {
img = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, W, H);
setPreferredSize(new Dimension(W, H));
x = 0;
y = 0;
color = Color.BLACK;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
@Override
public void keyPressed(KeyEvent e) {
int oldx = x;
int oldy = y;
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN:
if(y < H - 1) {
y += 5;
}
break;
case KeyEvent.VK_UP:
if(y > 0) {
y -= 5;
}
break;
case KeyEvent.VK_LEFT:
if(x > 0) {
x -= 5;
}
break;
case KeyEvent.VK_RIGHT:
if(x < W - 1) {
x += 5;
}
break;
case KeyEvent.VK_R:
color = Color.RED;
break;
case KeyEvent.VK_G:
color = Color.GREEN;
break;
case KeyEvent.VK_B:
color = Color.BLUE;
break;
}
Graphics g = img.getGraphics();
g.setColor(color);
g.fillOval(Math.abs(x + oldx) / 2, Math.abs(y + oldy) / 2, 10, 10);
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}