IllegalStateException thrown when trying to run my Game Launcher - java

I'm trying to launch a Game launcher and it was working fine until yesterday (I had most of the code written already) and then it just starts throwing Illegal state exceptions all over the place like theres no tomorrow.
And I for the life of me cannot figure out the solution :(
So this is my code:
package com.MHafi.Pandora.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import com.MHafi.Pandora.Configuration;
import com.MHafi.Pandora.Display;
import com.MHafi.Pandora.RunGame;
import com.MHafi.Pandora.input.InputHandler;
public class Launcher extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private JFrame frame = new JFrame();
Configuration config = new Configuration();
private int width = 800;
private int height = 390;
protected int button_width = 80;
protected int button_height = 39;
boolean running = false;
Thread thread;
private BufferedImage img;
public Launcher(int id) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
frame.setUndecorated(true);
frame.setTitle(Display.TITLE + " Launcher");
frame.setSize(new Dimension(width, height));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().add(window);
//frame.add(this);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
window.setLayout(null);
System.out.println("YAY");
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
startMenu();
frame.repaint();
}
public void updateFrame() {
if (InputHandler.dragged) {
Point p = frame.getLocation();
int x = frame.getX();
int y = frame.getY();
frame.setLocation (x + InputHandler.MouseDX - InputHandler.MousePX, y + InputHandler.MouseDY - InputHandler.MousePY);
}
}
public void startMenu() {
running = true;
thread = new Thread(this, "menu");
thread.start();
}
public void stopMenu() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
requestFocus();
while (running) {
renderMenu();
updateFrame();
}
}
private void renderMenu() throws IllegalStateException {
System.out.println("1");
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
System.out.println("2");
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 390);
System.out.println("3");
try {
g.drawImage(ImageIO.read(Launcher.class.getResource("/Launcher.png")), 0, 0, 800, 390, null);
System.out.println("4");
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 110 && InputHandler.MouseY < 110 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/play_on.png")), 50, 110, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 118, 30, 14, null);
if (InputHandler.MouseButton == 1) {
config.loadConfiguration("res/config/config.xml");
dispose();
new RunGame();
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/play_off.png")), 50, 110, 60, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 140 && InputHandler.MouseY < 140 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Options_on.png")), 50, 141, 100, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 155, 149, 30, 14, null);
if (InputHandler.MouseButton == 1) {
System.out.println("Options");
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Options_off.png")), 50, 140, 100, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 175 && InputHandler.MouseY < 175 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Help_on.png")), 50, 175, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 183, 30, 14, null);
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Help_off.png")), 50, 175, 60, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 210 && InputHandler.MouseY < 210 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Quit_on.png")), 50, 210, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 218, 30, 14, null);
if (InputHandler.MouseButton == 1) {
System.exit(0);
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Quit_off.png")), 50, 210, 60, 30, null);
}
} catch (IOException e) {
e.printStackTrace();
}
g.dispose();
bs.show();
}
}
And here is the error thrown:
YAY
1
Exception in thread "menu" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.<init>(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Window.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Window.createBufferStrategy(Unknown Source)
So what's going on?
Why can't I create a BufferStrategy?

Well, a problem I see here is this call createBufferStrategy(3) in the renderMenu method. The method createBufferStrategy can cause such exceptions if the JFrame (or to be more general, the Window) wasn't set visible before (or added to a component that is visible) as you can see in the JavaDoc.
I see two ways to fix it:
think about the purpose of private JFrame frame and if you should use this instead, since Launcher is a JFrame itself (you're setting frame as visible, not the Launcher instance)
change this.getBufferStrategy() and createBufferStrategy(3) to frame.getBufferStrategy() and frame.createBufferStrategy(3)
If you used the second idea, then also think about removing JFrame as the parent class for Launcher, because it creates an own JFrame instance, instead of using "himself" as the JFrame.

Related

Problems with getClass().getResourceAsStream()

I am making a project with a graphics environment which uses buffered images from files. I searched and the way I was using (Java.IO file) wouldn't work after exporting the jar, and the way to do it was with getClass().getResourceAsStream() but I'm having troubles figuring out filepath
here is my files at eclipse-IDE:
some people said I should move my resources folder inside the src
but I still don't know what would be the text for a image1.png inside of res
I did try searching and implementing but that gave me the errors:
https://pastebin.com/MChSyWH5
here is how the class I'm trying to draw the images is without implementing getClass().getResourceAsStream() :
package src;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class Menu {
public Rectangle Playbutton = new Rectangle( Game.WIDTH/2-25, 60, 50, 10);
public Rectangle Exitbutton = new Rectangle( Game.WIDTH/2-25, 80, 50, 10);
public static String desc = null;
private BufferedImage imagePlay;
private BufferedImage players1;
private BufferedImage players2;
private BufferedImage imageExit;
private BufferedImage IMPOSSIBLE;
private BufferedImage Hard;
private BufferedImage Easy;
private BufferedImage Normal;
private BufferedImage imageTitle;
private BufferedImage imageResume;
private BufferedImage imageMain;
private BufferedImage OPTIONS;
private BufferedImage BACK;
public static int brightloss = 0;
public static int stibaum = 0;
public static boolean sti = true;
public static boolean showc = false;
public static enum STATE{
MAIN,
P1P2,
INGAME,
DIFICULTY,
OPTIONS
};
public static STATE State = STATE.MAIN;
InputStream input = null;
public static STATE Statepre = State;
public static boolean dark = true;
public static Slider slider;
public static void SAVESTATE(){
Statepre = State;
}
public Menu() {
try {
input = new FileInputStream("res/Playbutt.png");
} catch (IOException e) {
e.printStackTrace();
}
String current;
try {
current = new java.io.File( "." ).getCanonicalPath();
System.out.println("Current dir:"+current);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" +currentDir);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
slider = new Slider(100, 100, 50, false, brightloss);
System.out.println(new File("res/Playbutt.png").getAbsolutePath()+"-arquivo");
System.out.println(new File("/res/Playbutt.png").exists()+"-arquivo2");
try { // ImageIO.read(new File("res/Playbutt.png"));
imagePlay = ImageIO.read(input);
IMPOSSIBLE = ImageIO.read(new File("res/IMPOSSIbutt.png"));
Hard = ImageIO.read(new File("res/Hardbutt.png"));
Easy = ImageIO.read(new File("res/Easybutt.png"));
Normal = ImageIO.read(new File("res/Normalbutt.png"));
players1 = ImageIO.read(new File("res/1P.png"));
players2 = ImageIO.read(new File("res/2P.png"));
imageExit = ImageIO.read(new File("res/Exitbutt.png"));
imageTitle = ImageIO.read(new File("res/Title.png"));
imageResume = ImageIO.read(new File("res/Resumebutt.png"));
imageMain = ImageIO.read(new File("res/Mainbutt.png"));
OPTIONS = ImageIO.read(new File("res/Optbutt.png"));
BACK = ImageIO.read(new File("res/Backbutt.png"));
} catch (IOException ex) {
// handle exception...
}
}
public void render(Graphics g) {
g.setFont(new Font("DefaultFont", Font.PLAIN, 10));
g.setColor(Colors.Trans_GREEN3);
g.fillRect(0, Game.HEIGHT-10, Game.WIDTH,10);
g.fillRect(0, Game.HEIGHT-9, Game.WIDTH,9);
g.fillRect(0, Game.HEIGHT-8, Game.WIDTH,8);
g.fillRect(0, Game.HEIGHT-7, Game.WIDTH,7);
g.fillRect(0, Game.HEIGHT-6, Game.WIDTH,6);
g.fillRect(0, Game.HEIGHT-5, Game.WIDTH,5);
g.setColor(Colors.Trans_GREEN3);
g.fillRect(0, 0, Game.WIDTH,10);
g.fillRect(0, 0, Game.WIDTH,9);
g.fillRect(0, 0, Game.WIDTH,8);
g.fillRect(0, 0, Game.WIDTH,7);
g.fillRect(0, 0, Game.WIDTH,6);
g.fillRect(0, 0, Game.WIDTH,5);
g.setColor(Colors.Trans_GREEN3);
g.fillRect(0, 0, 10,Game.HEIGHT);
g.fillRect(0, 0, 9,Game.HEIGHT);
g.fillRect(0, 0, 8,Game.HEIGHT);
g.fillRect(0, 0, 7,Game.HEIGHT);
g.fillRect(0, 0, 6,Game.HEIGHT);
g.fillRect(0, 0, 5,Game.HEIGHT);
g.setColor(Colors.Trans_GREEN3);
g.setColor(Colors.Trans_GREEN3);
g.fillRect(Game.WIDTH-10, 0, 10,Game.HEIGHT);
g.fillRect(Game.WIDTH-9, 0, 9,Game.HEIGHT);
g.fillRect(Game.WIDTH-8, 0, 8,Game.HEIGHT);
g.fillRect(Game.WIDTH-7, 0, 7,Game.HEIGHT);
g.fillRect(Game.WIDTH-6, 0, 6,Game.HEIGHT);
g.fillRect(Game.WIDTH-5, 0, 5,Game.HEIGHT);
Graphics2D g2d = (Graphics2D) g;
if(State==STATE.MAIN) {
if(MouseInput.mx>=95 && MouseInput.mx<=145) {
if(MouseInput.my>60&&MouseInput.my<70) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 59, 54, 14);
}
else if(MouseInput.my>80&&MouseInput.my<90) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 79, 54, 14);
}
else if(MouseInput.my>40&&MouseInput.my<50) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 39, 54, 14);
desc=("");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}
}
g2d.drawImage(this.imageTitle,100,200,null);
g2d.drawImage(this.OPTIONS, Game.WIDTH/2-25, 60, null);
g2d.drawImage(this.imagePlay, Game.WIDTH/2-25, 40, null);
g2d.drawImage(this.imageExit, Game.WIDTH/2-25, 80, null);
double locationX = imageTitle.getWidth() / 2;
double locationY = imageTitle.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance((Math.toRadians(stibaum)), locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
AffineTransform old = g2d.getTransform();
g2d.drawImage(op.filter(imageTitle, null), Game.WIDTH/2-50, 10, null);
g2d.setTransform(old);
//things you draw after here will not be rotated
}
else if(State==STATE.INGAME) {
if(MouseInput.mx>=95 && MouseInput.mx<=145) {
if(MouseInput.my>70&&MouseInput.my<80) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 69, 54, 14);
}
else if(MouseInput.my>90&&MouseInput.my<100) {
g.fillRect(Game.WIDTH/2-26, 89, 54, 14);
}else if(MouseInput.my>50&&MouseInput.my<60) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 49, 54, 14);
}
}
g2d.drawImage(this.imageResume, Game.WIDTH/2-25, 70, null);
g2d.drawImage(this.imageMain, Game.WIDTH/2-25, 50, null);
g2d.drawImage(this.imageExit, Game.WIDTH/2-25, 90, null);
g2d.drawImage(this.imageTitle, Game.WIDTH/2-50, 10, null);}
else if(State==STATE.P1P2) {
if(MouseInput.mx>=15 && MouseInput.mx<=40) {
if(MouseInput.my>=106&&MouseInput.my<118) {
g.setColor(Colors.outline);
g.fillRect(14, Game.HEIGHT-29, 28, 15);
desc=("");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}}
if(MouseInput.my>30&&MouseInput.my<90) {
if(MouseInput.mx>=60 && MouseInput.mx<=120) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-61, 29,66, 66);
}
if(MouseInput.mx>=130 && MouseInput.mx<=190) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2+9, 29,66, 66);
}}
g2d.drawImage(this.players1, Game.WIDTH/2-60, 30, null);
g2d.drawImage(this.players2, Game.WIDTH/2+10, 30, null);
g2d.drawImage(this.BACK, 15, Game.HEIGHT-28, null);
}
else if(State==STATE.DIFICULTY) {
if(MouseInput.mx>=15 && MouseInput.mx<=40) {
if(MouseInput.my>=106&&MouseInput.my<118) {
g.setColor(Colors.outline);
g.fillRect(14, Game.HEIGHT-29, 28, 15);
desc=("");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}}
if(MouseInput.mx>=95 && MouseInput.mx<=145) {
if(MouseInput.my>70&&MouseInput.my<80) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 69, 54, 14);
g.setColor(Color.green);
desc=("for those who want challenge");
g.drawString(desc,50 , Game.HEIGHT/2+50);
}
else if(MouseInput.my>90&&MouseInput.my<100) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 89, 54, 14);
desc=("for those who want to cry");
g.setColor(Color.green);
g.drawString(desc,70 , Game.HEIGHT/2+50);
}else if(MouseInput.my>50&&MouseInput.my<60) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 49, 54, 14);
desc=("for those who want to play casually");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}if(Ball.pmih) {
if(MouseInput.my>33&&MouseInput.my<44) {
g.setColor(Colors.outline);
g.fillRect(Game.WIDTH/2-26, 32, 54, 14);
desc=("for those who don't really have a life");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}}
}
if(Ball.pmih) {
g2d.drawImage(this.IMPOSSIBLE, Game.WIDTH/2-25, 33, null);}
g2d.drawImage(this.Normal, Game.WIDTH/2-25, 70, null);
g2d.drawImage(this.Easy, Game.WIDTH/2-25, 50, null);
g2d.drawImage(this.Hard, Game.WIDTH/2-25, 90, null);
g2d.drawImage(this.imageTitle, Game.WIDTH/2-50, 10, null);
g2d.drawImage(this.BACK, 15, Game.HEIGHT-28, null);
}
else if(State==STATE.OPTIONS) {
if(MouseInput.mx>=15 && MouseInput.mx<=40) {
if(MouseInput.my>=106&&MouseInput.my<118) {
g.setColor(Colors.outline);
g.fillRect(14, Game.HEIGHT-29, 28, 15);
desc=("");
g.setColor(Color.green);
g.drawString(desc,45 , Game.HEIGHT/2+50);
}}
slider.render(g);
g2d.drawImage(this.imageTitle, Game.WIDTH/2-50, 10, null);
g2d.drawImage(this.BACK, 15, Game.HEIGHT-28, null);
}
}
public void tick() {
slider.tick();
if(stibaum<5&&sti==true) {
stibaum+=1;
}
if(stibaum>=5&&sti==true) {sti=false;}
if(stibaum>-5&&sti==false) {
stibaum-=1;
}
if(stibaum<=-5&&sti==false) {sti=true;}
if(State==STATE.OPTIONS) {
Statepre=STATE.MAIN;
}
else if(State==STATE.P1P2) {
Statepre=STATE.MAIN;
}
else if(State==STATE.DIFICULTY) {
Statepre=STATE.P1P2;
}
}
}
input = new FileInputStream("res/Playbutt.png");
This doesn't work. You can't use FIS, you'd have to use Menu.class.getResource. Not getClass().
ImageIO.read(new File("res/2P.png"));
Same here.
} catch (IOException ex) {
// handle exception...
}
This isn't how you do this stuff. Get rid of it all, and add throws IOException to the constructor. public static void main can and generally should be declared to throws Exception. You're ignoring the errors, making it harder to debug this problem. Hence, don't do it this way.
None of your code is trying to use Main.class.getResource.
res is not marked as a source dir in your eclipse project. You need to fix that. You have 2 options:
Forget about a res dir. Put your images in the exact same place as your java files are. Just move them there - and then getResource will work fine. For example, if img.png is in the same dir (the exact same dir!) as Main.java, then Main.class.getResource("img.png") will work fine.
Use maven, and then change this project to be a maven based one. Then eclipse will take care of it.

Add a button to Java Applet

Using this code I would like to add a button to the page that displays when the gamestate is either Dead or Win. This button will let the user either start over or go on to the next level. My action listener is not yet fully coded because I can't even get the button to be visible on the page. I have tried coding in a button using
setLayout(new FlowLayout());
this.add(sOver);
sOver = new Button("Start Over");
sOver.addActionListener(this);
But that results in a an error when the game changes state.
package androidGame;
import java.applet.Applet;
import java.awt.event.*;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.net.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import androidGame.framework.Animation;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class StartingClass extends Applet implements Runnable, KeyListener, ActionListener {
enum GameState {
Running, Dead, Win
}
GameState state = GameState.Running;
private static Robot robot;
public static Heliboy hb, hb2, hb3, hb4, hb5, hb6, hb7, hb8, hb9, hb10, hb11, hb12, hb13, hb14, hb15, hb16;
public static int score = 0;
public static int rHealth = 120;
private Font font = new Font(null, Font.BOLD, 30);
private Image image, currentSprite, character, character2, character3,
characterDown, characterJumped, background, heliboy, heliboy2,
heliboy3, heliboy4, heliboy5;
public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
tilegrassRight, tiledirt, tilefire, tiledoor;
private Graphics second;
private URL base;
private static Background bg1, bg2;
private Animation anim, hanim;
int level = 1;
AudioClip clip;
Button next, sOver;
private ArrayList<Tile> tilearray = new ArrayList<Tile>();
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Robot Mania");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "data/character.png");
character2 = getImage(base, "data/character2.png");
character3 = getImage(base, "data/character3.png");
characterDown = getImage(base, "data/down.png");
characterJumped = getImage(base, "data/jumped.png");
heliboy = getImage(base, "data/heliboy.png");
heliboy2 = getImage(base, "data/heliboy2.png");
heliboy3 = getImage(base, "data/heliboy3.png");
heliboy4 = getImage(base, "data/heliboy4.png");
heliboy5 = getImage(base, "data/heliboy5.png");
background = getImage(base, "data/spacebackground.png");
tiledirt = getImage(base, "data/tiledirt.png");
tilegrassTop = getImage(base, "data/tilegrasstop.png");
tilegrassBot = getImage(base, "data/tilegrassbot.png");
tilegrassLeft = getImage(base, "data/tilegrassleft.png");
tilegrassRight = getImage(base, "data/tilegrassright.png");
tilefire = getImage(base, "data/tilefire.png");
tiledoor = getImage(base, "data/tiledoor.png");
anim = new Animation();
anim.addFrame(character, 1250);
anim.addFrame(character2, 50);
anim.addFrame(character3, 50);
anim.addFrame(character2, 50);
hanim = new Animation();
hanim.addFrame(heliboy, 100);
hanim.addFrame(heliboy2, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy5, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy2, 100);
currentSprite = anim.getImage();
}
#Override
public void start() {
//Sound.MAIN.loop();
bg1 = new Background(0, 0);
bg2 = new Background(2160, 0);
robot = new Robot();
// Initialize Tiles
try {
loadMap("data/map"+ level +".txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random random = new Random();
int randomInt = random.nextInt(500);
hb = new Heliboy(700, 360);
hb2 = new Heliboy(900 + randomInt, 360);
hb3 = new Heliboy(2300 + randomInt, 360);
hb4 = new Heliboy(2900 + randomInt, 360);
hb5 = new Heliboy(3400 + randomInt, 360);
hb6 = new Heliboy(3900 + randomInt, 360);
hb7 = new Heliboy(4300 + randomInt, 360);
hb8 = new Heliboy(4700 + randomInt, 360);
hb9 = new Heliboy(5000 + randomInt, 360);
hb10 = new Heliboy(5300 + randomInt, 360);
hb11 = new Heliboy(5700 + randomInt, 360);
hb12 = new Heliboy(6000 + randomInt, 360);
hb13 = new Heliboy(6300 + randomInt, 360);
hb14 = new Heliboy(6700 + randomInt, 360);
hb15 = new Heliboy(7000 + randomInt, 360);
hb16 = new Heliboy(7200 + randomInt, 360);
Thread thread = new Thread(this);
thread.start();
}
private void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
int width = 0;
int height = 0;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (true) {
String line = reader.readLine();
// no more lines to read
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();
for (int j = 0; j < 12; j++) {
String line = (String) lines.get(j);
for (int i = 0; i < width; i++) {
if (i < line.length()) {
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tilearray.add(t);
}
}
}
}
#Override
public void run() {
if (state == GameState.Running) {
while (true) {
robot.update();
if (robot.isJumped()) {
currentSprite = characterJumped;
} else if (robot.isJumped() == false
&& robot.isDucked() == false) {
currentSprite = anim.getImage();
}
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
if (p.isVisible() == true) {
p.update();
} else {
projectiles.remove(i);
}
}
updateTiles();
hb.update();
hb2.update();
hb3.update();
hb4.update();
hb5.update();
hb6.update();
hb7.update();
hb8.update();
hb9.update();
hb10.update();
hb11.update();
hb12.update();
hb13.update();
hb14.update();
hb15.update();
hb16.update();
bg1.update();
bg2.update();
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (rHealth == 0) {
state = GameState.Dead;
Sound.MAIN.stop();
//Sound.DIE.play();
sOver = new Button("Start Over");
this.add(sOver);
sOver.addActionListener(this);
sOver.setVisible(true);
revalidate();
repaint();
}
if (robot.getCenterY() > 500) {
state = GameState.Dead;
Sound.MAIN.stop();
//Sound.DIE.play();
sOver = new Button("Start Over");
this.add(sOver);
sOver.addActionListener(this);
sOver.setVisible(true);
revalidate();
repaint();
}
if (score == 5){
state = GameState.Win;
Sound.MAIN.stop();
//Sound.WIN.play();
next = new Button("Next Level");
this.add(next);
next.addActionListener(this);
next.setVisible(true);
revalidate();
repaint();
}
}
}
}
public void animate() {
anim.update(10);
hanim.update(50);
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
if (state == GameState.Running) {
g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
paintTiles(g);
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
g.setColor(Color.BLUE);
g.fillRect(p.getX(), p.getY(), 10, 5);
}
g.drawImage(currentSprite, robot.getCenterX() - 61,
robot.getCenterY() - 63, this);
g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
hb.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
hb2.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb3.getCenterX() - 48,
hb3.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb4.getCenterX() - 48,
hb4.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb5.getCenterX() - 48,
hb5.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb6.getCenterX() - 48,
hb6.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb7.getCenterX() - 48,
hb7.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb8.getCenterX() - 48,
hb8.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb9.getCenterX() - 48,
hb9.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb10.getCenterX() - 48,
hb10.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb11.getCenterX() - 48,
hb11.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb12.getCenterX() - 48,
hb12.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb13.getCenterX() - 48,
hb13.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb14.getCenterX() - 48,
hb14.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb15.getCenterX() - 48,
hb15.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb16.getCenterX() - 48,
hb16.getCenterY() - 48, this);
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString("Health: " + Integer.toString(rHealth), 5, 30);
g.drawString("Score: " + Integer.toString(score), 650, 30);
} else if (state == GameState.Dead) {
//setLayout(new FlowLayout());
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString("You're Dead!", 300, 200);
g.drawString("Score: " + score, 300, 250);
}
else if (state == GameState.Win) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString("You Beat this level!", 300, 200);
g.drawString("Score: " + score, 300, 250);
level++;
}
}
private void updateTiles() {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
t.update();
}
}
private void paintTiles(Graphics g) {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
currentSprite = characterDown;
if (robot.isJumped() == false) {
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
robot.jump();
break;
case KeyEvent.VK_CONTROL:
if (robot.isDucked() == false && robot.isJumped() == false
&& robot.isReadyToFire()) {
robot.shoot();
robot.setReadyToFire(false);
}
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
currentSprite = anim.getImage();
robot.setDucked(false);
break;
case KeyEvent.VK_LEFT:
robot.stopLeft();
break;
case KeyEvent.VK_RIGHT:
robot.stopRight();
break;
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_CONTROL:
robot.setReadyToFire(true);
Sound.GUN.play();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static Background getBg1() {
return bg1;
}
public static Background getBg2() {
return bg2;
}
public static Robot getRobot() {
return robot;
}
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == next)
level ++;
{
}
if (evt.getSource() == sOver)
level = 1;
{
}
}
}
The error message that I was getting is:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at androidGame.StartingClass.paint(StartingClass.java:372)
at androidGame.StartingClass.update(StartingClass.java:305)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$300(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
this.add(sOver);
sOver = new Button("Start Over");
I guess the error is here. You gotta initialize sOver before adding it to the applet. So put it like this :
sOver = new Button("Start Over");
this.add(sOver);
Let's see whether it works or not.

smooth rounded corners in swing

I want to make smooth rounded corners for my swing application, but I can't get my desired result...
here's the screenshots:
1.setShape() for JFrame :
2.overriding paintComponent() method for JPanel instead of using setShape() :
3.setBackground(new Color(0, 0, 0, 0)) for JFrame :
well, but there's a problem with text quality:
before step 3 :
after step 3 :
guys I'm confused, I've searched many times but nothing helped me...
what should I do? please help me
here's the full code :
public class WelcomePage extends JFrame {
private Point initialClick;
private boolean end = false;
private JLabel jLabelAppTitle;
private JPanel jPanelExit;
private JLabel jLabelHint;
private int r = 220, g = 0, b = 0;
private int r2 = 10, g2 = 10, b2 = 10;
private boolean flag = false;
public WelcomePage() {
initComponents();
// setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 15, 15));
centerLocation();
refreshPage();
}
public static void main(String args[]) {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
EventQueue.invokeLater(() -> FadeTransitions.fadeIn(new WelcomePage(), FadeTransitions.NORMAL_FADE, true));
}
private void refreshPage() {
Timer timer = new Timer(20, e -> {
if (!end) {
if (r == 220 && b == 0 && g < 220) {
g++;
} else if (g == 220 && b == 0 && r > 0) {
r--;
} else if (g == 220 && r == 0 && b < 220) {
b++;
} else if (b == 220 && r == 0 && g > 0) {
g--;
} else if (b == 220 && g == 0 && r < 220) {
r++;
} else if (r == 220 && g == 0 && b > 0) {
b--;
}
if (!flag) {
r2 += 5;
g2 += 5;
b2 += 5;
if (r2 == 250) {
flag = true;
}
} else {
r2 -= 5;
g2 -= 5;
b2 -= 5;
if (r2 == 10) {
flag = false;
}
}
jLabelAppTitle.setForeground(new Color(r, g, b));
jLabelHint.setForeground(new Color(r2, g2, b2));
} else {
((Timer) e.getSource()).stop();
}
});
timer.setCoalesce(true);
timer.setRepeats(true);
timer.start();
}
private void centerLocation() throws HeadlessException {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - this.getWidth()) / 2;
final int y = (screenSize.height - this.getHeight()) / 2;
this.setLocation(x, y);
}
#SuppressWarnings("unchecked")
private void initComponents() {
JPanel jPanelMain = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(qualityHints);
g2.setPaint(Color.WHITE);
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 25, 25);
g2.dispose();
}
};
jPanelExit = new JPanel();
JLabel jLabelExit = new JLabel();
JLabel jLabelWelcome = new JLabel();
jLabelAppTitle = new JLabel();
jLabelHint = new JLabel();
JButton jButtonGo = new JButton();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("welcome to My App!");
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
close();
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
thisMouseDragged(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent evt) {
thisMousePressed(evt);
}
});
jPanelMain.setBackground(Color.WHITE);
jPanelExit.setBackground(new Color(160, 0, 20));
jLabelExit.setFont(new Font("Tahoma", Font.BOLD, 13));
jLabelExit.setForeground(new Color(255, 255, 255));
jLabelExit.setHorizontalAlignment(SwingConstants.CENTER);
jLabelExit.setText("X");
jLabelExit.setCursor(new Cursor(Cursor.HAND_CURSOR));
jLabelExit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
jLabelExitMouseClicked();
}
public void mouseEntered(MouseEvent evt) {
jLabelExitMouseEntered();
}
public void mouseExited(MouseEvent evt) {
jLabelExitMouseExited();
}
});
GroupLayout jPanelExitLayout = new GroupLayout(jPanelExit);
jPanelExit.setLayout(jPanelExitLayout);
jPanelExitLayout.setHorizontalGroup(
jPanelExitLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, jPanelExitLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabelExit, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE))
);
jPanelExitLayout.setVerticalGroup(
jPanelExitLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, jPanelExitLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabelExit, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
);
jLabelWelcome.setFont(new Font("Tahoma", 0, 25));
jLabelWelcome.setForeground(new Color(0, 0, 100));
jLabelWelcome.setHorizontalAlignment(SwingConstants.CENTER);
jLabelWelcome.setText("Welcome");
jLabelAppTitle.setFont(new Font("MV Boli", 0, 29));
jLabelAppTitle.setHorizontalAlignment(SwingConstants.CENTER);
jLabelAppTitle.setText("My Swing App");
jButtonGo.setBackground(new Color(100, 20, 80));
jButtonGo.setFont(new Font("Tahoma", 0, 15));
jButtonGo.setForeground(new Color(255, 255, 255));
jButtonGo.setText("GO");
jButtonGo.addActionListener(evt -> jButtonGoActionPerformed());
jLabelHint.setFont(new Font("Tahoma", 0, 11));
jLabelHint.setHorizontalAlignment(SwingConstants.CENTER);
jLabelHint.setText("press GO button");
javax.swing.GroupLayout jPanelMainLayout = new javax.swing.GroupLayout(jPanelMain);
jPanelMain.setLayout(jPanelMainLayout);
jPanelMainLayout.setHorizontalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMainLayout.createSequentialGroup()
.addContainerGap(48, Short.MAX_VALUE)
.addGroup(jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMainLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanelExit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15))
.addGroup(jPanelMainLayout.createSequentialGroup()
.addGroup(jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabelWelcome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelAppTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(jLabelHint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonGo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(48, Short.MAX_VALUE))))
);
jPanelMainLayout.setVerticalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMainLayout.createSequentialGroup()
.addComponent(jPanelExit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(64, 64, 64)
.addComponent(jLabelWelcome, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(98, 98, 98)
.addComponent(jLabelAppTitle)
.addGap(86, 86, 86)
.addComponent(jLabelHint)
.addGap(24, 24, 24)
.addComponent(jButtonGo, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
pack();
}
private void thisMousePressed(MouseEvent evt) {
initialClick = evt.getPoint();
}
private void thisMouseDragged(MouseEvent evt) {
int thisX = this.getLocation().x;
int thisY = this.getLocation().y;
int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y);
int x = thisX + xMoved;
int y = thisY + yMoved;
this.setLocation(x, y);
}
private void jLabelExitMouseClicked() {
close();
}
private void close() {
end = true;
FadeTransitions.fadeOut(this, FadeTransitions.FAST_FADE, FadeTransitions.EXIT_ON_CLOSE);
}
private void jLabelExitMouseEntered() {
jPanelExit.setBackground(new Color(200, 0, 20));
}
private void jLabelExitMouseExited() {
jPanelExit.setBackground(new Color(160, 0, 20));
}
private void jButtonGoActionPerformed() {
end = true;
FadeTransitions.run(this, new ServerManager(this), FadeTransitions.NORMAL_FADE, FadeTransitions.DISPOSE_ON_CLOSE);
}
}
thanks.
Sorry, not an answer, but hopefully at least one step towards an acceptable answer: From my analysis so far, it might be that this is simply a bug somewhere deep (deeeep!) inside the rendering pipeline.
The following MVCE shows two (undecorated) frames, each containing a button. They are equal, except for the background of the frames. For one frame, the color is transparent, and for the other one, it is opaque.
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TextRenderBug extends JFrame {
public static void main(String[] args)
{
setLookAndFeel();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI(new Color(0,0,0 ), 400);
createAndShowGUI(new Color(0,0,0,0), 600);
}
});
}
private static void setLookAndFeel()
{
try
{
for (UIManager.LookAndFeelInfo info :
UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void createAndShowGUI(Color background, int x)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(background);
JButton b = new JButton("Text");
b.setFont(new Font("Tahoma", 0, 15));
f.getContentPane().add(b);
f.setBounds(x, 400, 200, 50);
f.setVisible(true);
}
}
It clearly shows that the text is rendered differently, solely depending on the background being transparent - and of course, this should not be the case.
(This is not Nimbus-specific, by the way: It also applies to other LookAndFeels. Just remove the line where the LaF is set).
What I found out so far:
The behavior is somehow caused by the drawString method of the sun.swing.SwingUtilities2 class
It does not appear in all components. It can be observed on JButton and JLabel, but not on a normal JComponent
Update: It also does not depend on the font (although with other fonts, the effect is not so noticable). When rendered correctly, the font looks a little bit more bold, but of course, it is not simply the same font as a Font.BOLD.
The painting process is rather complicated.
(OK, some of you might already have known the latter).
Here is an example that shows the last observations, maybe it can serve as a starting point for further research of others:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.lang.reflect.Method;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TextRenderBugTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI(new Color(0,0,0 ), 400);
createAndShowGUI(new Color(0,0,0,0), 600);
}
});
}
private static void createAndShowGUI(Color background, int x)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(background);
JButton b = new JButton("Text");
b.setFont(new Font("Tahoma", 0, 15));
JComponent c = new ExampleComponent();
c.setFont(new Font("Tahoma", 0, 15));
f.getContentPane().setLayout(new GridLayout(0,1));
f.getContentPane().add(b);
f.getContentPane().add(c);
f.setBounds(x, 400, 200, 100);
f.setVisible(true);
}
static class ExampleComponent
//extends JComponent
extends JButton
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.drawString("Text", 10, 20);
drawStringWithSwingUtilities(g, 60, 20);
}
private void drawStringWithSwingUtilities(Graphics g, int x, int y)
{
try
{
Class<?> c = Class.forName("sun.swing.SwingUtilities2");
Method m = c.getMethod("drawString", JComponent.class,
Graphics.class, String.class, int.class, int.class);
m.invoke(null, this, g, "Text", x, y);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
I already tried to analyze this further, and played around with RenderingHints like KEY_TEXT_ANTIALIASING and KEY_TEXT_LCD_CONTRAST and other settings that are changed in the painting pipeline while it is heading towards the pixels that are finally placed on the screen, but no further insights until now.
(If you want to, you can add this information to your original question, then I'll delete this (not-)answer)
The only chance you have is working with regions. You will need to hardcode a bit and play with subtract, but eventually it will look fine. You can take a look at how it's done in mylyn's notification class: http://grepcode.com/file/repository.grepcode.com/java/eclipse.org/3.6/org.eclipse.mylyn.commons/ui/3.4.0/org/eclipse/mylyn/internal/provisional/commons/ui/AbstractNotificationPopup.java
Hope it helps, best of luck!
Edit: Just remembered this little tutorial which might help: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/SWTShellcreateanonrectangularwindow.htm

Boolean value changes when run

just need a little help locating an error(?) in my code, is set the default of the boolean avtive to false but when i run the code, it mysteriously becomes true
import javax.swing.*;
import java.awt.*;
import java.net.URL;
#SuppressWarnings("serial")
public class openScreenBuild extends JPanel{
String picPath = "pictures/";
String[] fileName = { "openScreen.png", "playButtonPress.png",
"playButtonRelease.png", "playButtonInactive.png" };
ClassLoader cl = openScreenBuild.class.getClassLoader();
URL imgURL[] = new URL[4];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgPlayPress, imgPlayRelease, imgPlayInactive;
Boolean active=false, playPress = false;
public openScreenBuild() throws Exception {
for (int x = 0; x < 4; x++) {
imgURL[x] = cl.getResource(picPath + fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
imgPlayPress = tk.createImage(imgURL[1]);
imgPlayRelease = tk.createImage(imgURL[2]);
imgPlayInactive = tk.createImage(imgURL[3]);
}
public void updateScreen(){
repaint();
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 0, 0, 600, 460, 0, 0, 600, 460, this);
if (active=true){
if (playPress == false)
g.drawImage(imgPlayRelease, 410, 355, 590, 450, 0, 0, 163, 87, this);
else if (playPress == true)
g.drawImage(imgPlayPress, 410, 355, 590, 450, 0, 0, 163, 87, this);
System.out.println("Active");
}
else if(active=false){
g.drawImage(imgPlayInactive, 410, 355, 590, 450, 0, 0, 163, 87, this);
System.out.println("Inactive");
}
g.setColor(Color.WHITE);
g.drawString("ABOUT PROGRAM STUFF", 25, 375);
}
public void checkCoord(Point point){
int xPos=(int)point.getX();
int yPos=(int)point.getY();
if (active==true){
if ((yPos>=355)&&(yPos<=450)&&(xPos>=410)&&(xPos<=590))
playPress=true;
}
updateScreen();
}
public void resetScreen(){
playPress=false;
updateScreen();
}
}
As you can see, if active is false it should show a inactive play button image but if its true then it does the click/release images. Also it outputs in the System box(?)(Not sure what its called) if its active or not active
if (active=true)
assigns active to true. You want:
if (active==true)

Why are graphics not appearing in JFrame?

Below I included two of the classes in my Java program (Launcher and Controls). In the both classes, they create a JFrame, draw a background image, and add lines of text. I have looked at the code over and over, but for some reason the background image and the line of text are not appearing in the second class (Controls). Could anyone please explain to me why this is happening?
Launcher Class:
import hungerGames.Display;
import hungerGames.RunGame;
import hungerGames.input.InputHandler;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Launcher extends JFrame implements Runnable {
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 800;
private int height = 450;
boolean running = false;
Thread thread;
public Launcher(int id) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
startMenu();
}
public void updateFrame() {
if (InputHandler.dragged) {
Point p = getLocation();
if (InputHandler.MouseDX != InputHandler.MousePX || InputHandler.MouseDX != InputHandler.MousePX) {
setLocation(p.x + InputHandler.MouseDX - InputHandler.MousePX, p.y + InputHandler.MouseDY - InputHandler.MousePY);
}
}
}
public void startMenu() {
running = true;
thread = new Thread(this, "menu");
thread.start();
}
public void stopMenu() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
try {
renderMenu();
} catch (IllegalStateException e) {
System.out.println("Handled");
}
updateFrame();
}
}
private void renderMenu() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/main_menu.jpg")), 0, 0, 800, 450, null);
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 100 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new RunGame();
}
}
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 320 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Controls();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 490 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Credits();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 440 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 30));
g.drawString("By Lawrence Zhao", 210, 275);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Play", 50, 325);
g.drawString("Controls and Options", 50, 425);
g.drawString("Credits", 400, 325);
g.drawString("Exit", 400, 425);
g.dispose();
bs.show();
}
}
Controls Class:
import hungerGames.Display;
import hungerGames.input.InputHandler;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Controls extends JFrame{
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 720;
private int height = 450;
private Rectangle rResolution;
private Choice resolution = new Choice();
public Controls() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
renderControls();
drawButtons();
stopMenuThread();
}
private void stopMenuThread() {
Display.getLauncherInstance().stopMenu();
}
private void drawButtons() {
rResolution = new Rectangle(50,100, 100, 25);
resolution.setBounds(rResolution);
resolution.add("640, 400");
resolution.add("800, 600");
resolution.add("1024, 768");
resolution.select(1);
add(resolution);
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/controls.jpg")),0, 0, 720, 450, null);
if (InputHandler.mouseX >= 360 && InputHandler.mouseX <= 400 && InputHandler.mouseY >=270 && InputHandler.mouseY <=305) {
g.drawImage(ImageIO.read(Controls.class.getResource("/pin.png")),360,270, 30, 33, null);
if (InputHandler.MouseButton == 1) {
Display.selection = resolution.getSelectedIndex();
dispose();
new Launcher(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
It's clear that you don't understand how the buffering strategy is suppose to work.
I'd suggest you have a read through Double Buffering for some clues.
(ps, I don't have much experience with this side of the API either, but I got your code to work by simply reading through the above linked tut)
Update
Seems to work just fine for me...
Some notes.
Pre-load your images, otherwise you're wasting your time double buffering as the IO is going to slow you down.
Make sure your images exist and are begin loaded properly
.
public class BadPaint03 {
public static void main(String[] args) {
new BadPaint03();
}
public BadPaint03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Controls frame = new Controls();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public class Controls extends JFrame {
private int width = 720;
private int height = 450;
private Rectangle rResolution;
protected JPanel window = new JPanel();
private BufferedImage background;
public Controls() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
renderControls();
try {
Thread.sleep(1000 / 24);
} catch (InterruptedException ex) {
Logger.getLogger(BadPaint03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
if (background != null) {
int x = (720 - background.getWidth()) / 2;
int y = (450 - background.getHeight()) / 2;
g.drawImage(background, x, y, null);
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
}

Categories