Bricks change color every instance of time - java

so, i'm doing breakout in java (this is not h/w, school is over)
I want to bricks to be random in color, but my bricks change color while the game is running. so right now, it looks like the bricks are lighting up!! please help!!
package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Random;
public class Brick {
public static final int X = 0, Y = 0, ROW_SIZE = 8, COL_SIZE = 5;
private Random random = new Random();
private ArrayList<Rectangle> arr = new ArrayList<>();
public Brick(int width, int height) {
for(int i = 0; i < COL_SIZE; i++){
for(int j = 0; j < ROW_SIZE; j++) {
Rectangle r = new Rectangle(X + (j * (width / ROW_SIZE)),
Y + (i * (height / COL_SIZE)), (width / ROW_SIZE), (height / COL_SIZE));
arr.add(r);
}
}
}
public ArrayList<Rectangle> getList(){
return arr;
}
public void setList(ArrayList<Rectangle> rects){
arr = rects;
}
public void paint(Graphics g){
for(Rectangle rect : arr){
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
}
}
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GamePanel extends JPanel implements ActionListener, KeyListener {
Player player = new Player();
Ball ball = new Ball();
Brick brick = new Brick(Pong.WIDTH, Pong.HEIGHT / 3);
JLabel label, gameOverLabel;
Timer time;
public GamePanel() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
time = new Timer(50, this);
time.start();
this.addKeyListener(this);
setFocusable(true);
// Displaying score
label = new JLabel();
gameOverLabel = new JLabel();
gameOverLabel.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
gameOverLabel.setAlignmentX(CENTER_ALIGNMENT);
label.setAlignmentX(CENTER_ALIGNMENT);
add(label);
add(gameOverLabel);
}
private void update() {
player.update();
if (ball.update()) {
gameOverLabel.setText("GAME OVER");
time.stop();
}
ball.checkCollisionWith(player);
ball.checkBrickCollision(brick);
}
public void paintComponent(Graphics g) {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
player.paint(g);
ball.paint(g);
brick.paint(g);
}
public void actionPerformed(ActionEvent e) {
update();
label.setText("Score: " + ball.getScore());
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
// Speed of player
int playerVelocity = 8;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.setXVelocity(playerVelocity);
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
player.setXVelocity(-playerVelocity);
} else if (e.getKeyCode() == KeyEvent.VK_R) {
ball = new Ball();
player = new Player();
ball.setScore(0);
label.setText("Score: " + ball.getScore());
gameOverLabel.setText("");
repaint();
time.start();
}
}
#Override
public void keyReleased(KeyEvent e) {
player.setXVelocity(0);
}
#Override
public void keyTyped(KeyEvent e) {
}
}
please help! thank you...

public void paint(Graphics g){
for(Rectangle rect : arr){
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
}
Indeed it change color on every repaint - you're creating new random Color on every call. I think you should create color in Brick constructor and reuse it.

Related

Adding Start, Stop, Reset button to simple java game

I am a new coder. I am having trouble adding a start and stop button for this piece of example code that i am working off. I'm sure i have to mess with with Thread.sleep(10); in the game class. This code starts the game when the program is run. is there a way i could add start button to start the thread. I have created j button already. Thanks.
Game Class
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Racquet racquet = new Racquet(this);
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
racquet.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
racquet.paint(g2d);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
Ball Class
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game= game;
}
void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if (collision()){
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
Racquet Class
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game = game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth() - WIDTH)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;
}
}
This is an mcve demonstrating the structure outlined in Hovercraft Full Of Eels comment :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimationUsingTimer {
private Timer timer;
AnimationUsingTimer() {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AnimationPanel animationPanel = new AnimationPanel();
window.add(animationPanel);
JButton start = new JButton("Start");
start.addActionListener(e -> animationPanel.start());
window.add(start, BorderLayout.PAGE_START);
JButton stop = new JButton("Stop");
stop.addActionListener(e -> animationPanel.stop());
window.add(stop, BorderLayout.PAGE_END);
window.pack();
window.setVisible(true);
}
class AnimationPanel extends JPanel{
private BufferedImage img;
private Area ball, walls;
private final static int W = 450, H = 300, DIAMETER = 20;
private int x = W/2, y = H/2, xDelta = 3, yDelta = 2;
AnimationPanel() {
img = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
JLabel imageLabel = new JLabel(new ImageIcon(img));
add(imageLabel);
walls = new Area(new Rectangle(0,0,W,H));
ActionListener animate = e -> {
animate();
repaint();
};
timer = new Timer(50, animate);
}
public void animate() {
x+=xDelta; y+=yDelta;
ball = new Area(new Ellipse2D.Double(x, y, DIAMETER, DIAMETER));
if (checkCollision(ball,walls)) {
if ( x+DIAMETER>img.getWidth() || x<0 ) {
xDelta *= -1;
}
if(y+DIAMETER>img.getHeight() || y<0 ) {
yDelta *= -1;
}
}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2D = img.createGraphics();
g2D.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2D.setColor(Color.CYAN);
g2D.fillRect(0, 0, img.getWidth(), img.getHeight());
if(ball != null){
g2D.setColor(Color.RED);
g2D.fill(ball);
}
g2D.dispose();
}
void start(){
timer.start();
}
void stop(){
timer.stop();
}
private boolean checkCollision(Area area1, Area area2) {
return area1.getBounds().intersects(area2.getBounds());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new AnimationUsingTimer());
}
}

Causing balls to collide in a simple ball bounce program

I have a simple ball bounce program in which the balls bounce of the sides of my frame fine. I tried to add a way for the balls to bounce off each other by checking if two balls were touching by creating a rectangle around each ball and checking if any other ball intersects that rectangle, and if they do switch their velocities. It works fine when I add the code that has ** around it and there is only one ball but as soon as I add more than one they start moving together until they get stuck out of the frame. I have no idea what is wrong.
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class BallBounceFrame
{
public static void main(String[] args)
{
new BallBounceFrame();
}
JFrame frame;
JPanel controlPanel;
JButton stop, start;
JSpinner ballNum;
Timer t;
BallCanvas c;
static int WIDTH = 500;
static int HEIGHT = 500;
public BallBounceFrame()
{
frame = new JFrame("Bouncing Balls");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
c = new BallCanvas(0, 20);
frame.add(c, BorderLayout.CENTER);
addPanels();
frame.setVisible(true);
t = new Timer(10, new animator());
t.start();
}
public void addPanels()
{
controlPanel = new JPanel();
start = new JButton("Start");
start.addActionListener(new buttonControlListener());
controlPanel.add(start);
stop = new JButton("Stop");
stop.addActionListener(new buttonControlListener());
controlPanel.add(stop);
ballNum = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
ballNum.addChangeListener(new spinnerControlListener());
controlPanel.add(ballNum);
frame.add(controlPanel, BorderLayout.NORTH);
}
class BallCanvas extends JPanel
{
private static final long serialVersionUID = 1L;
ArrayList<Ball> balls = new ArrayList<Ball>();
public BallCanvas(int ballNum, int ballSize)
{
setBalls(ballNum, ballSize);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
for(Ball b : balls)
{
b.move(this.getSize());
g2.fill(b);
}
}
public void animate()
{
while(true)
{
try
{
frame.repaint();
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void setBalls(int ballNum, int ballSize)
{
balls.clear();
for(int i = 0; i < ballNum; i++)
{
balls.add(new Ball(ballSize, balls));
}
}
}
class Ball extends Ellipse2D.Float
{
private int xVel, yVel;
private int size;
private ArrayList<Ball> balls;
public Ball(int size, ArrayList<Ball> balls)
{
super((int) (Math.random() * (BallBounceFrame.WIDTH /(1.1)) + 1), (int) (Math.random() * (BallBounceFrame.WIDTH /(1.3)) + 7), size, size);
this.size = size;
this.xVel = (int) (Math.random() * 7 + 2);
this.yVel = (int) (Math.random() * 7 + 2);
this.balls = balls;
}
public void move(Dimension panelSize)
{
**Rectangle2D r = new Rectangle2D.Float(super.x, super.y, size, size);
for(Ball b : balls)
{
if(b != this && b.intersects(r));
{
int tempx = xVel;
int tempy = yVel;
xVel = b.xVel;
yVel = b.yVel;
b.xVel = tempx;
b.yVel = tempy;
break;
}
}**
if(super.x < 0 || super.x > panelSize.getWidth() - size) xVel *= -1;
if(super.y < 5 || super.y > panelSize.getHeight() - size) yVel *= -1;
super.x += xVel;
super.y += yVel;
}
}
class animator implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
frame.repaint();
}
}
class buttonControlListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == stop) t.stop();
if(e.getSource() == start) t.start();
}
}
class spinnerControlListener implements ChangeListener
{
public void stateChanged(ChangeEvent e) {
if(e.getSource() == ballNum)
{
int balls = (int) ballNum.getValue();
c.setBalls(balls, 20);
frame.revalidate();
frame.repaint();
}
}
}
}
Your code has a single ArrayList<Ball> inside BallCanvas - the 'master' list - and then each Ball has its own ArrayList<Ball> representing the list of balls the were created up until that time. Ball then only uses its own ArrayList<Ball> inside the move() method.
May I suggest that you only have one, master ArrayList<Ball> inside BallCanvas? Instead of passing it in to the Ball constructor, pass it in to the move() call.

Java Tile Scrolling Issues

I'm fairly new to programming with graphics and I'm attempting to code a side scrolling 2D game. At the moment, I'm trying to figure out how to approach redrawing a scrolling image as it appears in the JFrame. I'm using 8x8 pixel blocks as images. One possible issue I thought about concerns moving a sprite just 1 or 2 pixels and still rendering each image as it appears pixel by pixel on/off of the screen. How do I go about rendering the image/blocks pixel by pixel instead of whole images should the sprite barely move? Any feedback is much appreciated!
This is a proof of concept only! I randomly generate the tiles that get painted, I hope you have some kind of virtual map setup so you know which tiles to paint at any given virtual point!
Basically, what this does, is when the screen is moved left or right, it shifts the "master" image left or right and stitches new tiles onto new edge
My test was using a style sheet of 31x31 cells (don't ask, I just grab it off the net)
This is VERY scaled down example of the output, it was running at 1100x700+
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Scroll {
public static void main(String[] args) {
new Scroll();
}
public Scroll() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage screen;
private BufferedImage styleSheet;
public TestPane() {
try {
styleSheet = ImageIO.read(getClass().getResource("/StyleSheet.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
ActionMap am = getActionMap();
am.put("left", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
stitch(-31);
}
});
am.put("right", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
stitch(31);
}
});
}
#Override
public void invalidate() {
screen = null;
super.invalidate();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void stitch(int direction) {
if (screen == null) {
prepareScreen();
}
Random r = new Random();
BufferedImage update = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = update.createGraphics();
g2d.drawImage(screen, direction, 0, this);
int gap = direction < 0 ? (direction * -1) : direction;
int xOffset = 0;
if (direction < 0) {
xOffset = getWidth() - gap;
}
for (int x = 0; x < gap; x += 31) {
for (int y = 0; y < getHeight(); y += 31) {
xOffset += x;
int cellx = 2;
int celly = 2;
if (r.nextBoolean()) {
cellx = 7;
celly = 5;
}
BufferedImage tile = styleSheet.getSubimage((cellx * 33) + 1, (celly * 33) + 1, 31, 31);
g2d.drawImage(tile, xOffset, y, this);
}
}
g2d.dispose();
screen = update;
repaint();
}
protected void prepareScreen() {
if (screen == null) {
screen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Random r = new Random();
Graphics2D g2d = screen.createGraphics();
for (int x = 0; x < getWidth(); x += 31) {
for (int y = 0; y < getHeight(); y += 31) {
int cellx = 2;
int celly = 2;
if (r.nextBoolean()) {
cellx = 7;
celly = 5;
}
BufferedImage tile = styleSheet.getSubimage((cellx * 33) + 1, (celly * 33) + 1, 31, 31);
g2d.drawImage(tile, x, y, this);
}
}
g2d.dispose();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (screen == null) {
prepareScreen();
}
g2d.drawImage(screen, 0, 0, this);
g2d.dispose();
}
}
}

Create a Trailing line of blood behind a player

I am currently working on a simple top down shooter. The object is a ball that slides around the screen, and I am trying to make a sort of wet-dragging affect.
I am using Java Swing and just the default Graphics2d lib inside.
This is what I have:
and this is my goal:
I need to know how I can make a curved line that has the ability to change alpha at the trailing end. I have searched online but I can only find non-dynamic solutions. (The tail needs to update as the player moves across the screen.)
A simple solution might be to simple add each point to a List of Points which before the player is moved.
You would simply then need to iterate this list and either simple use something like Graphics#drawLine or even GeneralPath to render the "drag" line, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Drag {
public static void main(String[] args) {
new Drag();
}
public Drag() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<Point> points;
private Point pos;
private int diametere = 10;
public TestPane() {
points = new ArrayList<>(25);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "down");
ActionMap am = getActionMap();
am.put("left", new MoveAction(-5, 0));
am.put("right", new MoveAction(5, 0));
am.put("up", new MoveAction(0, -5));
am.put("down", new MoveAction(0, 5));
pos = new Point(100 - (diametere / 2), 100 - (diametere / 2));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (points.size() > 1) {
g2d.setColor(Color.RED);
GeneralPath path = new GeneralPath();
boolean started = false;
System.out.println("----");
for (Point p : points) {
if (started) {
System.out.println(p);
path.lineTo(p.x, p.y);
} else {
path.moveTo(p.x, p.y);
started = true;
}
}
g2d.draw(path);
}
int radius = (int) (diametere / 2d);
g2d.setColor(Color.GREEN);
g2d.draw(new Ellipse2D.Double(pos.x - radius, pos.y - radius, diametere, diametere));
g2d.dispose();
}
protected void moveBy(int xDelta, int yDelta) {
if (pos.x + xDelta < 0) {
xDelta = 0;
pos.x = 0;
} else if (pos.x + xDelta + diametere > getWidth()) {
xDelta = 0;
pos.x = getWidth() - diametere;
}
if (pos.y + yDelta < 0) {
yDelta = 0;
pos.y = 0;
} else if (pos.y + yDelta + diametere > getHeight()) {
yDelta = 0;
pos.y = getWidth() - diametere;
}
points.add(new Point(pos));
pos.x += xDelta;
pos.y += yDelta;
repaint();
}
public class MoveAction extends AbstractAction {
private int xDelta;
private int yDelta;
public MoveAction(int xDelta, int yDelta) {
this.xDelta = xDelta;
this.yDelta = yDelta;
}
#Override
public void actionPerformed(ActionEvent e) {
moveBy(xDelta, yDelta);
}
}
}
}
Hmm.. maybe you need something like this:
public class BallArea extends JComponent {
static final int MAX_SIZE = 63;
static final BasicStroke stroke = new BasicStroke(5);
final Queue<Point> points = new LinkedList();
public BallArea() {
setSize(400, 400);
setBackground(Color.BLACK);
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
if (points.size() >= MAX_SIZE) {
points.poll();
}
points.add(e.getPoint());
repaint();
}
});
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(stroke);
int i = 1;
Point prev = null;
for (Point p : points) {
if (prev == null) {
prev = p;
continue;
}
g2.setColor(new Color(255, 0, 0, i*4));
g.drawLine(prev.x, prev.y, p.x, p.y);
i++;
prev = p;
}
}
}

Java ScrollPane on Buffered Image

So I have 4 classes, in my paint program and I am trying to add scrollbars to the canvas so that I can scroll around, When I make my buffered Image it is set to the size of the desktop, but the JFrame is only I think 700 or so pixels so as you expand or resize you are still on canvas. But I cant figure out how to add a JScrollPane to the buffered image so I can scroll around.
//MAIN//
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class Main
{
public static int choice;
public static void main(String[] args)
{
Board.getInstance();
}
}
//FRAME//
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
*
* #author Calvin Moss
*/
public class Board extends JFrame implements ActionListener
{
public static Board inst;
Board()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.add(Menu.getInstance(), BorderLayout.NORTH);
getContentPane().add(Drawing.getInstance(), BorderLayout.CENTER);
Drawing.getInstance().add(new JScrollPane());
setSize(1200, 800);
setBackground(Color.WHITE);
setVisible(true);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);
}
public static Board getInstance()
{
if(inst == null)
inst = new Board();
return inst;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("About"))
{
JFrame about = new JFrame("About");
about.setSize(300, 300);
JButton picture = new JButton(new ImageIcon("C:/Users/TehRobot/Desktop/Logo.png"));
about.add(picture);
about.setVisible(true);
}
}
}
//MENUPANEL//
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
*
* #author Calvin Moss
*/
public class Menu extends JPanel implements MouseListener, ActionListener{
public static Color bgColor = null;
public static int stroke = 0;
public static Menu instance;
private JButton clear;
private JButton line;
private JButton color;
private JButton erase;
private JButton pen;
public static boolean once = true;
public static BufferedImage buf = new BufferedImage(50,25,2);
public static Graphics2D gr = buf.createGraphics();
public static BufferedImage buf2 = new BufferedImage(50,25,2);
public static Graphics2D gr2 = buf2.createGraphics();
public static BufferedImage buf3 = new BufferedImage(50,25,2);
public static Graphics2D gr3 = buf3.createGraphics();
public static BufferedImage buf1 = new BufferedImage(50,25,2);
public static Graphics2D gr1 = buf1.createGraphics();
Menu()
{
setBackground(Color.GRAY);
TitledBorder titledBorder = BorderFactory.createTitledBorder("Toolbox");
setBorder(titledBorder);
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
;
clear = new JButton("Clear");
clear.setActionCommand("Clear");
clear.addActionListener(this);
pen = new JButton("Pen");
pen.setActionCommand("Pen");
pen.addActionListener(this);
erase = new JButton("Erase");
erase.setActionCommand("e");
erase.addActionListener(this);
color = new JButton("Color");
color.setActionCommand("Color");
color.addActionListener(this);
ImageIcon ir2 = new ImageIcon(buf3);
JButton emptyR = new JButton(ir2);
emptyR.addActionListener(this);
emptyR.setActionCommand("ER");
ImageIcon ir1 = new ImageIcon(buf2);
JButton emptyO = new JButton(ir1);
emptyO.addActionListener(this);
emptyO.setActionCommand("EO");
ImageIcon ir = new ImageIcon(buf);
JButton fillR = new JButton(ir);
fillR.addActionListener(this);
fillR.setActionCommand("FR");
ImageIcon io = new ImageIcon(buf1);
JButton fillO = new JButton(io);
fillO.addActionListener(this);
fillO.setActionCommand("FO");
line = new JButton("Line");
line.setActionCommand("L");
line.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);
ButtonGroup lineOption = new ButtonGroup( );
lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);
add(clear);
add(erase);
add(color);
add(pen);
add(line);
add(thin);
add(medium);
add(thick);
add(emptyR);
add(emptyO);
add(fillR);
add(fillO);
buttonGraphics();
once = false;
}
public static Menu getInstance()
{
if(instance == null)
instance = new Menu();
return instance;
}
public static void buttonGraphics()
{
if (once == true)
{
gr.setColor(Color.RED);
gr1.setColor(Color.RED);
gr2.setColor(Color.RED);
gr3.setColor(Color.RED);
}else
gr3.setColor(bgColor);
gr3.drawRect(0, 0, 48, 23);
gr2.setColor(bgColor);
gr2.drawOval(0, 0, 47, 23);
gr.setColor(bgColor);
gr.fillRect(0, 0, 50, 23);
gr1.setColor(bgColor);
gr1.fillOval(0, 0, 50, 25);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Clear"))
{
Drawing.getInstance().clear();
repaint();
}
if (e.getActionCommand().equals("e"))
{
Main.choice = 8;
Drawing.getInstance().draw();
}
if (e.getActionCommand().equals("Color"))
{
bgColor = JColorChooser.showDialog(this,"Choose Background Color", getBackground());
gr.setColor(bgColor);
gr1.setColor(bgColor);
gr2.setColor(bgColor);
gr3.setColor(bgColor);
Main.choice = 7;
buttonGraphics();
repaint();
Drawing.getInstance().draw();
}
if (e.getActionCommand().equals("L"))
{
Drawing.getInstance().FoE = 2;
Main.choice = 1;
repaint();
}
if (e.getActionCommand().equals("FR"))
{
Drawing.getInstance().FoE = 2;
Main.choice = 2;
repaint();
}
if (e.getActionCommand().equals("EO"))
{
Drawing.getInstance().FoE = 2;
Main.choice = 3;
repaint();
}
if (e.getActionCommand().equals("FO"))
{
Drawing.getInstance().FoE = 2;
Main.choice = 4;
repaint();
}
if(e.getActionCommand().equals("ER"))
{
Drawing.getInstance().FoE = 2;
Main.choice = 5;
repaint();
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
Drawing.getInstance().eraserHeight = 5;
Drawing.getInstance().eraserWidth = 5;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
Drawing.getInstance().eraserHeight = 15;
Drawing.getInstance().eraserWidth = 15;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
Drawing.getInstance().eraserHeight = 25;
Drawing.getInstance().eraserWidth = 25;
}
if(e.getActionCommand().equals("Pen"))
{
Main.choice = 10;
Drawing.getInstance().draw();
}
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
//DRAWING CANVAS PANEL//
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
*
* #author Calvin Moss
*/
public class Drawing extends JPanel implements MouseListener, ActionListener, MouseMotionListener
{
public int x1, x2 ,y1, y2;
public static Drawing instance;
public int FoE;
public int eraserWidth = 15;
public int eraserHeight = 15;
BufferedImage grid;
static Graphics2D gc;
Drawing()
{
setBackground(Color.RED);
addMouseListener(this);
}
public static Drawing getInstance()
{
if(instance == null)
instance = new Drawing();
return instance;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(grid == null)
{
Toolkit toolkit = Toolkit.getDefaultToolkit ();
Dimension dim = toolkit.getScreenSize();
grid = (BufferedImage)(this.createImage(dim.width,dim.height));
gc = grid.createGraphics();
gc.setColor(Color.RED);
BufferedImage grid;
Graphics2D gc;
}
g2.drawImage(grid, null, 0, 0);
}
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = x2 - x1;
if (w<0)
w = w *(-1);
int h = y2-y1;
if (h<0)
h= h*(-1);
gc.setColor(Menu.bgColor);
switch(Main.choice)
{
case 1:
{
removeMouseMotionListener(instance);
if (Menu.stroke == 0)
gc.setStroke(new BasicStroke (1));
if (Menu.stroke == 1)
gc.setStroke(new BasicStroke (3));
if (Menu.stroke == 2)
gc.setStroke(new BasicStroke (6));
gc.drawLine(x1, y1, x2, y2);
repaint();
break;
}
case 2:
{
removeMouseMotionListener(instance);
check();
gc.drawRect(x1, y1, w, h);
gc.fillRect(x1, y1, w, h);
repaint();
break;
}
case 3:
{
removeMouseMotionListener(instance);
check();
gc.drawOval(x1, y1, w, h);
repaint();
break;
}
case 4:
{
removeMouseMotionListener(instance);
check();
gc.drawOval(x1, y1, w, h);
gc.fillOval(x1, y1, w, h);
repaint();
break;
}
case 5:
{
removeMouseMotionListener(instance);
check();
gc.drawRect(x1, y1, w, h);
repaint();
break;
}
case 6:
{
removeMouseMotionListener(instance);
repaint();
Color temp = gc.getColor();
gc.setColor(Color.WHITE);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
break;
}
case 7:
{
removeMouseMotionListener(instance);
gc.setColor(Menu.bgColor);
break;
}
case 8:
{
FoE = 0;
addMouseMotionListener(instance);
break;
}
case 10:
{
FoE = 1;
addMouseMotionListener(instance);
break;
}
}
}
public void check()
{
if (Menu.stroke == 0)
gc.setStroke(new BasicStroke (1));
if (Menu.stroke == 1)
gc.setStroke(new BasicStroke (3));
if (Menu.stroke == 2)
gc.setStroke(new BasicStroke (6));
if (x1 > x2)
{
int z = 0;
z = x1;
x1 = x2;
x2 =z;
}
if (y1 > y2)
{
int z = 0;
z = y1;
y1 = y2;
y2 = z;
}
}
public void clear()
{
repaint();
Color temp = gc.getColor();
gc.setColor(Color.WHITE);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
}
public void mouseExited(MouseEvent e){ }
public void mouseEntered(MouseEvent e){}
public void mouseClicked(MouseEvent e){
}
public void mousePressed(MouseEvent evt)
{
x1 = evt.getX();
y1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
x2 = evt.getX();
y2 = evt.getY();
removeMouseMotionListener(instance);
draw();
}
public void mouseDragged(MouseEvent me)
{
check();
if (FoE == 0)
{
Color c = gc.getColor();
gc.setColor(Color.WHITE);
gc.drawOval(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.fillOval(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.setColor(c);
repaint();
}
else if (FoE == 1)
{
gc.setColor(gc.getColor());
gc.drawOval(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.fillOval(me.getX(), me.getY(), eraserWidth, eraserHeight);
repaint();
}
else
{
}
}
public void mouseMoved(MouseEvent arg0)
{
}
public void actionPerformed(ActionEvent arg0) {
}
}
I haven't tested your code but it looks like you're trying to add add JScrollPane to your JPanel (Drawing). It should be the other way around you should add the JPanel to the JScrollPane and then add the JScrollPane to the content pane of the frame:
JScrollPane scrollPane = new JScrollPane(Drawing.getInstance());
getContentPane().add(scrollPane, BorderLayout.CENTER);
How to use JScrollPane
You need to override the getPreferredSize() method of your Drawing class to return the size of the BufferedImages.
Scrollbars only appear when the preferred size of the component added to the scroll pane is greater than the size of the scroll pane.

Categories

Resources