Why are graphics not appearing in JFrame? - java

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();
}
}
}

Related

How can I make my swing graphics project have a higher FPS(frames per second for anyone who doesn't know what it means)?

I started remaking my graphics engine and i have a problem with repainting the VolatileImage on the JFrame, i added an FPS counter and when it is in full-screen it only gets to around 250 or 280 FPS even though i have the loop in a new thread and I'm only drawing 2 dots on the screen.
Here is the code for the init and render functions in the Window class, might be a bit unorganized:
`
public int render() {
frame.getGraphics().drawImage(vImg, 0, 0, frame.getWidth(), frame.getHeight(), null);
totalFrames++;
if (System.nanoTime() > lastFPScheck + 1000000000) {
lastFPScheck = System.nanoTime();
currentFPS = totalFrames;
totalFrames = 0;
}
if (vImg.validate(gc) == VolatileImage.IMAGE_OK) {
vImg = gc.createCompatibleVolatileImage(frame.getWidth(), frame.getHeight());
}
if (debugging()) {
frame.setTitle(title + "[FPS: " + currentFPS + "]");
}
graphics = (Graphics2D)vImg.getGraphics();
graphics.setColor(bg_color);
graphics.fillRect(0, 0, frame.getWidth(), frame.getHeight());
return currentFPS;
}
public void repaint_buffer() {
frame.getContentPane().getGraphics().drawImage(vImg, 0, 0, canvasWidth, canvasHeight, null);
}
public void init(int width,
int height,
String title,
Color bg_color,
Consumer<Void> onDestroy) {
this.canvasWidth = width;
this.canvasHeight = height;
this.is_open = true;
this.title = title;
this.bg_color = bg_color;
this.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onDestroy.accept(null);
}
});
this.frame.addWindowListener(new WindowAdapter() {
public void windowResized(WindowEvent e) {
vImg = gc.createCompatibleVolatileImage(frame.getWidth(), frame.getHeight());
}
});
this.frame.setLayout(null);
this.frame.setSize(canvasWidth, canvasHeight);
this.frame.addKeyListener(keyInput);
this.frame.setResizable(true);
this.frame.setLocation(-7, 0);
this.frame.setTitle(title);
this.frame.setVisible(true);
gc = this.frame.getGraphicsConfiguration();
vImg = gc.createCompatibleVolatileImage(this.frame.getWidth(), this.frame.getHeight());
this.graphics = (Graphics2D) vImg.getGraphics();
}
`
and here is the code from the Main class, the GraphicsManager object only contains the set_pixel function which sets the color and draws a rectangle at the given position with a size of 1x1 pixels:
package obsidian.core;
import obsidian.core.Window;
import java.awt.*;
public class Main {
private static void on_destroy() {
System.exit(0);
}
public static void main(String[] args) {
Window window = new Window();
window.init(Window.get_max_size().width, Window.get_max_size().height, "title", new Color(0, 0, 0), destroy -> on_destroy());
GraphicsManager gm = new GraphicsManager(window);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while(window.is_open()) {
window.render();
gm.draw_pixel(0.5, 0.5, new Color(255, 0, 0));
gm.draw_pixel(0, 0, new Color(255, 255, 255));
System.out.println(window.get_current_fps());
}
}
});
t.start();
}
}
I tried removing the VolatileImage and directly drawing on the frame but the filling of the image makes it glitchy but it got to about 2000 FPS and IntelliJ IDEA couldn't keep up. The only solution I could find to make it run faster is removing the VolatileImage and draw directly to the frame. Didn't work ;-;
Can anyone help me with this? Thank you
Swing "passive" painting
This makes use of a Swing Timer
~170fps
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.Instant;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Timer timer;
private Instant lastTick;
private int fps = 0;
public TestPane() {
}
#Override
public void addNotify() {
super.addNotify();
if (timer != null) {
timer.stop();
}
timer = new Timer(5, new ActionListener() {
private int frameCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (lastTick != null) {
Duration duration = Duration.between(lastTick, Instant.now());
if (duration.toMillis() >= 1000) {
lastTick = Instant.now();
fps = frameCount;
frameCount = 0;
} else {
frameCount++;
}
} else {
lastTick = Instant.now();
}
repaint();
}
});
timer.start();
}
#Override
public void removeNotify() {
if (timer != null) {
timer.stop();
}
timer = null;
super.removeNotify();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval(20, 20, 20, 20);
g2d.fillOval(40, 40, 20, 20);
FontMetrics fm = g2d.getFontMetrics();
String text = Integer.toString(fps);
g2d.drawString(text, 10, fm.getAscent());
g2d.dispose();
}
}
}
"Active" painting via a BufferStrategy
~680fps
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean;
public class Other {
public static void main(String[] args) {
new Other();
}
public Other() {
Frame frame = new Frame();
MainCanvas canvas = new MainCanvas();
frame.setBackground(Color.BLUE);
frame.add(canvas);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public class MainCanvas extends Canvas {
private Thread thread;
private AtomicBoolean running = new AtomicBoolean(false);
private int fps;
public MainCanvas() {
}
#Override
public void addNotify() {
super.addNotify();
createBufferStrategy(3);
start();
}
#Override
public void removeNotify() {
stop();
super.removeNotify();
}
public void start() {
stop();
run();
}
protected void stop() {
if (running.get()) {
running.set(false);
}
thread = null;
}
protected void run() {
stop();
running.set(true);
thread = new Thread(new Runnable() {
private Instant lastTick;
private int frameCount;
#Override
public void run() {
while (running.get()) {
if (lastTick != null) {
Duration duration = Duration.between(lastTick, Instant.now());
if (duration.toMillis() >= 1000) {
lastTick = Instant.now();
fps = frameCount;
frameCount = 0;
} else {
frameCount++;
}
} else {
lastTick = Instant.now();
}
render();
// Comment out these lines and see where it takes you
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
java.util.logging.Logger.getLogger(Other.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
}
});
thread.start();
}
protected void render() {
BufferStrategy bs = getBufferStrategy();
while (bs == null) {
bs = getBufferStrategy();
}
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// to make sure the strategy is validated
Graphics2D g2d = (Graphics2D) bs.getDrawGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, getWidth(), getHeight());
// Render to graphics
// ...
g2d.setColor(Color.RED);
g2d.fillOval(20, 20, 20, 20);
g2d.fillOval(40, 40, 20, 20);
FontMetrics fm = g2d.getFontMetrics();
String text = Integer.toString(fps);
g2d.drawString(text, 10, fm.getAscent());
// Dispose the graphics
g2d.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (bs.contentsRestored());
// Display the buffer
bs.show();
// Repeat the rendering if the drawing buffer was lost
} while (bs.contentsLost());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
Disclaimer
This is by far a "scientific" example and is intended simply as a demonstration between passive and active rendering workflows

When I export my Java program, why does the frame come up but not the panel?

I wanted to export my game into a .jar file. It exported; when I ran it the frame came up, but the panel didn't load. I have my frame and panel in two different class files but I didn't think that made a difference. Also, It completely works in Eclipse. I exported my .jar file under Runnable Jar File and packaged required libraries into generated jar. In the SlashRunnerPanel I imported and resized many images. Can that be the problem?
Here is my code for the frame:
package baseFiles;
import javax.swing.*;
public class SlashRunnerFrame {
public static void main(String args[]) {
JFrame frame = new JFrame(); // Create new JFrame (the window)
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
SlashRunnerPanel panel = new SlashRunnerPanel();
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
panel.mainLoop();
}
}
Here is my code for the panel:
package baseFiles;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
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.util.ArrayList;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.imageio.*;
import java.io.File;
import player.Player;
import surroundings.Obstacle;
public class SlashRunnerPanel extends JPanel implements KeyListener,
ActionListener, MouseListener
{
public static boolean mailbox1 = false;
Color skin = new Color(255, 223, 196);
boolean goo = true;
BufferedImage origMailBox;
BufferedImage house;
BufferedImage ReplaceableBackgroundPic;
BufferedImage origPlayerBack;
BufferedImage origPlayerFront;
BufferedImage origletter;
BufferedImage blackScreen;
BufferedImage exclamation;
BufferedImage borderRocks;
BufferedImage pause;
Image ReplaceableBackground;
Image resizedHouse;
Image mailbox;
Image PlayerBack;
Image PlayerFront;
Image letter;
Image Exclamation;
ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>();
Obstacle mailboxRegion;
Player player;
Obstacle Beginning;
String ps = System.getProperty("file.separator");
//Animation for walking
boolean aniUp = true;
boolean aniDown;
boolean aniRight;
boolean aniLeft;
boolean lastAni;
//mail
boolean openMail = false;
boolean isMailbox;
boolean mailcontinue;
boolean arrow = true;
boolean showMailRegion;
//Scene
boolean begin = true;
int cmX;
int cmY;
boolean obstaclesInBeginning = true;
boolean showObstInBegin;
//Keys
boolean showObstacles;
boolean stats;
boolean pausebool;
boolean play = true;
public SlashRunnerPanel()
{
try{
borderRocks = ImageIO.read(new File("src" + ps + "Images" + ps + "Boundary.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
exclamation = ImageIO.read(new File("src" + ps + "Images" + ps + "Exclamation.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
origletter = ImageIO.read(new File("src" + ps + "Images" + ps + "Scroll.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
blackScreen = ImageIO.read(new File("src" + ps + "Images" + ps + "BlackScreen.png"));
} catch(Exception e) {e.printStackTrace();}
try{
house = ImageIO.read(new File("src" + ps + "Images" + ps + "House.png"));
} catch(Exception e) {e.printStackTrace();}
try{
ReplaceableBackgroundPic = ImageIO.read(new File("src" + ps + "Images" + ps + "ReplaceableBackground.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origMailBox = ImageIO.read(new File("src" + ps + "Images" + ps + "SmallMailbox.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origPlayerBack = ImageIO.read(new File("src" + ps + "Images" + ps + "WarriorBack.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origPlayerFront = ImageIO.read(new File("src" + ps + "Images" + ps + "WarriorFront.png"));
} catch(Exception e) {e.printStackTrace();}
try{
pause = ImageIO.read(new File("src" + ps + "Images" + ps + "Pause.png"));
} catch(Exception e) {e.printStackTrace();}
}
public void mainLoop()
{
obstacles.add(new Obstacle(140, 170, 300, 545));
obstacles.add(new Obstacle(560, 170, 350, 500));
obstacles.add(new Obstacle(500, 900, 800, 100));
this.setFocusable(true);
addKeyListener(this);
addMouseListener(this);
Exclamation = exclamation.getScaledInstance(20, 20, Image.SCALE_FAST);
letter = origletter.getScaledInstance(500, 500, Image.SCALE_FAST);
ReplaceableBackground = ReplaceableBackgroundPic.getScaledInstance(1600, 2336, Image.SCALE_FAST);
resizedHouse = house.getScaledInstance((int) (getWidth() / 5), (int) (getHeight() / 4), Image.SCALE_FAST);
mailbox = origMailBox.getScaledInstance((int)(getWidth() / 6), (int) (getHeight() / 6), Image.SCALE_FAST);
Image PlayerBack = origPlayerBack.getScaledInstance((int)(getWidth() / 30), (int) (getHeight() / 12), Image.SCALE_FAST);
Image PlayerFront = origPlayerFront.getScaledInstance((int)(getWidth() / 30), (int) (getHeight() / 12), Image.SCALE_FAST);
player = new Player(585, 725, (int)(getWidth() / 30), (int) (getHeight() / 12), false, PlayerFront, PlayerBack);
mailboxRegion = new Obstacle(795, 750, 50, 50);
Beginning = new Obstacle(450, 750, 100, 100);
while(goo)
{
if(player.intersects(Beginning) && obstaclesInBeginning)
player.playerX += 10;
if(!player.dead)
player.move(obstacles);
updateCamera();
if(player.experience == 100)
{
player.experience = 0;
player.experienceLv++;
}
checkCondition();
repaint();
wait(100);
}
}
public void wait(int milsec)
{
try{
Thread.sleep(milsec);
} catch(Exception e) {System.out.println(e.getMessage());}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(begin && !pausebool && play) //For beginning
{
g.drawImage(ReplaceableBackground, 150 - cmX, -620 - cmY, null);
g.drawImage(resizedHouse, 600 - cmX, 563 - cmY, null);
g.drawImage(mailbox, 720 - cmX, 670 - cmY, null);
g.drawImage(pause, 900, 10, null);
if(obstaclesInBeginning)
g.drawImage(borderRocks,523 - cmX,755 - cmY,null);
}
if(pausebool)
{
g.drawRect(0, 0, 1000, 1000);
}
if(arrow )
{
g.drawImage(Exclamation, 790 - cmX, 665 - cmY, null);
}
player.drawTo(g, 500, 450);
if(isMailbox)
{
g.setColor(Color.magenta);
g.setFont(new Font("AlgerianBasD", Font.BOLD, 15));
g.drawString("Press 'Q' to open the mailbox!", 600, 300);
}
if(showObstInBegin)
{
obstBegin(g);
}
if(play)
{
g.setColor(Color.black);
g.fillRect(738, 35, 250, 30);
g.fillRect(738, 90, 250, 30);
g.setColor(Color.red);
g.fillRect(738, 35, (int)(player.playerHealth * 2.5), 30);
g.setFont(new Font("AlgerianBasD", Font.BOLD, 20));
g.drawString("Health:", 738, 30);
g.setColor(new Color(128, 255, 210));
g.drawString("Experience:", 738, 85);
g.fillRect(738, 90, (int)(player.experience * 2.5), 30);
g.setColor(new Color(10, 133, 255));
g.drawString("" + player.experienceLv, 850, 110);
}
if(showObstacles)
{
drawObst(g, obstacles);
}
if(showMailRegion)
{
drawMailRegion(g);
}
if(stats)
{
g.setColor(Color.yellow);
g.drawRect(1, 600, 200, 300);
g.setFont(new Font("AlgerianBasD", Font.PLAIN, 15));
g.setColor(Color.black);
g.drawString("Stats:", 50, 620);
g.setColor(new Color(140, 0, 0));
g.drawString("Overall Strength: " + player.completeStrength, 3, 650);
g.setColor(new Color(100, 88, 115));
g.drawString("Armor: " + player.playerArmor, 3, 680);
g.setColor(Color.yellow);
g.drawString("X: " + player.playerX, 3, 710);
g.drawString("Y: " + player.playerY, 3, 740);
}
if(openMail && !mailcontinue)
{
g.drawImage(blackScreen,0, 0, null);
g.drawImage(letter, 250, 200, null);
}
}
public void checkCondition()
{
if(player.intersects(mailboxRegion))
{
isMailbox = true;
} if( isMailbox && !player.intersects(mailboxRegion))
{
isMailbox = false;
}
}
public void drawObst(Graphics g, ArrayList<Obstacle> obst)
{
for(int i = 0; i < obst.size(); i++)
{
g.setColor(Color.magenta);
g.fillRect(obst.get(i).getX() - cmX, obst.get(i).getY() - cmY, obst.get(i).getWidth(), obst.get(i).getHeight());
}
}
public void drawMailRegion(Graphics g)
{
g.setColor(Color.cyan);
g.fillRect(mailboxRegion.getX() - cmX, mailboxRegion.getY() - cmY, mailboxRegion.getWidth(), mailboxRegion.getHeight());
}
public void obstBegin(Graphics g)
{
g.setColor(Color.ORANGE);
g.fillRect(Beginning.getX() - cmX, Beginning.getY() - cmY, Beginning.getWidth(), Beginning.getHeight());
}
public void updateCamera()
{
cmX = player.playerX - getWidth() / 2;
cmY = player.playerY - getHeight() / 2;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_L)
{
if(stats == true)
{
stats = false;
} else
stats = true;
}
if(isMailbox && !openMail && key == KeyEvent.VK_Q)
{
openMail = true;
isMailbox = false;
arrow = false;
obstaclesInBeginning = false;
}
else if(openMail && key == KeyEvent.VK_Q)
{
obstaclesInBeginning = false;
openMail = false;
repaint();
}
if(key == KeyEvent.VK_EQUALS)
{
if(pausebool)
pausebool = false;
else
pausebool = true;
}
if(key == KeyEvent.VK_BACK_SLASH)
{
if(showObstacles == true)
{
showMailRegion = false;
showObstacles = false;
showObstInBegin = false;
} else {
showObstacles = true;
showMailRegion = true;
showObstInBegin = true;
}
}
if(key == KeyEvent.VK_W)
{
player.up = true;
player.aniUp = true;
player.aniDown = false;
player.aniRight = false;
player.aniLeft = false;
}
if(key == KeyEvent.VK_S)
{
player.down = true;
player.aniDown = true;
player.aniUp = false;
player.aniRight = false;
player.aniLeft = false;
}
if(key == KeyEvent.VK_A)
{
player.left = true;
}
if(key == KeyEvent.VK_D)
{
player.right = true;
}
repaint();
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_W)
{
player.up = false;
}
if(key == KeyEvent.VK_S)
{
player.down = false;
}
if(key == KeyEvent.VK_A)
{
player.left = false;
}
if(key == KeyEvent.VK_D)
{
player.right = false;
}
}
public void keyTyped(KeyEvent e)
{
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
}
}
Try running the game on the Event Dispatch Thread. Swing is not thread safe; if you try to create and modify controls off of the Event Dispatch Thread than things may not work as you expect; controls not displaying is a very common result.
EventQueue.invokeLater is the most common way to make tasks run on the EDT, as seen here:
package baseFiles;
import javax.swing.*;
public class SlashRunnerFrame
{
public static void main(String args [])
{
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(); // Create new JFrame (the window)
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
SlashRunnerPanel panel = new SlashRunnerPanel();
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
panel.mainLoop();
}
});
}
}
If this doesn't fix your problem, then your issue is almost certainly in the code of SlashRunnerPanel, not this code.
Try setting a panel.setPreferredSize(new Dimension(someHeight, someWidth)) and after that frame.pack()
EDIT:
Try this:
package baseFiles;
import javax.swing.*;
import java.awt.Dimension;
public class SlashRunnerFrame {
JFrame frame = new JFrame();
SlashRunnerPanel panel = new SlashRunnerPanel();
public SlashRunnerFrame(){
// Create new JFrame (the window)
panel.mainLoop();
panel.setPreferredSize(new Dimension(1000, 800));
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
frame.pack();
}
public static void main(String args[]) {
new SlashRunnerFrame();
}
}
see if it works
modify your panel before adding it to the frame.
I figured it out. When it was loading in the images in the .jar file it was trying to access the folder on my desktop instead of the one in the jar file. So it sent an error because it was trying to access a file that is out of the .jar file. My solution was to replace:
try{
yourImageVariableName = ImageIO.read(new File("yourImagePath1" + ps + "yourImagePath2" + ps + "yourImage.png"));
} catch(Exception e) {e.printStackTrace();}
with:
try{
yourImageVariableName = ImageIO.read(yourClassName.class.getResourceAsStream("/yourImagePath2/yourImage.png"));
} catch(Exception e) {e.printStackTrace();}

IllegalStateException thrown when trying to run my Game Launcher

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.

Resize the panel without revalidation

I have aJPanel in which I draw lines to create an illusion of pencil. This panel is in aScrollPane.
When I resize the panel one call to revalidate() method is automatically placed and all my drawn lines in this panel are gone. Is there any way to keep my drawn line in the panel with the new size ?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author Sanjeev
*/
public class WorkArea extends JFrame implements ActionListener, MouseListener, MouseMotionListener
{
private final int PEN_OP = 1;
private final int ERASER_OP = 2;
private final int SCROLL_OP = 3;
private int mousex = 0;
private int mousey = 0;
private int prevx = 0;
private int prevy = 0;
private boolean initialPen = true;
private boolean initialEraser = true;
private int eraserLength = 5;
private int opStatus = PEN_OP;
private Color mainColor = new Color(0,0,0);
private int drawPanelHeight =1000;
public WorkArea()
{
initComponents();
setLocationRelativeTo(null);
pencilButton.addActionListener(this);
eraserButton.addActionListener(this);
drawPanel.addMouseMotionListener(this);
drawPanel.addMouseListener(this);
drawPanel.add(new TestPane());
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void initComponents() {
headerPanel = new javax.swing.JPanel();
backButton = new javax.swing.JLabel();
headerImage = new javax.swing.JLabel();
controlPanel = new javax.swing.JPanel();
scrollButton = new javax.swing.JButton();
pencilButton = new javax.swing.JButton();
eraserButton = new javax.swing.JButton();
drawingPanel = new javax.swing.JPanel();
drawingScrollPane = new javax.swing.JScrollPane();
drawPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("v0.1");
setBackground(new java.awt.Color(237, 254, 255));
setBounds(new java.awt.Rectangle(0, 0, 513, 693));
setResizable(false);
headerPanel.setBackground(new java.awt.Color(237, 254, 255));
headerPanel.setPreferredSize(new java.awt.Dimension(513, 25));
headerPanel.setLayout(null);
backButton.setBackground(new java.awt.Color(237, 254, 255));
backButton.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
backButton.setForeground(new java.awt.Color(255, 255, 255));
backButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back-arrow.png"))); // NOI18N
backButton.setText("Back");
backButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
backButton.setPreferredSize(new java.awt.Dimension(40, 20));
headerPanel.add(backButton);
backButton.setBounds(0, 3, 40, 20);
headerImage.setBackground(new java.awt.Color(237, 254, 255));
headerImage.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
headerImage.setForeground(new java.awt.Color(255, 255, 255));
headerImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/topbar_ipad_wide.png"))); // NOI18N
headerImage.setText("Work Area");
headerImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headerImage.setPreferredSize(new java.awt.Dimension(513, 25));
headerPanel.add(headerImage);
headerImage.setBounds(0, 0, 513, 25);
controlPanel.setBackground(new java.awt.Color(237, 254, 255));
controlPanel.setPreferredSize(new java.awt.Dimension(90, 670));
controlPanel.setLayout(null);
scrollButton.setBackground(new java.awt.Color(237, 254, 255));
scrollButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/up_down_ipad.png"))); // NOI18N
scrollButton.setPreferredSize(new java.awt.Dimension(60, 60));
scrollButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
scrollButtonMouseClicked(evt);
}
});
controlPanel.add(scrollButton);
scrollButton.setBounds(20, 570, 60, 60);
pencilButton.setBackground(new java.awt.Color(237, 254, 255));
pencilButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pencil_ipad.png"))); // NOI18N
pencilButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
pencilButtonMouseClicked(evt);
}
});
controlPanel.add(pencilButton);
pencilButton.setBounds(20, 450, 60, 60);
eraserButton.setBackground(new java.awt.Color(237, 254, 255));
eraserButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/eraser_ipad.png"))); // NOI18N
eraserButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
eraserButtonMouseClicked(evt);
}
});
controlPanel.add(eraserButton);
eraserButton.setBounds(20, 510, 60, 60);
drawingPanel.setBackground(new java.awt.Color(237, 254, 255));
drawingPanel.setPreferredSize(new java.awt.Dimension(420, 670));
drawingPanel.setLayout(null);
drawingScrollPane.setBorder(null);
drawingScrollPane.setPreferredSize(new java.awt.Dimension(423, 1000));
drawPanel.setBackground(new java.awt.Color(237, 254, 255));
drawPanel.setPreferredSize(new java.awt.Dimension(400, 1000));
drawPanel.setLayout(null);
drawingScrollPane.setViewportView(drawPanel);
drawingPanel.add(drawingScrollPane);
drawingScrollPane.setBounds(0, 0, 424, 670);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 513, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(headerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(controlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 423, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 93, Short.MAX_VALUE)
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 693, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(headerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 668, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 23, Short.MAX_VALUE)
.addComponent(controlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 23, Short.MAX_VALUE)
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "Pen")
opStatus = PEN_OP;
if (e.getActionCommand() == "Eraser")
opStatus = ERASER_OP;
if(e.getActionCommand() == "Scroll")
opStatus = SCROLL_OP;
}
private void pencilButtonMouseClickedTest(java.awt.event.MouseEvent evt)
{
opStatus = PEN_OP;
Graphics g = drawPanel.getGraphics();
if (initialPen)
{
setGraphicalDefaults(evt);
initialPen = false;
g.drawLine(prevx,prevy,mousex,mousey);
}
if (mouseHasMoved(evt))
{
mousex = evt.getX();
mousey = evt.getY();
g.drawLine(prevx,prevy,mousex,mousey);
prevx = mousex;
prevy = mousey;
}
}
private void eraserButtonMouseClickedTest(java.awt.event.MouseEvent evt)
{
opStatus = ERASER_OP;
Graphics g = drawPanel.getGraphics();
if (initialEraser)
{
setGraphicalDefaults(evt);
initialEraser = false;
mousex = evt.getX();
mousey = evt.getY();
System.out.println("Initial Eraser ::::::::x's value is : "+prevx+" , "+mousey+" and y's value is : "+mousex+" , "+mousey);
g.setColor(new java.awt.Color(237,254,255));
g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
//g.setColor(Color.black); //Eraser Border
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
prevx = mousex;
prevy = mousey;
}
if (mouseHasMoved(evt))
{
System.out.println("Eraser ::::::::x's value is : "+prevx+" , "+mousey+" and y's value is : "+mousex+" , "+mousey);
g.setColor(new java.awt.Color(237,254,255));
g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);
mousex = evt.getX();
mousey = evt.getY();
/* Draw eraser block to panel */
g.setColor(new java.awt.Color(237,254,255));
g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
g.setColor(Color.black);//Eraser Border
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
prevx = mousex;
prevy = mousey;
}
}
private void scrollButtonMouseClicked(java.awt.event.MouseEvent evt) {
opStatus = SCROLL_OP;
drawingScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e)
{
int extent,curValue;
extent = drawingScrollPane.getVerticalScrollBar().getModel().getExtent();
curValue = drawingScrollPane.getVerticalScrollBar().getValue()+extent;
if(curValue==drawPanel.getHeight())
{
System.out.println("value of scroll equals to Max value....");
drawPanel.setPreferredSize(new Dimension(423,drawPanelHeight*4));
}
System.out.println("Value: " + curValue + " Max: " + drawingScrollPane.getVerticalScrollBar().getMaximum());
}
});
}
private void eraserButtonMouseClicked(java.awt.event.MouseEvent evt) {
eraserButtonMouseClickedTest(evt);
updateMouseCoordinates(evt);
}
private void pencilButtonMouseClicked(java.awt.event.MouseEvent evt) {
opStatus = PEN_OP;
}
public boolean mouseHasMoved(MouseEvent e)
{
return (mousex != e.getX() || mousey != e.getY());
}
public void setGraphicalDefaults(MouseEvent e)
{
mousex = e.getX();
mousey = e.getY();
prevx = e.getX();
prevy = e.getY();
}
#Override
public void mouseDragged(MouseEvent e)
{
updateMouseCoordinates(e);
switch (opStatus)
{
case PEN_OP : pencilButtonMouseClickedTest(e);
break;
case ERASER_OP: eraserButtonMouseClicked(e);
break;
case SCROLL_OP: scrollButtonMouseClicked(e);
break;
}
}
public void mouseReleased(MouseEvent e)
{
updateMouseCoordinates(e);
switch (opStatus)
{
case PEN_OP : releasedPen();
break;
case ERASER_OP : releasedEraser();
break;
}
}
public void mouseEntered(MouseEvent e)
{
updateMouseCoordinates(e);
}
public void releasedPen()
{
initialPen = true;
}
public void releasedEraser()
{
initialEraser = true;
Graphics g = drawPanel.getGraphics();
g.setColor(mainColor.white);
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
}
public void updateMouseCoordinates(MouseEvent e)
{
String xCoor ="";
String yCoor ="";
if (e.getX() < 0) xCoor = "0";
else
{
xCoor = String.valueOf(e.getX());
}
if (e.getY() < 0) xCoor = "0";
else
{
yCoor = String.valueOf(e.getY());
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WorkArea().setVisible(true);
}
});
}
private javax.swing.JLabel backButton;
private javax.swing.JPanel controlPanel;
private javax.swing.JPanel drawPanel;
private javax.swing.JPanel drawingPanel;
private javax.swing.JScrollPane drawingScrollPane;
private javax.swing.JButton eraserButton;
private javax.swing.JLabel headerImage;
private javax.swing.JPanel headerPanel;
private javax.swing.JButton pencilButton;
private javax.swing.JButton scrollButton;
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
updateMouseCoordinates(e);
}
#Override
public void mouseMoved(MouseEvent e) {
updateMouseCoordinates(e);
}
#Override
public void mousePressed(MouseEvent e) {
updateMouseCoordinates(e);
}
}
I assume you are drawing to the JPanel by using getGraphics() and rendering your out put to it.
You have now seen why you shouldn't do this. When the component is repainted, anything previously painted to is wiped cleaned and you are expected to repaint the contents.
Start by overriding paintComponent and updating all the lines within this method (don't forget to call super.paintComponent
See Performing Custom Painting and Painting in AWT and Swing for more details
For example..
Drawing a rectangle that won't disappear in next paint
MouseEvent is not registering a release when I release the mouse button
Updated with example
This is a modified version of the answer to MouseEvent is not registering a release when I release the mouse button which includes a scroll pane...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
public class MouseDraggedTest {
public static void main(String[] args) {
new MouseDraggedTest();
}
public MouseDraggedTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(new TestPane()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Map<Point, List<Point>> mapPoints;
private Point currentPoint;
public TestPane() {
mapPoints = new HashMap<>(25);
MouseAdapter mouseListener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
currentPoint = e.getPoint();
mapPoints.put(currentPoint, new ArrayList<Point>(25));
}
#Override
public void mouseReleased(MouseEvent e) {
List<Point> points = mapPoints.get(currentPoint);
if (points.isEmpty()) {
mapPoints.remove(currentPoint);
}
currentPoint = null;
}
#Override
public void mouseDragged(MouseEvent me) {
List<Point> points = mapPoints.get(currentPoint);
points.add(me.getPoint());
repaint();
}
};
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 800);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Point startPoint : mapPoints.keySet()) {
List<Point> points = mapPoints.get(startPoint);
for (Point p : points) {
if (startPoint != null) {
g.drawLine(startPoint.x, startPoint.y, p.x, p.y);
}
startPoint = p;
}
}
}
}
}
Updated with a BufferedImage example
Because you need to supply more operations than just drawing, you may find it easier to use BufferedImage as your primary drawing surface and render this to your DrawingPanel
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyPicture {
public static void main(String[] args) {
new MyPicture();
}
public MyPicture() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum DrawOperation {
Draw,
Erase
}
public class TestPane extends JPanel {
private DrawOperation op;
private JToggleButton pencil;
private JToggleButton eraser;
private DrawPane drawPane;
public TestPane() {
setLayout(new BorderLayout());
drawPane = new DrawPane();
MouseAdapter adapter = new MouseAdapter() {
private Point startPoint;
#Override
public void mouseEntered(MouseEvent e) {
drawPane.updateDrawCursor(e.getPoint(), op);
}
#Override
public void mouseExited(MouseEvent e) {
drawPane.removeDrawCursor();
}
#Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
startPoint = null;
}
#Override
public void mouseDragged(MouseEvent e) {
drawPane.applyOperation(startPoint, e.getPoint(), op);
drawPane.updateDrawCursor(e.getPoint(), op);
startPoint = e.getPoint();
}
#Override
public void mouseMoved(MouseEvent e) {
drawPane.updateDrawCursor(e.getPoint(), op);
}
};
drawPane.addMouseListener(adapter);
drawPane.addMouseMotionListener(adapter);
JPanel operations = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
pencil = new JToggleButton("Draw");
eraser = new JToggleButton("Erase");
ButtonGroup bgOps = new ButtonGroup();
bgOps.add(pencil);
bgOps.add(eraser);
operations.add(pencil, gbc);
operations.add(eraser, gbc);
pencil.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
op = DrawOperation.Draw;
}
});
eraser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
op = DrawOperation.Erase;
}
});
add(operations, BorderLayout.WEST);
add(new JScrollPane(drawPane));
}
}
public class DrawPane extends JPanel {
private BufferedImage image;
private Shape drawCursor;
private Point cursorPoint;
private int eraseSize = 20;
public DrawPane() {
image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, 400, 400);
g2d.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (image != null) {
g2d.drawImage(image, 0, 0, this);
}
if (drawCursor != null && cursorPoint != null) {
int x = (cursorPoint.x - (drawCursor.getBounds().width) / 2);
int y = (cursorPoint.y - (drawCursor.getBounds().height) / 2);
g2d.translate(x, y);
g2d.draw(drawCursor);
g2d.translate(-x, -y);
}
g2d.dispose();
}
public void updateDrawCursor(Point point, DrawOperation op) {
cursorPoint = point;
if (op != null) {
switch (op) {
case Draw:
drawCursor = new Ellipse2D.Float(0, 0, 4, 4);
break;
case Erase:
drawCursor = new Ellipse2D.Float(0, 0, eraseSize, eraseSize);
break;
}
} else {
drawCursor = null;
}
repaint();
}
protected void removeDrawCursor() {
drawCursor = null;
repaint();
}
protected void applyOperation(Point fromPoint, Point toPoint, DrawOperation op) {
if (image != null) {
if (op != null) {
Graphics2D g2d = image.createGraphics();
switch (op) {
case Draw:
g2d.setColor(Color.BLACK);
g2d.draw(new Line2D.Float(fromPoint, toPoint));
break;
case Erase:
g2d.setColor(Color.WHITE);
g2d.setStroke(new BasicStroke(eraseSize));
g2d.draw(new Line2D.Float(fromPoint, toPoint));
break;
}
g2d.dispose();
}
}
repaint();
}
}
}

AlphaComposite Transparency with repaint overlaps into black

So I have an image on top of another panel, and that image is transparent so you can see the panel beneath it. What I'm trying to do is use repaint() to fade the image (which is drawn with the drawImage() method in java.awt.Graphics) out until it is completely transparent so you can see the panel beneath it clearly. As of now, the image is just fading into black instead of into a transparent texture.
This is a little bit of my code right now:
paintComponent method:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
float alpha = 1f-(.01f*(float)opcounter);
Graphics2D g2d = (Graphics2D)g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha);
g2d.drawImage(img, 0, 0, null);
}
actionPerformed method that is called for the timer
public void actionPerformed(ActionEvent e)
{
opcouner++;
panel.repaint();
}
Longer (uncondensed) version of my code: (including paintComponent and Mover class for timer)
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension framesize = frame.getSize();
this.setBounds(0,0,framesize.width, framesize.height-61);
if (buff)
{
//this.add(buffer);
if (opcounter <= 255)
{
buffer.setForeground(new Color(250, 250, 250, 0+opcounter));
}
else
{
opcounter = 0;
buff = false;
hand = true;
}
}
if (hand)
{
this.add(handson);
if (opcounter <= 255)
{
handson.setForeground(new Color(250, 250, 250, 0+opcounter));
}
else
{
opcounter = 0;
hand = false;
log = true;
}
}
if (log)
{
this.add(logic);
if (opcounter <= 255)
{
logic.setForeground(new Color(250, 250, 250, 0+opcounter));
}
else
{
opcounter = 0;
log = false;
pan = true;
}
}
if (pan)
{
this.add(panic);
if (opcounter <= 255)
{
panic.setForeground(new Color(250, 250, 250, 0+opcounter));
}
else
{
opcounter = 0;
pan = false;
first = false;
second = true;
try
{
//Thread.sleep(2000);
}
catch(Exception e)
{
System.out.println("thread not slept");
}
System.out.println("opcounter = " + opcounter);
black.setVisible(false);
handson.setVisible(false);
logic.setVisible(false);
panic.setVisible(false);
tutpic = true;
}
}
if (tutpic)
{
if (opcounter <= 200)
{
Graphics2D g2d = (Graphics2D)g.create();
float alpha = 1f-(.01f*(float)opcounter);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2d.drawImage(tut, 0, 0, null);
g2d.dispose();
}
else
{
opcounter = 0;
tutpic = false;
}
}
}
class Mover implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (!tutpic)
opcounter+=4;
else
{
opcounter++;
}
tutorial.repaint();
}
}
Any help would be appreciated. Thanks!
You need to restore the state of the Graphics context BEFORE the paintComponent method exists. This is very important, as the Graphics context is a shared resource, all the components that need to be updated will be given the same Graphics, so now every thing after you component is painted will share the some AlphaComposite...
A better solution would be to create temporary copy of the Graphics context, apply what ever settings you want to it and dispose of it after you have finished. This will ensure that what ever changes you make to the Graphics context won't be carried on after the method exists...
public void paintComponent(Graphics g)
{
super.paintComponent(g);
float alpha = 1f-(.01f*(float)opcounter);
// Create your own copy...
Graphics2D g2d = (Graphics2D)g.create();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha);
g2d.drawImage(img, 0, 0, null);
// Don't forget to dispose of it
g2d.dispose();
}
Remember, you create it, you dispose it!
Update
Try using AlphaComposite.SRC_OVER instead...
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFadeOut {
public static void main(String[] args) {
new TestFadeOut();
}
public TestFadeOut() {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private float alpha = 1f;
private float diff = -0.02f;
private BufferedImage img;
public TestPane() {
try {
img = ImageIO.read(new File("C:\\Users\\swhitehead\\Documents\\My Dropbox\\Ponies\\url.png"));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
alpha += diff;
if (alpha < 0) {
diff *= -1;
alpha = diff;
} else if (alpha > 1f) {
diff *= -1;
alpha = 1f + diff;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
int x = getWidth() - img.getWidth();
int y = getHeight() - img.getHeight();
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
}
Have a look at Composting Graphics for more details...

Categories