JavaFX Cell Spacing? - java

Here is my code for my game of life i am creating, I want to try to add spacing between the alive cells but can't figure it out.
Can somebody help to do this? or is it possible to make a grid in the background?
public class ClickFX extends Application
{
public LifeGrid lg;
public int x;
public int y;
public static void main(String[] args)
{
launch(args);
}
GraphicsContext gc;
ClickData clickData;
int squareSize;
Stage primaryStage;
Color colours[] = { Color.WHITE, Color.RED, Color.GREEN, Color.CYAN,
Color.BLUE, Color.BLACK };
public void start(Stage primaryStage) throws FileNotFoundException {
squareSize = 6;
int x = 80, y = 80;
clickData = new ClickData(x, y);
lg = new LifeGrid(x,y,"seed.txt");
VBox root = new VBox(8);
HBox buttons = new HBox(5);
buttons.setAlignment(Pos.CENTER);
Button ngButton = new Button("Next Gen");
ngButton.setOnAction(new ngButtonHandler());
ngButton.setTooltip(new Tooltip("Click to Start!\nKeep clicking to Evolve!"));
Button clearButton = new Button("Clear");
clearButton.setOnAction(new clearButtonHandler());
clearButton.setTooltip(new Tooltip("Click to Clear"));
Button randomButton = new Button("Random Generate");
randomButton.setOnAction(new randomButtonHandler());
randomButton.setTooltip(new Tooltip("Click to create Random Generation"));
Button closeButton = new Button("Close");
closeButton.setOnAction(new closeButtonHandler());
buttons.getChildren().addAll(ngButton, randomButton, clearButton, closeButton);
Canvas canvas = new Canvas(x * squareSize, y * squareSize);
gc = canvas.getGraphicsContext2D();
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, new mouseClickHandler());
this.primaryStage = primaryStage;
primaryStage.setTitle("Game Of Life");
root.getChildren().addAll(canvas, buttons);
primaryStage.setScene(new Scene(root));![enter image description here][1]
primaryStage.setResizable(false);
primaryStage.show();
}
public void init() throws Exception
{
super.init();
Parameters parameters = getParameters();
Map<String, String> namedParameters = parameters.getNamed();
for(Map.Entry<String, String> entry : namedParameters.entrySet())
{
if("width".equals(entry.getKey()))
{
x = Integer.parseInt(entry.getValue());
}
else if("height".equals(entry.getKey()))
{
y = Integer.parseInt(entry.getValue());
}
}
}
The action for the buttons are created below.
class clearButtonHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
clickData.clear();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, clickData.getX() * squareSize, clickData.getY()
* squareSize);
}
}
class closeButtonHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
primaryStage.close();
}
}
class randomButtonHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
lg.RandomGeneration();
drawNG();
}
}
class ngButtonHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
drawNG();
lg.Run();
}
}
Here I draw onto the canvas the alive cells.
public void drawNG()
{
for(int i=0; i<lg.CG.length; i++)
{
for(int k=0; k<lg.CG[0].length; k++)
{
if(lg.CG[i][k] == 1)
{
gc.setFill(Color.BLACK);
gc.setStroke(Color.RED);
gc.fillRect(k*squareSize, i*squareSize, squareSize, squareSize);
}
else
{
gc.setFill(Color.WHITE);
gc.fillRect(k*squareSize, i*squareSize, squareSize, squareSize);
}
}
}
}

Change
gc.fillRect(k*squareSize, i*squareSize, squareSize, squareSize)
to...
gc.fillRect(k*squareSize + offset, i*squareSize + offset, squareSize, squareSize)
where offset is the distance you want between them.

Related

Show an Array of JButtons one after another with a timer [JAVA SWING]

I am making a Color game in which when I click on start a chain of colors will be shown. Now I have to click on my 4 color buttons and match the shown chain.
If I win, the chain adds a color (Level up) if I lose the chain loses a color (Level down).
My problems right now :
If I overlap the shown colors to match, I will only see the first index of the Array. I need to make it to show all Indexes of the JButton [] like every 2 seconds. I tried it with timer but it still show only the first one.
If I level up, I can add a color to the need to match array, but If I level down, I cant delete the last added color. I know there is no way to remove something from an Array, but is there a workaround. Right now I am making the player lose completely if he doesnt match the scheme.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Farbgedaechtnisspiel {
private static int startLevel = 1;
private static int gameLevel = 3;
private static List<Integer> gameArray = new ArrayList<>();
private static List<Integer> userArray = new ArrayList<>();
private static int save = 0;
private static int count = 0;
private static JButton [] b;
private static final Color red = new Color(255, 0, 0);
private static final Color green = new Color(0, 255, 0);
private static final Color blue = new Color(0, 0, 255);
private static final Color yellow = new Color(255, 255, 0);
private static JFrame frame = new JFrame("Farbgedächtnisspiel");
private static JLabel levelTxt;
public static void main(String[] args) {
// create mainframe
new Farbgedaechtnisspiel();
}
public Farbgedaechtnisspiel () {
createFrame(frame);
levelTxt = new JLabel("Level: " + startLevel);
frame.add(levelTxt);
levelTxt.setFont(new Font("Times New Roman", Font.ITALIC, 40));
// create 4 color buttons + start/exit
b = new JButton[7];
for(int i = 0;i<b.length;i++){
b[i] = new JButton();
frame.add(b[i]);
}
// create button layout
createButtons();
// button listeners
b[4].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// start Game -> show taskArray
levelTxt.setBounds(550, 200, 200, 200);
startGame(gameLevel);
}});
b[5].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
b[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(1);
save++;
}
}
);
b[1].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(2);
save++;
}
});
b[2].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(3);
save++;
}
});
b[3].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(4);
save++;
}
});
b[6].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean result = compareArrays(userArray, gameArray);
if (result){
gameLevel++;
save = 0;
startLevel++;
levelTxt.setText("Level: " + startLevel);
} else {
JOptionPane.showMessageDialog(frame, "Sie haben verloren");
new Farbgedaechtnisspiel();
System.exit(1);
}
startGame(gameLevel);
}
});
// make frame visible
frame.setVisible(true);
}
public static void startGame(int gameLevel){
int x = 100;
JButton [] tmp = new JButton[gameLevel];
for(int i = 0;i<tmp.length;i++) {
tmp[i] = new JButton();
tmp[i].setBackground(randomColor());
tmp[i].setOpaque(true);
tmp[i].setBorderPainted(false);
frame.add(tmp[i]);
if (tmp[i].getBackground() == red) {
gameArray.add(1);
} else if (tmp[i].getBackground() == blue) {
gameArray.add(2);
} else if (tmp[i].getBackground() == green) {
gameArray.add(3);
} else if (tmp[i].getBackground() == yellow) {
gameArray.add(4);
}
}
for (int i = 0; i < tmp.length; i++) {
tmp[i].setBounds(x, 50, 100, 100);
x+=100;
}
// for (int i = 0; i < tmp.length; i++) {
// tmp[i].setBounds(450, 50, 300, 299);
// x += 100;
// }
}
public static void createButtons() {
int x = 0;
for (int i = 0; i < b.length; i++) {
b[i].setBounds(x, 0, 200, 200);
x += 200;
}
b[0].setBackground(red);
b[0].setOpaque(true);
b[0].setBorderPainted(false);
b[1].setBackground(blue);
b[1].setOpaque(true);
b[1].setBorderPainted(false);
b[2].setBackground(green);
b[2].setOpaque(true);
b[2].setBorderPainted(false);
b[3].setBackground(yellow);
b[3].setOpaque(true);
b[3].setBorderPainted(false);
b[4].setBounds(150,600,300,200);
b[4].setText("Start");
b[5].setBounds(450, 600, 300, 200);
b[5].setText("Beenden");
b[6].setBounds(750, 600, 300, 200);
b[6].setText("Continue");
b[0].setBounds(200, 400, 200, 200);
b[1].setBounds(400, 400, 200, 200);
b[2].setBounds(600, 400, 200, 200);
b[3].setBounds(800, 400, 200, 200);
}
public static boolean compareArrays(List<Integer> userArray, List<Integer> gameArray){
return userArray.equals(gameArray);
}
public static void createFrame(JFrame frame){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setResizable(false);
}
public static Color randomColor () {
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
return switch (randomNum) {
case 1 -> red;
case 2 -> green;
case 3 -> blue;
case 4 -> yellow;
default -> null;
};
}
}```

Adding a JButton to a class extended by JPanel is not displaying a button

When I use normal JPanel initialized inside main instead of extended class. The button is added to a panel without problem and after launch is displayed in a center of a frame (default layout).
I would like to be able to add buttons inside an extended class. This problem occurs in Screen class aswell, where I need a Play Again button or Next Level button. The Screen is class extended by a JPanel too and JButtons are initialized inside the constructor aswell.
I'm not sure if the wrong part is in way of adding the components or in writing a code for a JPanel.
Here is the code:
Main:
public static void main(String[] args) {
// window - class JFrame
theFrame = new JFrame("Brick Breaker");
// game panel initialization
GamePanel gamePanel = new GamePanel(1);
theFrame.getContentPane().add(gamePanel);
// base settings
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setLocationRelativeTo(null);
theFrame.setResizable(false);
theFrame.setSize(WIDTH, HEIGHT);
theFrame.setVisible(true);
}
GamePanel Class:
public class GamePanel extends JPanel {
// Fields
boolean running;
boolean clicked = false;
private int rows = 8, colms = 11, N = rows * colms, level; // numbers of rows and columns
private int colmsC, rowsC;
private BufferedImage image;
private Graphics2D g;
private MyMouseMotionListener theMouseListener;
private MouseListener mouseListener;
private int counter = 0;
// entities
Ball theBall;
Paddle thePaddle;
Bricle[] theBricks;
Screen finalScreen;
public GamePanel(int level) {
// buttons
JButton pause = new JButton(" P ");
add(pause);
this.level = level;
init(level);
}
public void init(int level) {
// level logic
this.rowsC = level + rows;
this.colmsC = level + colms;
int count = rowsC * colmsC;
thePaddle = new Paddle();
theBall = new Ball();
theBall.setY(thePaddle.YPOS - thePaddle.getHeight() + 2);
theBall.setX(thePaddle.getX() + thePaddle.getWidth() / 2 - 5);
theBricks = new Bricle[count];
theMouseListener = new MyMouseMotionListener();
addMouseMotionListener(theMouseListener);
mouseListener = new MyMouseListener();
addMouseListener(mouseListener);
// make a canvas
image = new BufferedImage(BBMain.WIDTH, BBMain.HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// specific Bricks initialized
int k = 0;
for (int row = 0; row < rowsC; row++) {
for (int col = 0; col < colmsC; col++) {
theBricks[k] = new Bricle(row, col);
k++;
}
}
running = true;
}
public void playGame() {
while (running) {
//update
if (clicked) {
update();
}
// draw
draw();
// display
repaint();
// sleep
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// update loop ( like playGame )
public void update() {
// ball moving
checkCollisions();
theBall.update();
}
public void draw() {
// background
g.setColor(Color.WHITE);
g.fillRect(0,0, BBMain.WIDTH, BBMain.HEIGHT-20);
// the bricks
int k = 0;
for (int row = 0; row < rowsC; row++) {
for (int col = 0; col < colmsC; col++) {
theBricks[k].draw(g, row, col);
k++;
}
}
// the ball and the paddle
theBall.draw(g);
thePaddle.draw(g);
// counter
String countString = new Integer(this.counter).toString();
g.drawString(countString, 20, 20);
// WIN / LOOSE SCREEN
if (this.counter == this.N * 20) {
win();
}
if (theBall.getRect().getY() + theBall.getRect().getHeight() >= BBMain.HEIGHT) {
loose();
}
}
public void paintComponent(Graphics g) {
// retype
Graphics2D g2 = (Graphics2D) g;
// draw image
g2.drawImage(image, 0, 0, BBMain.WIDTH, BBMain.HEIGHT, null);
// dispose
g2.dispose();
}
public void pause() {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"GAME PAUSED");
}
public void win() {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"YOU WIN");
}
public void loose () {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"YOU LOOSE");
}
public void addScore() {
this.counter += 20;
theBall.setDY(theBall.getDY() - 0.001);
}
// Mouse Listeners
private class MyMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
clicked = true;
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
private class MyMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
if (clicked)
thePaddle.mouseMoved(e.getX());
}
}
}

how to separate the logic from the form in java swing?

I have difficulties in separating the logic of the game from the view. The view should be dumb and simply render the current state of the model. But I can not figure out how to do that. Could you please help me in making the code simpler and separating the logic from the form? Because I want to extend the game and add new things but I can not because of the confusing form of the code. I am new in java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
public class ProjectileShooterTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
final ProjectileShooter projectileShooter = new ProjectileShooter();
ProjectileShooterPanel projectileShooterPanel = new ProjectileShooterPanel(
projectileShooter);
projectileShooter.setPaintingComponent(projectileShooterPanel);
JPanel controlPanel = new JPanel(new GridLayout(1, 0));
controlPanel.add(new JLabel("Angle"));
final JSlider angleSlider = new JSlider(0, 90, 45);
controlPanel.add(angleSlider);
controlPanel.add(new JLabel("Power"));
final JSlider powerSlider = new JSlider(0, 100, 50);
controlPanel.add(powerSlider);
JButton shootButton = new JButton("Shoot");
shootButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int angleDeg = angleSlider.getValue();
int power = powerSlider.getValue();
projectileShooter.setAngle(Math.toRadians(angleDeg));
projectileShooter.setPower(power);
projectileShooter.shoot();
}
});
controlPanel.add(shootButton);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(controlPanel, BorderLayout.NORTH);
f.getContentPane().add(projectileShooterPanel, BorderLayout.CENTER);
f.setVisible(true);
}
}
class ProjectileShooter {
private double angleRad = Math.toRadians(45);
private double power = 50;
private Projectile projectile;
private JComponent paintingComponent;
void setPaintingComponent(JComponent paintingComponent) {
this.paintingComponent = paintingComponent;
}
void setAngle(double angleRad) {
this.angleRad = angleRad;
}
void setPower(double power) {
this.power = power;
}
void shoot() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
executeShot();
}
});
t.setDaemon(true);
t.start();
}
private void executeShot() {
if (projectile != null) {
return;
}
projectile = new Projectile();
Point2D velocity = AffineTransform.getRotateInstance(angleRad).transform(
new Point2D.Double(1, 0), null);
velocity.setLocation(velocity.getX() * power * 0.5, velocity.getY() * power * 0.5);
projectile.setVelocity(velocity);
long prevTime = System.nanoTime();
while (projectile.getPosition().getY() >= 0) {
long currentTime = System.nanoTime();
double dt = 3 * (currentTime - prevTime) / 1e8;
projectile.performTimeStep(dt);
prevTime = currentTime;
paintingComponent.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
projectile = null;
paintingComponent.repaint();
}
Projectile getProjectile() {
return projectile;
}
}
class Projectile {
private final Point2D ACCELERATION = new Point2D.Double(0, -9.81 * 0.1);
private final Point2D position = new Point2D.Double();
private final Point2D velocity = new Point2D.Double();
public Point2D getPosition() {
return new Point2D.Double(position.getX(), position.getY());
}
public void setPosition(Point2D point) {
position.setLocation(point);
}
public void setVelocity(Point2D point) {
velocity.setLocation(point);
}
void performTimeStep(double dt) {
scaleAddAssign(velocity, dt, ACCELERATION);
scaleAddAssign(position, dt, velocity);
}
private static void scaleAddAssign(Point2D result, double factor, Point2D addend) {
double x = result.getX() + factor * addend.getX();
double y = result.getY() + factor * addend.getY();
result.setLocation(x, y);
}
}
class ProjectileShooterPanel extends JPanel {
private final ProjectileShooter projectileShooter;
public ProjectileShooterPanel(ProjectileShooter projectileShooter) {
this.projectileShooter = projectileShooter;
}
#Override
protected void paintComponent(Graphics gr) {
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
Projectile projectile = projectileShooter.getProjectile();
if (projectile != null) {
g.setColor(Color.RED);
Point2D position = projectile.getPosition();
int x = (int) position.getX();
int y = getHeight() - (int) position.getY();
Ellipse2D.Double gerd = new Ellipse2D.Double(x - 01, y - 10, 20, 20);
g.draw(gerd);
// g.fillOval(x-01, y-10, 20, 20);
}
Rectangle hadaf1 = new Rectangle(450, 450, 50, 50);
Rectangle hadaf2 = new Rectangle(500, 450, 50, 50);
Rectangle hadaf3 = new Rectangle(475, 400, 50, 50);
g.draw(hadaf1);
g.draw(hadaf2);
g.draw(hadaf3);
}
}
I will be so thankful.

How to scroll a JLayeredpane in java?

I'm trying to make a java class that contains one layeredpane with 2 JPanel and a scroller.
There are 2 drawings so that I'll be able to draw different things with different threads on each panel, however, nothing happens when I use this class, and, I've checked if I delete the layeredPane and drawingPane0, creating the scroller with drawingPane1, it works correctly...
Does anyone know whats wrong?
Thank you all!
Here it's my code:
public class ScrollPanel extends JPanel implements MouseListener{
private Dimension area; //indicates area taken up by graphics
private Vector<Rectangle> circles; //coordinates used to draw graphics
private JPanel drawingPane0;
private JPanel drawingPane1;
private JLayeredPane layeredPane;
private final Color colors[] = {
Color.red, Color.blue, Color.green, Color.orange,
Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
private final int color_n = colors.length;
public ScrollPanel() {
super(new BorderLayout());
area = new Dimension(0, 0);
circles = new Vector<Rectangle>();
drawingPane1 = new DrawingPane();
layeredPane = new JLayeredPane();
drawingPane0 = new DrawingPane();
drawingPane0.setBackground(Color.WHITE);
drawingPane1.addMouseListener(this);
drawingPane1.setOpaque(false);
layeredPane.add(drawingPane0,0);
layeredPane.add(drawingPane1,1);
JScrollPane scroller = new JScrollPane(layeredPane);
add(scroller, BorderLayout.CENTER);
}
public class DrawingPane extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle rect;
for (int i = 0; i < circles.size(); i++) {
rect = circles.elementAt(i);
g.setColor(colors[(i % color_n)]);
g.fillOval(rect.x, rect.y, rect.width, rect.height);
}
}
}
public void mouseReleased(MouseEvent e) {
final int W = 100;
final int H = 100;
boolean changed = false;
if (SwingUtilities.isRightMouseButton(e)) {
circles.removeAllElements();
area.width = 0;
area.height = 0;
changed = true;
} else {
int x = e.getX() - W / 2;
int y = e.getY() - H / 2;
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
Rectangle rect = new Rectangle(x, y, W, H);
circles.addElement(rect);
drawingPane1.scrollRectToVisible(rect);
int this_width = (x + W + 2);
if (this_width > area.width) {
area.width = this_width;
changed = true;
}
int this_height = (y + H + 2);
if (this_height > area.height) {
area.height = this_height;
changed = true;
}
}
if (changed) {
drawingPane1.setPreferredSize(area);
drawingPane1.revalidate();
}
drawingPane1.repaint();
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
}

Mouse positon updating incorrectly

I'm trying to get the mouse position and light up a button when the curser is over it. However the mouse position isn't updating right. I think the y position is messed up because currently if i am far above the button it lights up.
Heres my code that is incorrect:
public void mouseMoved(MouseEvent e) {
Window.mse = new Point((e.getX()) + ((Frame.size.width - Window.myWidth)/2), (e.getY()) + (Frame.size.height - (Window.myHeight)/2));
}
This is the Window file:
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class Window extends JPanel implements Runnable {
public Thread thread = new Thread(this);
public static Image[] tileset_ground = new Image[100];
public static Image[] tileset_air = new Image[100];
public static Image[] tileset_resources = new Image[100];
public static int myWidth, myHeight;
public static boolean isFirst = true;
public static Point mse = new Point(0, 0);
public static Room room;
public static Levels levels;
public static Shop shop;
public Window(Frame frame) {
frame.addMouseListener(new KeyHandler());
frame.addMouseMotionListener(new KeyHandler());
thread.start();
}
public void define() {
room = new Room();
levels = new Levels();
shop = new Shop();
tileset_resources[0] = new ImageIcon("resources/cell.png").getImage();
levels.loadLevels(new File("levels/level1.level"));
for(int i=0;i<tileset_ground.length; i++) {
tileset_ground[i] = new ImageIcon("resources/tileset_ground.png").getImage();
tileset_ground[i] = createImage(new FilteredImageSource(tileset_ground[i].getSource(), new CropImageFilter(0, 32 * i, 32, 32)));
}
for(int i=0;i<tileset_air.length; i++) {
tileset_air[i] = new ImageIcon("resources/tileset_air.png").getImage();
tileset_air[i] = createImage(new FilteredImageSource(tileset_air[i].getSource(), new CropImageFilter(0, 32 * i, 32, 32)));
}
}
public void paintComponent(Graphics g) {
if(isFirst) {
myWidth = getWidth();
myHeight = getHeight();
define();
isFirst = false;
}
g.setColor(new Color(70, 70, 70));
g.fillRect(0, 0, myWidth, myHeight);
g.setColor(new Color(0, 0, 0));
g.drawLine(room.block[0][0].x, room.block[room.worldHeight - 1][0].y + room.blockSize, room.block[0][room.worldWidth - 1].x + room.blockSize, room.block[room.worldHeight - 1][0].y + room.blockSize);
g.drawLine(room.block[0][0].x, room.block[room.worldHeight - 1][0].y + 1 + room.blockSize, room.block[0][room.worldWidth - 1].x + room.blockSize, room.block[room.worldHeight - 1][0].y + 1 + room.blockSize);
room.draw(g); //Draws room
shop.draw(g); //Draws shop
}
public void run() {
while(true) {
if(!isFirst) {
room.physic();
}
repaint();
try {
Thread.sleep(1);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Simply add a MouseListener to the JButton. Or better still add a ChangeListener to the button's model, and in it, call isRollover() on the model.

Categories

Resources