Problems with getClass().getResourceAsStream() - java

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.

Related

Set location to image using paintComponent

I have the next code:
public class GalleryPrinter extends JPanel {
private BufferedImage image;
public GalleryPrinter() {
}
public GalleryPrinter(LinkedList<String> paths) {
for(int i = 0; i < paths.size(); i++ ) {
try {
image = ImageIO.read(new File(paths.get(i)));
} catch (IOException ex) {
Logger.getLogger(GalleryPrinter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//g.drawImage(image, 25, 25, this); // see javadoc for more info on the parameters
g.drawImage(image, 0, 0, 140, 200, this);
}
}
But is printing all the images in the same place, defined here:
g.drawImage(image, 0, 0, 140, 200, this);
How I can make this position dynamic? Something like:
If is the first image
g.drawImage(image, 0, 0, 140, 200 * index, this);
To create a vertical image gallery.
Someone can help me with that?

MouseListener starts giving errors mid-runtime

I am currently in progress of making a game involving a button made via JPanel. However, at some point during the program's runtime, the JPanel used to make the button begins to give constant errors whenever a mouse event is registered in the following form:
at java.awt.AWTEventMultiCaster.mouse[eventName](UnknownSource)
It goes so fast that I can't see the initial error, and the error only begins at some point during mid-runtime. Can anybody help me out here? The following is the code for my JPanel:
JPanel trackPanel = new JPanel() {
int state = 0;
#Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
if (dragMe == null) {
state = 1;
}
}
public void mouseExited(MouseEvent e) {
if (dragMe == null) state = 0;
else state = 1;
}
public void mousePressed(MouseEvent e) {
if (dragMe == null && !e.isMetaDown())
{
dragMe = new DragFrameThread(vTrack);
dragMe.start();
}
state = 2;
}
public void mouseReleased(MouseEvent e) {
if (state == 2 && e.isMetaDown()) System.exit(0);
if (dragMe != null) {
dragMe.interrupt();
dragMe = null;
state = 1;
}
}
});
g.setColor(new Color(0, 127, 127, 255));
g.drawRect(0, 0, getWidth()-1, getHeight()-1);
g.setColor(new Color(0, 127, 127, 223));
g.drawRect(1, 1, getWidth()-3, getHeight()-3);
g.setColor(new Color(0, 127, 127, 191));
g.drawRect(2, 2, getWidth()-5, getHeight()-5);
g.setColor(new Color(0, 127, 127, 159));
g.fillRect(3, 3, getWidth()-6, getHeight()-6);
g.drawImage(BootAssets.VTScaledLogo, 0, 0, getWidth(), getHeight(), null);
if (state == 1) g.setColor(new Color(255, 255, 255, 127));
if (state == 2) g.setColor(new Color(0, 0, 0, 127));
if (state != 0) g.fillRect(0, 0, getWidth(), getHeight());
repaint();
}
};
Thanks a bunch!
~Para
I believe the problem is that the paintComponent method is called when the widget is painted. Adding a mouse listener on every paint call is wrong.
Move the addMouseListener out of the paintComponent method and add it separately to the trackPanel. You will need to refactor the code since it currently has the state set and updated in the way the JPanel is defined.
private final AtomicInteger state = new AtomicInteger(0);
JPanel trackPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(new Color(0, 127, 127, 255));
g.drawRect(0, 0, getWidth()-1, getHeight()-1);
g.setColor(new Color(0, 127, 127, 223));
g.drawRect(1, 1, getWidth()-3, getHeight()-3);
g.setColor(new Color(0, 127, 127, 191));
g.drawRect(2, 2, getWidth()-5, getHeight()-5);
g.setColor(new Color(0, 127, 127, 159));
g.fillRect(3, 3, getWidth()-6, getHeight()-6);
g.drawImage(BootAssets.VTScaledLogo, 0, 0, getWidth(), getHeight(), null);
if (state.get() == 1) g.setColor(new Color(255, 255, 255, 127));
if (state.get() == 2) g.setColor(new Color(0, 0, 0, 127));
if (state.get() != 0) g.fillRect(0, 0, getWidth(), getHeight());
}
};
trackPanel.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
if (dragMe == null) {
state.set(1);
}
}
public void mouseExited(MouseEvent e) {
if (dragMe == null) state.set(0);
else state.set(1);
}
public void mousePressed(MouseEvent e) {
if (dragMe == null && !e.isMetaDown())
{
dragMe = new DragFrameThread(vTrack);
dragMe.start();
}
state.set(2);
}
public void mouseReleased(MouseEvent e) {
if (state.get() == 2 && e.isMetaDown()) System.exit(0);
if (dragMe != null) {
dragMe.interrupt();
dragMe = null;
state.set(1);
}
}
});

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.

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)

Categories