Screen Size auto adjust - java

so currently I am in the process of making a game, and I want to make it easy so that all screen sizes can use it. But I don't know how to do this, currently I just have it set so the default resolution is 1600 x 900. If you guys know how I can make this adjustable for all sizes I would appreciate the help :)
I have look through all my code but I don't know what I have to do to make this work, if you need more information on my problem just ask.
Many thanks,
Ash
package net.captainash123.minitale;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Main extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
public static byte pixelSize = 5;
public static int moveFromBorder = 0;
public static double sX = moveFromBorder, sY = moveFromBorder;
public static double dir = 0;
public static int width = 1600;
public static int height = 900;
public int timer = 0;
public byte movingTimer = 0;
public static Dimension realSize;
public static Dimension size = new Dimension(1600, 900);
public static Dimension pixel = new Dimension(size.width / pixelSize, size.height / pixelSize);
public static Point mse = new Point(0, 0);
public static String name = "Minitale: Beta - 1.1.3";
public static String deathText = "You Died";
public static boolean isRunning = false;
public static boolean isMoving = false;
public static boolean isJumping = false;
public static boolean isMouseLeft = false;
public static boolean isMouseRight = false;
private Image screen;
public int FPS;
public int totalTime;
public static Level level;
public static Character character;
public static Inventory inventory;
public static CraftingTable craftingTable;
public static Sky sky;
public static Checker checker;
public static ArrayList<Mob> mob = new ArrayList<Mob>();
public Main() {
setPreferredSize(size);
addKeyListener(new Listening());
addMouseListener(new Listening());
addMouseMotionListener(new Listening());
addMouseWheelListener(new Listening());
}
public void start() {
requestFocus();
//Defining objects etc.
new Tile(); //Loading Images.
level = new Level();
character = new Character(Tile.tileSize, Tile.tileSize * 2);
inventory = new Inventory();
craftingTable = new CraftingTable();
Furnace furnace = new Furnace();
sky = new Sky();
checker = new Checker();
//mob.add(new Zombie(50, 10, Tile.tileSize, Tile.tileSize * 2, Tile.zombie));
//mob.add(new P2(60, 10, Tile.tileSize, Tile.tileSize * 2, Tile.P2));
//mob.add(new Turtle(40, 10, Tile.tileSize * 2, Tile.tileSize, Tile.turtle));
mob.add(new Chicken(40, 10, Tile.tileSize, Tile.tileSize, Tile.chicken));
mob.add(new Pig(60, 10, Tile.tileSize, Tile.tileSize, Tile.pig));
//Starting game loop.
isRunning = true;
new Thread(this).start();
}
public void stop() {
isRunning = false;
}
private static JFrame frame;
public static void main(String args[]) {
Main component = new Main();
frame = new JFrame();
frame.add(component);
frame.setIconImage(new ImageIcon("assets/textures/gui/gameIcon.png").getImage());
frame.pack();
realSize = new Dimension(frame.getWidth(), frame.getHeight());
frame.setTitle(name);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
component.start();
}
public void tick() {
if(frame.getWidth() != realSize.width || frame.getHeight() != realSize.height) {
frame.pack();
}
character.tick();
level.tick((int) sX, (int) sY, (pixel.width / Tile.tileSize) + 2, (pixel.height / Tile.tileSize) + 2);
sky.tick();
checker.tick();
craftingTable.checkRecipes();
Furnace.checkRecipes();
for(int i = 0; i < mob.toArray().length; i++) {
mob.get(i).tick();
}
}
public void render() {
Graphics g = screen.getGraphics();
//Drawing things. //102, 178, 255 blue sky.
sky.render(g);
level.render(g, (int) sX, (int) sY, (pixel.width / Tile.tileSize) + 2, (pixel.height / Tile.tileSize) + 2);
character.render(g);
for(int i = 0; i < mob.toArray().length; i++) {
mob.get(i).render(g);
}
inventory.render(g);
craftingTable.render(g);
Furnace.render(g);
if(character.isDead) {
g.setColor(Color.BLACK); //255, 0 ,0, 50
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
g.setFont(new Font("Calibri", Font.BOLD, 24));
g.drawString(deathText, 116, 150);
}
if(timer < 270) {
timer++;
movingTimer++;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
if(movingTimer > 10) {
}
if(movingTimer > 20){
movingTimer = 0;
}
g.setColor(new Color(108, 108, 108));
g.setFont(new Font("Calibri", Font.BOLD, 24));
g.drawString("Minitale", width / 16 + 16, height / 8 + 30);
g.drawImage(Tile.Splash, width / 32 + 34, height / 32 - 40, null);
}
g = getGraphics();
g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null);
g.dispose();
}
public void run() {
screen = createVolatileImage(pixel.width, pixel.height);
int frames = 0;
double nonProcessedSeconds = 0;
long previousTime = System.nanoTime();
double secondsPerTick = 1 / 60.0;
int tickCount = 0;
boolean hasTicked = false;
int totalTime = 0;
while(isRunning) {
long currentTime = System.nanoTime();
long passedTime = currentTime - previousTime;
previousTime = currentTime;
nonProcessedSeconds += passedTime / 1000000000.0;
while(nonProcessedSeconds > secondsPerTick) {
tick();
nonProcessedSeconds -= secondsPerTick;
hasTicked = true;
tickCount++;
if(tickCount % 60 == 0) {
previousTime += 1000;
FPS = frames;
frames = 0;
}
}
if(hasTicked) {
frames++;
}
frames++;
requestFocus();
tick();
render();
try {
Thread.sleep(5);
} catch(Exception e){ }
}
}
}

You can get the screen size with the Toolkit.getScreenSize() method.
See How can I get screen resolution in java?

Related

How do I create a frame with images to act as a tool tip in Java?

I've been struggling with an issue for 2 days now and I keep running into walls. When I mouse over a task on my first window I want another frame to pop up and display the images of available people on a roster that I could then click on to assign to the task I had moused over. I'm using Java.awt. I feel like this shouldn't be that hard but I can't get it to work. Any advice or help would be greatly appreciated.
MAIN CLASS
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private boolean isRunning = false;
private Thread thread;
private Handler handler;
public Game() {
new Window(1000, 800, "blah blah", this);
start();
handler = new Handler();
this.addMouseListener(new MouseInput(handler));
handler.addObject(new InterfaceElement(10, 10, ID.InterfaceElement, "C:\\Users\\cpaqu\\eclipse-workspace\\Expediter Game\\res\\Face.png"));
handler.addObject(new InterfaceElement(10, 500, ID.InterfaceElement, "C:\\Users\\cpaqu\\eclipse-workspace\\Expediter Game\\res\\MessageBox.png"));
Maintainer carl = new Maintainer("Carl", 0.75, "CommonMx.png");
Maintainer bill = new Maintainer("Bill", 1.0, "GoodMx.png");
Maintainer Max = new Maintainer("Max", 1.1, "RareMx.png");
Maintainer Sarah = new Maintainer("Sarah", 1.15, "LegendaryMx.png");
Maintainer Darius = new Maintainer("Darius", 1.25, "ExoticMx.png");
Task task = new Task(280, "OWS Warning Light");
handler.addObject(task);
task.setSlotOneMx(Max);
}
private void start() {
isRunning = true;
thread = new Thread(this);
thread.start();
}
private void stop() {
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(isRunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
frames = 0;
}
}
stop();
}
public void tick() {
handler.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
/////////////////////////////////////
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, 1000, 800);
handler.render(g);
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 24));
g.drawString("Launches in 15 minutes,", 60, 600);
g.drawString("get those B-men out to", 60, 630);
g.drawString("their spots!", 60, 660);
////////////////////////////////////
g.dispose();
bs.show();
}
public static void main(String[] args) {
new Game();
}
}
===============TASK CLASS====================
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Task extends GameObject{
private final int MAX_TASKS = 6;
private final double ticksPerSecond = 60.0;
private final double progressBarLength = 250.0;
private Maintainer slotOneMx = null;
private Maintainer slotTwoMx = null;
private static int numTasks = 0;
private double task_len_in_sec;
private double progress_per_second = 20;
private double completed_progress = 0.0;
private String name;
private int mxSize;
private int mxRows;
private String interfacePath = "C:\\Users\\cpaqu\\eclipse-workspace\\Expediter Game\\res\\TaskBG.png";
private String progressPath = "C:\\Users\\cpaqu\\eclipse-workspace\\Expediter Game\\res\\ProgressBar.png";
private String NoMxPath = "C:\\Users\\cpaqu\\eclipse-workspace\\Expediter Game\\res\\NoMx.png";
private BufferedImage interfaceImage = null;
private BufferedImage progressImage = null;
private BufferedImage NoMxImage = null;
// private Frame frame;
private ArrayList<Maintainer> workers;
private BufferedImage[] icons;
BufferedImageLoader loader;
public Task(double taskLen, String name) {
super(465, 15, ID.Task);
// frame = new Frame();
// frame.setVisible(true);
// frame.setBounds(200, 200, (74 * 4) + (15 * 5), (mxRows * 80) + 30);
loader = new BufferedImageLoader();
mxSize = Maintainer.getMxQty();
mxRows = mxSize / 4;
icons = new BufferedImage[10];
y = y + (Task.numTasks * 115);
Task.numTasks++;
this.task_len_in_sec = taskLen;
this.name = name;
interfaceImage = loader.loadImage(interfacePath);
progressImage = loader.loadImage(progressPath);
NoMxImage = loader.loadImage(NoMxPath);
}
public void tick() {
if (completed_progress / task_len_in_sec <= 1.0) { completed_progress += (progress_per_second / ticksPerSecond); }
// workers = Maintainer.getMaintainers();
// mxSize = Maintainer.getMxQty();
// mxRows = (mxSize % 4 == 0) ? mxSize / 4 : ((mxSize / 4) + 1);
// frame.setTitle(Integer.toString(mxSize) + " - " + Integer.toString(mxRows));
}
public void render(Graphics g) {
g.drawImage(interfaceImage, x, y, null);
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 24));
g.drawString(name, x+20, y+30);
if (slotOneMx == null) {
g.drawImage(NoMxImage, x+302, y+14, null);
} else {
g.drawImage(loader.loadImage(slotOneMx.getImagePath()), x+302, y+14, null);
}
if (slotTwoMx == null) {
g.drawImage(NoMxImage, x+397, y+15, null);
} else {
g.drawImage(loader.loadImage(slotTwoMx.getImagePath()), x+397, y+15, null);
}
g.drawImage(progressImage, x+29, y+53, (int) (progressBarLength * (completed_progress / task_len_in_sec)), 20, null);
}
public void setSlotOneMx(Maintainer mx) {
slotOneMx = mx;
}
public void setSlotTwoMx(Maintainer mx) {
slotTwoMx = mx;
}
public Rectangle getBounds() {
return null;
}
public int getNumTasks() {
int x = numTasks;
return x;
}
}
I would HIGHLY recommend you moving to Swing or JavaFX. I don't know about raw AWT, but Swing can interpret HTML, so an easy way to get image tooltips is to embed HTML:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("This is a task");
label.setToolTipText("<html><img src=\"file:/path/to/image\"></html>");
label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

Java - MouseListener Does Not Work

I have been trying to create a functional button for a basic Java game, but whenever I click on the screen (literally anywhere within or out of the parameters I have), there is no function in my game. I am trying to figure out where I have my conflict that the mouse event is not working. I have double and triple checked almost everything and I cannot find the issue. I included the Game Class and Menu class but if the other Classes are needed I will post them. I also know that the code is most likely very sloppy and improper, but I am just learning and trying to teach myself some of the basics.
Is the problem with the "STATE" enum I created?
Can the issue be somewhere within the boolean mouseOver?
I am super confused and don't understand where exactly I am messing up on this. I want to be able to have the functionality I need for the game. Sorry if this is a really basic question or the code is horrible, I'll take any help you can offer.
package com.test.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 5348695609807625849L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Random r;
private Handler handler;
private HUD hud;
private Spawn spawner;
private Menu menu;
public enum STATE {
Menu,
Game
};
public STATE gameState = STATE.Menu;
public Game(){
handler = new Handler();
menu = new Menu(this, handler);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "GafGin", this);
hud = new HUD();
spawner = new Spawn(handler, hud);
r = new Random();
if(gameState == STATE.Game) {
handler.addObject(new Player(WIDTH/2-32, HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, handler));
}
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try {
thread.join();
running = false;
}catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
gameOver();
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer+= 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
private void tick() {
handler.tick();
if(gameState == STATE.Game) {
hud.tick();
spawner.tick();
}else if(gameState == STATE.Menu) {
menu.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
if(gameState == STATE.Game) {
hud.render(g);
}else if(gameState == STATE.Menu) {
menu.render(g);
}
g.dispose();
bs.show();
}
public static float clamp(float var, float min, float max) {
if(var >= max)
return (var = max);
else if(var <= min)
return (var = min);
else
return var;
}
public void gameOver() {
if(HUD.HEALTH <= 0) {
handler.endGame();
}
checkRunning();
}
public void checkRunning() {
if(Handler.getGameEnded() == true) {
running = false;
}
}
public static void main(String[] args) {
new Game();
}
}
package com.test.main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import com.test.main.Game.STATE;
public class Menu extends MouseAdapter{
private Game game;
private Handler handler;
private Random r = new Random();
public Menu(Game game, Handler handler) {
this.game = game;
this.handler = handler;
}
public void MousePressed(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(mouseOver(mx, my, (Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) - 64, 250, 64)){
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH/2-32, Game.HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, handler));
}
if(mouseOver(mx, my, 100, 100, 250, 64)) {
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH/2-32, Game.HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, handler));
}
}
public void MouseReleased(MouseEvent e) {
}
private boolean mouseOver(int mx, int my, int x, int y, int width, int height) {
if(mx > x && mx < x + width) {
if(my > y && my < y + height) {
return true;
}else return false;
}else return false;
}
public void tick() {
}
public void render(Graphics g) {
Font fnt = new Font("arial", 1, 50);
Font fnt2 = new Font("arial", 1, 30);
g.setColor(Color.white);
g.drawRect(100, 100, 250, 64);
g.setFont(fnt);
g.setColor(Color.white);
g.drawString("Menu", (Game.WIDTH / 2) - 85, (Game.HEIGHT / 2) - 124);
g.setFont(fnt2);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) - 64, 250, 64);
g.drawString("Play", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) - 22);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2), 250, 64);
g.drawString("Quit", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) + 42);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) + 64, 250, 64);
g.drawString("Help", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) + 106);
}
}

I am creating a 2d game, i am trying to import some fonts but i keep getting the error

package aaron.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.*;
import javax.swing.JFrame;
import aaron.game.gfx.Colours;
import aaron.game.gfx.Font;
import aaron.game.gfx.Screen;
import aaron.game.gfx.SpriteSheet;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private int[] colours = new int[6*6*6];
private Screen screen;
public InputHandler input;
public Game(){
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void init(){
int index = 0;
for(int r = 0;r<6;r++){
for(int g = 0;g<6;g++){
for(int b = 0;b<6;b++){
int rr= (r*255/5);
int gg= (g*255/5);
int bb= (b*255/5);
colours[index++] = rr<<16| gg<<8 | bb;
}
}
}
screen = new Screen(WIDTH, HEIGHT, new SpriteSheet("/sprite_sheet.png"));
input = new InputHandler(this);
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D/60D;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
init();
while (running){
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = true;
while(delta >= 1){
ticks++;
tick();
delta -= 1;
shouldRender = true;}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender){
frames++;
render();
}
if(System.currentTimeMillis() - lastTimer >= 1000){
lastTimer += 1000;
System.out.println(ticks + " ticks, " + frames + " frames");
frames = 0;
ticks = 0;
}
}
}
public void tick(){
tickCount++;
if(input.up.isPressed()){screen.yOffset--;}
if(input.down.isPressed()){screen.yOffset++;}
if(input.left.isPressed()){screen.xOffset--;}
if(input.right.isPressed()){screen.xOffset++;}
for (int i = 0; i < pixels.length; i++){
pixels[i] = i + tickCount;
}
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if (bs == null){
createBufferStrategy(3);
return;
}
for(int y=0;y<32;y++){
for(int x=0;x<32;x++){
boolean flipX = x%2==1;
boolean flipY = y%2==1;
screen.render(x<<3, y<<3, 0, Colours.get(555,505,055,550), flipX, flipY);
}
}
// Font.render("Hello Wolrd! 0157", screen, 0, 0, Colours.get(000, -1, -1, 555));
for(int y=0;y<screen.height;y++){
for(int x=0;x<screen.width;x++){
int colourCode=screen.pixels[x+y*screen.width];
if(colourCode<255)pixels[x+y*WIDTH]=colours[colourCode];
}
}
Graphics g = bs.getDrawGraphics();
//g.setColor(Color.BLACK);
//g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args){
new Game().start();
}
}
^This is my main class [ // Font.render("Hello Wolrd! 0157", screen, 0, 0, Colours.get(000, -1, -1, 555));] < this is where i am getting the error...
package aaron.game.gfx;
public class Font {
private static String chars = "" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ " + "0123456789.,:;'\"!?$%()-=+/ ";
public static void render(String msg, Screen screen, int x, int y, int colour, int scale) {
msg = msg.toUpperCase();
for (int i = 0; i < msg.length(); i++) {
int charIndex = chars.indexOf(msg.charAt(i));
if (charIndex >= 0) screen.render(x + (i * 8), y, charIndex + 30 * 32, colour, false, false);
}
}
}
This is the class for reading my fonts
package aaron.game.gfx;
public class Screen {
public static final int MAP_WIDTH = 64;
public static final int MAP_WIDTH_MASK = MAP_WIDTH - 1;
public int[]pixels;
public int xOffset = 0;
public int yOffset = 0;
public int width;
public int height;
public SpriteSheet sheet;
public Screen(int width, int height, SpriteSheet sheet){
this.width = width;
this.height = height;
this.sheet = sheet;
pixels=new int[width * height];
}
public void render(int xPos, int yPos, int tile, int colour){
render(xPos, yPos, tile, colour, false, false);
}
public void render(int xPos, int yPos, int tile, int colour, boolean mirrorX, boolean mirrorY){
xPos -= xOffset;
yPos -= yOffset;
int xTile = tile %32;
int yTile = tile /32;
int tileOffset=(xTile<<3)+(yTile<<3)*sheet.width;
for(int y=0;y<8;y++){
if(y+yPos<0 || y+yPos>=height)continue;
int ySheet = y;
if(mirrorY) ySheet = 7 - y;
for(int x=0;x<8;x++){
if(x+xPos<0 || x+xPos>=width)continue;
int xSheet = x;
if(mirrorX) xSheet = 7 - x;
int col=(colour>>(sheet.pixels[xSheet+ySheet*sheet.width+tileOffset]*8))&255;
if(col<255) pixels[(x+xPos)+(y+yPos)*width]=col;
}
}
}
}
This is my display class, anyway this error is killing me and i hae no idea how to fix it whatsoever, I have looked all over the place bot a single place, the error i am getting is
The method render(String, Screen, int, int, int, int) in the type Font is not applicable for the arguments (String, Screen, int, int, int)
Try cleaning and rebuilding the project. It seems like an older version of the program is being run...

CardLayout showing two panels, flashing

I'm trying to use CardLayout to show two JPanels, a main menu, and a controls screen. When I add two JPanels to my cards JPanel, it just shows two with flashing images. Here is my code:
package main;
public class MazeGame {
// Layout
public static JPanel cards = new JPanel();
// Window
public static JFrame window;
public static String windowLabel = "2D Maze Game - Before Alpha";
// Window Dimensions and Location
public static int WIDTH = 600;
public static int HEIGHT = 600;
public static Component center = null;
public static int exit = 3;
public static void main(String[] args) {
window = new JFrame(windowLabel);
window.setSize(new Dimension(WIDTH, HEIGHT));
window.setResizable(false);
window.setLocationRelativeTo(center);
window.setDefaultCloseOperation(exit);
cards.setLayout(new CardLayout());
cards.add(new MazeGamePanel(), "main");
cards.add(new MazeControlsPanel(), "controls");
window.add(cards);
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, "main");
window.setVisible(true);
}
}
MazeGamePanel:
public class MazeGamePanel extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
// Timer
public Timer timer;
// Font
public Font bitTrip;
public Thread thread;
public BufferedImage canvas;
public Graphics2D g;
public boolean running;
public int HEIGHT = MazeGame.HEIGHT;
public int WIDTH = MazeGame.WIDTH;
public int FPS = 30;
public int opacity = 255;
public int selectedOption = 0;
public String option1 = "Play";
public String option2 = "Controls";
public String option3 = "Quit";
public MazeGamePanel() {
this.setFocusable(true);
this.requestFocus();
addKeyListener(new MazeGameKeyListener());
try {
bitTrip = Font.createFont(Font.TRUETYPE_FONT, new File(
"res/font/BitTrip7.TTF"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
/**
ActionListener action = new ActionListener () {
public void actionPerformed (ActionEvent e) {
if(opacity != 0) {
opacity--;
} else {
timer.stop();
opacity = 0;
}
}
};
timer = new Timer(10, action);
timer.setInitialDelay(0);
timer.start();
*/
}
public void addNotify() {
super.addNotify();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
running = true;
canvas = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) canvas.getGraphics();
long startTime = 0;
long millis = 0;
long waitTime = 0;
long targetTime = 1000 / FPS;
while (running) {
startTime = System.nanoTime();
update();
render();
draw();
millis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - millis;
try {
Thread.sleep(waitTime);
} catch (Exception e) {
}
}
}
// TODO
public void render() {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
bitTrip = bitTrip.deriveFont(40F);
g.setFont(bitTrip);
if (selectedOption == 0) {
//Play
g.setColor(Color.BLACK);
g.drawString(option1, WIDTH / 2 - 200, HEIGHT / 2);
//Controls
g.setColor(Color.GRAY);
g.drawString(option2, WIDTH / 2 - 200, HEIGHT / 2 + 50);
//Quit
g.setColor(Color.GRAY);
g.drawString(option3, WIDTH / 2 - 200, HEIGHT / 2 + 100);
} else if (selectedOption == 1) {
//Play
g.setColor(Color.GRAY);
g.drawString(option1, WIDTH / 2 - 200, HEIGHT / 2);
//Controls
g.setColor(Color.BLACK);
g.drawString(option2, WIDTH / 2 - 200, HEIGHT / 2 + 50);
//Quit
g.setColor(Color.GRAY);
g.drawString(option3, WIDTH / 2 - 200, HEIGHT / 2 + 100);
} else if (selectedOption == 2) {
//Play
g.setColor(Color.GRAY);
g.drawString(option1, WIDTH / 2 - 200, HEIGHT / 2);
//Controls
g.setColor(Color.GRAY);
g.drawString(option2, WIDTH / 2 - 200, HEIGHT / 2 + 50);
//Quit
g.setColor(Color.BLACK);
g.drawString(option3, WIDTH / 2 - 200, HEIGHT / 2 + 100);
}
//g.setColor(new Color(0, 0, 0, opacity));
//g.fillRect(0, 0, WIDTH, HEIGHT);
}
public void update() {
}
public void draw() {
Graphics g2 = this.getGraphics();
g2.drawImage(canvas, 0, 0, null);
g2.dispose();
}
private class MazeGameKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (selectedOption == 1) {
selectedOption = 0;
} else if (selectedOption == 2) {
selectedOption = 1;
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (selectedOption == 0) {
selectedOption = 1;
} else if (selectedOption == 1) {
selectedOption = 2;
}
}
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(selectedOption == 1) {
MazeGame.window.removeAll();
MazeGame.window.add(new MazeControlsPanel());
MazeGame.window.validate();
}
}
}
}
}
MazeControlsPanel:
package screens;
public class MazeControlsPanel extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
// Font
public Font bitTrip;
public Thread thread;
public BufferedImage canvas;
public Graphics2D g;
public boolean running;
public int HEIGHT = MazeGame.HEIGHT;
public int WIDTH = MazeGame.WIDTH;
public int FPS = 30;
public int opacity = 255;
public int selectedOption = 0;
public MazeControlsPanel() {
this.setFocusable(true);
this.requestFocus();
addKeyListener(new MazeControlsKeyListener());
try {
bitTrip = Font.createFont(Font.TRUETYPE_FONT, new File(
"res/font/BitTrip7.TTF"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
/**
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (opacity != 0) {
opacity--;
} else {
timer.cancel();
opacity = 0;
}
}
}, 0, 4);
*/
}
public void addNotify() {
super.addNotify();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
running = true;
canvas = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) canvas.getGraphics();
long startTime = 0;
long millis = 0;
long waitTime = 0;
long targetTime = 1000 / FPS;
while (running) {
startTime = System.nanoTime();
update();
render();
draw();
millis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - millis;
try {
Thread.sleep(waitTime);
} catch (Exception e) {
}
}
}
// TODO
public void render() {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
bitTrip = bitTrip.deriveFont(40F);
g.setFont(bitTrip);
// Quit
g.setColor(Color.BLACK);
g.drawString("Main Menu", WIDTH / 2 - 200, HEIGHT / 2 + 100);
//g.setColor(new Color(0, 0, 0, opacity));
//g.fillRect(0, 0, WIDTH, HEIGHT);
}
public void update() {
}
public void draw() {
Graphics g2 = this.getGraphics();
g2.drawImage(canvas, 0, 0, null);
g2.dispose();
}
private class MazeControlsKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
}
}
Here's a problem:
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
Don't use a java.util.Timer in a Swing program as you will have threading problems. Instead use a Swing Timer.
Also, you're making Swing calls in background threads and using Graphics object obtained by calling getGraphics() on a component, two no-nos for Swing programs.
EDIT
Here is a program that I worked on that swaps components with a CardLayout, but fades one component out as it fades the other one in. What it does:
The program adds all the swapping components to the CardLayout using JPanel.
It also adds a single SwappingImgPanel, a JPanel created to draw two images, one of the component that is fading out, and one of the component that is fading in.
When you swap components, you create images of the two components, the one currently visible, and the one that will next be visible.
You send the images to the SwappingImgPanel instance
You call swap() on the SwappingImgPanel instance.
The SwappingImgPanel will then draw both images but uses a Swing Timer to change the Graphic object's composite value. This is what causes an image to be partially visible.
When the SwappingImgPanel's Timer is done, a done() method is called which sets the SwappingImgPanel's State to State.DONE.
The main GUI is listening to the SwappingImgPanel's state value, and when it achieves State.DONE, the main GUI shows the actual next component (and not an image of it).
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class DimmingPanelSwaps extends JPanel {
private static final int DELTA_TIME = 10;
private static final int ELAPSED_TIME = 3000;
private static final String SWAPPING_IMG_PANEL = "swapping img panel";
private CardLayout cardlayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardlayout);
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> cardCombo = new JComboBox<>(comboModel);
private Map<String, JComponent> componentMap = new HashMap<String, JComponent>();
private String key = "";
private SwappingImgPanel swappingImgPanel = new SwappingImgPanel(DELTA_TIME, ELAPSED_TIME);
public DimmingPanelSwaps() {
registerComponent(createComponentOne(), "one");
registerComponent(createComponentTwo(), "two");
registerComponent(createComponentThree(), "three");
registerComponent(createComponentFour(), "four");
key = "one";
cardHolderPanel.add(swappingImgPanel, SWAPPING_IMG_PANEL);
JPanel southPanel = new JPanel();
southPanel.add(cardCombo);
setLayout(new BorderLayout());
add(cardHolderPanel, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
swappingImgPanel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getNewValue() == State.DONE) {
cardlayout.show(cardHolderPanel, key);
cardCombo.setEnabled(true);
}
}
});
cardCombo.addActionListener(new CardComboListener());
}
private JPanel createComponentFour() {
int rows = 4;
int cols = 4;
int gap = 5;
int tfColumns = 8;
JPanel panel = new JPanel(new GridLayout(rows, cols, gap, gap));
for (int i = 0; i < rows * cols; i++) {
JTextField textField = new JTextField(tfColumns);
JPanel tfPanel = new JPanel();
tfPanel.add(textField);
panel.add(tfPanel);
}
return panel;
}
private JLabel createComponentThree() {
int biWidth = 200;
BufferedImage img = new BufferedImage(biWidth, biWidth, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, Color.red, 20, 20, Color.blue, true));
g2.fillOval(0, 0, biWidth, biWidth);
g2.dispose();
Icon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
return label;
}
private JScrollPane createComponentTwo() {
JTextArea textArea = new JTextArea(15, 40);
JScrollPane scrollpane = new JScrollPane(textArea);
scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
return scrollpane;
}
private JPanel createComponentOne() {
JPanel innerPanel = new JPanel(new GridLayout(1, 0, 5, 0));
String[] btnTitles = {"One", "Two", "Three"};
for (String btnTitle : btnTitles) {
JButton btn = new JButton(btnTitle);
innerPanel.add(btn);
}
JPanel panel = new JPanel(new GridBagLayout());
panel.add(innerPanel);
return panel;
}
#SuppressWarnings("hiding")
private void registerComponent(JComponent jComp, String key) {
cardHolderPanel.add(jComp, key);
componentMap.put(key, jComp);
comboModel.addElement(key);
}
private class CardComboListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
final String oldKey = key;
key = (String) cardCombo.getSelectedItem();
cardCombo.setEnabled(false);
final JComponent firstComp = componentMap.get(oldKey);
final BufferedImage firstImg = extractComponentImg(firstComp);
final JComponent secondComp = componentMap.get(key);
final BufferedImage secondImg = extractComponentImg(secondComp);
cardlayout.show(cardHolderPanel, SWAPPING_IMG_PANEL);
swappingImgPanel.setFirstImg(firstImg);
swappingImgPanel.setSecondImg(secondImg);
swappingImgPanel.swap();
}
private BufferedImage extractComponentImg(final JComponent component) {
Dimension size = component.getSize();
BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
component.paint(g2);
g2.dispose();
return img;
}
}
private static void createAndShowGui() {
DimmingPanelSwaps mainPanel = new DimmingPanelSwaps();
JFrame frame = new JFrame("Dimming Panel Swaps");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
/**
* A JPanel that draws two images
* When swap is called, the first image is shown
* Then a Timer dims the first image while it reveals
* the second image.
* When the elapsed time is complete, it sets its state to State.DONE.
* #author Pete
*
*/
#SuppressWarnings("serial")
class SwappingImgPanel extends JPanel {
public static final String STATE = "state";
private BufferedImage firstImg;
private BufferedImage secondImg;
private int deltaTime;
private int elapsedTime;
// state is a "bound" property, one that is listened to via PropertyChangeSupport
private State state = State.PENDING;
private float alpha1;
private float alpha2;
public SwappingImgPanel(final int deltaTime, final int elapsedTime) {
this.deltaTime = deltaTime;
this.elapsedTime = elapsedTime;
}
public void swap() {
setState(State.STARTED);
if (firstImg == null || secondImg == null) {
done();
}
alpha1 = 1.0f;
alpha2 = 0.0f;
new Timer(deltaTime, new ActionListener() {
private int counter = 0;
private int max = elapsedTime / deltaTime;
#Override
public void actionPerformed(ActionEvent e) {
if (counter >= elapsedTime / deltaTime) {
((Timer)e.getSource()).stop();
done();
return;
}
// set new alpha composite values
alpha1 = ((float)max - counter) / (float) max;
alpha2 = (float) counter / (float) max;
// make sure alphas are within bounds
alpha1 = Math.min(1f, alpha1);
alpha1 = Math.max(0f, alpha1);
alpha2 = Math.min(1f, alpha2);
alpha2 = Math.max(0f, alpha2);
repaint();
counter++;
}
}).start();
}
private void done() {
firstImg = null;
secondImg = null;
setState(State.DONE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (firstImg == null || secondImg == null) {
return;
}
// create a new Graphics2D object with g.create()
// to avoid any possible side effects from changing the
// composite of the JVM's Graphics object
Graphics2D g2 = (Graphics2D) g.create();
// set the first alpha composite, and draw the image
g2.setComposite(((AlphaComposite)g2.getComposite()).derive(alpha1));
g2.drawImage(firstImg, 0, 0, this);
// set the second alpha composite, and draw the image
g2.setComposite(((AlphaComposite)g2.getComposite()).derive(alpha2));
g2.drawImage(secondImg, 0, 0, this);
g2.dispose(); // can get rid of this Graphics because we created it
}
public void setFirstImg(BufferedImage firstImg) {
this.firstImg = firstImg;
}
public void setSecondImg(BufferedImage secondImg) {
this.secondImg = secondImg;
}
public State getState() {
return state;
}
public void setState(State state) {
State oldValue = this.state;
State newValue = state;
this.state = state;
firePropertyChange(STATE, oldValue, newValue);
}
}
/**
* Modeled on SwingWorker.StateValue
* #author Pete
*
*/
enum State {
PENDING, STARTED, DONE
}

Drawing pictures in JFRame

) please help to solve the problem. I'm doing a little game and paint it a coin) to the player went and gathered them.
Here's how the process of gathering (that's code):
if (x + w3 == 190) {
coins++;
mon = null;
} else {
g.drawImage(mon, 190 - x, 265, wm, hm, this);
}
Where 190 - is the position where the coin
Where x + w3 the coordinates of the player
That is, when the coordinates of touch coin disappear,but along with this coin disappear, and others, in fact - mon = null;
What should I do? really for each coin to make your picture?
thanks in advance.
UPD
All Code:
package GameTs;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
public static final String NAME = "DrakGo Game";
public static final int WIDTH = 500;
public static final int HEIGHT = 460;
private static final int MAP_SIZE_X = 100;
private Image img;
private Image img2;
private Image mon;
private Image mon2;
private Image mon3;
private Image pl;
private Image mag;
private Image drak;
private Input input = new Input(this);
static JFrame frame;
static int x = 0;
int y = 0;
int xp = 110;
int yp = 180;
int coins = 0;
URL url4;
URL url7;
public Game() {
URL url2 = getClass().getResource("images/Grass.png");
img = Toolkit.getDefaultToolkit().getImage(url2);
URL url = getClass().getResource("images/Cloud.png");
img2 = Toolkit.getDefaultToolkit().getImage(url);
URL url3 = getClass().getResource("images/Mon.png");//THIS
mon = Toolkit.getDefaultToolkit().getImage(url3);
mon2 = Toolkit.getDefaultToolkit().getImage(url3);//THIS
mon3 = Toolkit.getDefaultToolkit().getImage(url3);//THIS
url4 = getClass().getResource("images/Right_Pic1.png");
URL url5 = getClass().getResource("images/Mag.png");
URL url6 = getClass().getResource("images/Dr.png");
url7 = getClass().getResource("images/Right_Pic2.png");
pl = Toolkit.getDefaultToolkit().getImage(url4);
mag = Toolkit.getDefaultToolkit().getImage(url5);
drak = Toolkit.getDefaultToolkit().getImage(url6);
}
public void paint(Graphics g) {
render(g);
repaint();
}
private void move(Graphics g) {
/*
* if (input.left) { x--; if (x == -1) { x++; }
*
* }
*/
if (input.right) {
x++;
if (x == -1) {
x--;
}
if ((x % 2) == 0) {
pl = Toolkit.getDefaultToolkit().getImage(url7);
} else {
pl = Toolkit.getDefaultToolkit().getImage(url4);
}
}
}
public void render(Graphics g) {
super.paint(g);
move(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 500, 360);
int w = 180;
int h = 180;
for (int i = 0; i < MAP_SIZE_X * 2; i++) {
g.drawImage(img, i * w - x, 260, (int) w, (int) h, this);
}
int w2 = 90;
int h2 = 50;
for (int c = 0; c < MAP_SIZE_X * 100; c += 200) {
g.drawImage(img2, 100 + c - x, 70, w2, h2, this);
}
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
Font[] allFonts = ge.getAllFonts();
Font font = allFonts[4].deriveFont(30.0F);
g.setFont(font);
g.setColor(Color.DARK_GRAY);
g.drawString("DrakGo - Game", 10, 40);
g.drawString("X: " + x, 300, 40);
g.drawString("Coins: " + coins, 400, 40);
int w3 = 50;
int h3 = 50;
int wm = 30;
int hm = 30;
if (x + w3 == 190) {
coins++;
mon = null;
} else {
g.drawImage(mon, 190 - x, 265, wm, hm, this);
}
//THIS!!!!!!!
if (x + w3 == 350) {
coins++;
mon2 = null;
} else {
g.drawImage(mon2, 350 - x, 265, wm, hm, this);
}
if (x + w3 == 650) {
coins++;
mon3 = null;
} else {
g.drawImage(mon3, 650 - x, 265, wm, hm, this);
}
int w4 = 50;
int h4 = 50;
if (x + w3 == 3500) {
drak = null;
} else {
g.drawImage(drak, 3500 - x, 260, w4, h4, this);
}
g.drawImage(mag, 1000 - x, 260, w3, h3, this);
g.drawImage(pl, 0, 260, w3, h3, this);
}
public static void main(String[] args) {
Game game = new Game();
game.setSize(WIDTH, HEIGHT);
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.add(game);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
}
}
Remove this:
public void paint(Graphics g) {
render(g);
repaint();
}
Instead use this:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
render(g);
}
Also change:
public void render(Graphics g) {
super.paint(g);
move(g);
// ..
To:
public void render(Graphics g) {
move(g);
// ..
Both methods as they were, would tend to cause an infinite loop.

Categories