Java Swing / AWT with setIcon Gif Animated High Load - java

I Have 1 single java app. ONly Containing 1 JMenu with 48 JMenuItem(s).
Each JMenuItems i set the Icon with Animated GIF.
I have no problem creating it.
And I also have no problem when Running it.
But the problem came, when I running it, and then viewing the JMenuItem.
My GIF(s) Animation seems consuming the PC Process very high!
And the ANimation seems jumping too fast! It's not the usual animation framerate, tough.
So anytime when I run the java app, and then trying the JMenuItem, The CPU Process
is getting higher...!
Look at this Preview: It's taken when My java app runs.
What's the best way to solve this?

What result do you get from this SSCCE? My system peaks to 40 at start-up then jumps to an average of around 20-30. The rendering of the animated GIFs is somewhat jerky.
import java.awt.*;
import javax.swing.*;
class Gif48 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String url = "http://1point1c.org/gif/thum/plnttm.gif";
int w = 12;
int h = 4;
JPanel p = new JPanel(new GridLayout(h,w,2,2));
String pre = "<html><body><img src='";
String post = "'>";
for (int ii=0; ii<w*h; ii++) {
JLabel l = new JLabel(
pre + url + post );
l.setBackground(Color.BLACK);
l.setOpaque(true);
p.add(l);
}
JOptionPane.showMessageDialog(null, p);
}
});
}
}
What's the best way to solve this?
Don't use animated GIFs in the controls of GUIs.

I have found the solutions guys! The GIF Animation has lots of frames. In each frames they have their own timing. When I reopened one single GIF Animation File, I could see clearly that the 0-time framerate is the problem. Now I should Changed it to somewhat above 0.1 framerate, that's all problem solved.

Related

Change screen resolution without resize window or use fullscreen (LWJGL 2)

I have a simple game made with LWJGL 2, and i want it to get the best resolution that's possible for a given window size.
It seems that there is something to do with the DisplayMod, but if i am not in FullScreen mod, it doesn't change game resolution, it just resize the window.
I am able to do what i want in FullScreen via: Display.setDisplayMode(DisplayMode), but as i said, if the Display is not in full screen mod, it just change the window size, but not the resolution.
So my question is, how to get a better resolution without fullscreen/resizing the window?
EDIT (04/08/2017):
To help you to understand my problem, i have recored a short video when a switch to FullScreen/Windowed: https://www.mediafire.com/file/j9t06qa3aaw9e59/Resolution%20bug.mov
To change the game resolution in Fullscreen when you create your frame juste put
Display.setFullscreen(true);
and after create a new ArrayList of DisplayMode
ArrayList<DisplayMode> Mode = new ArrayList<DisplayMode>();
after create your new ArrayList get all screen size support by your graphic cards
try {
DisplayMode[] modes;
modes = Display.getAvailableDisplayModes(); //get all resolution
for (int i=0;i<modes.length;i++) {
DisplayMode current = modes[i]; //add all DisplaMode to arraylist
Resolutions.add(current);
}
} catch (LWJGLException e) {
e.printStackTrace();
}
for (DisplayMode mode : Resolutions) { //optional just to see all resolution
System.out.println(mode.getWidth() + "x" + mode.getHeight() + "x"+mode.getBitsPerPixel() + " " + mode.getFrequency() + "Hz");
}
And to load a DisplayMode
Display.setDisplayMode(Mode.get(int));
In order to set the resolution, you will need to use frame buffers. You will need to render to a frame buffer, then when you are ready to send the framebuffer of the proper resolution to the screen, you will blit the framebuffer to the window's back buffer. Here is a tutorial, albeit in C++. This should get you pointed in the right direction!

Java game keeps crashing after about 2 minutes of runtime (Intellij)

I am using Intellij to program Java.
I am currently trying to make a top down tile based shooter.
My issue is that my game, after approximately 2 minutes, crashes with a popup saying "Java(TM) Platform SE Binary has stopped working. I recorded the time it took for it to crash 3 times: 1m57s, 1m59s, 1m58s.
The game is in a very simple state right now and I am not sure what could be causing the crash. All of the relevant code is in just two classes: GameFrame.java (extends JFrame) and GamePanel.java (which extends JPanel).
GameFrame.java:
package net.magnusfrater.tds.game;
import javax.swing.*;
public class GameFrame extends JFrame {
public static final int width = 1000;
public static final int height = width / 16 * 10;
private GamePanel gp;
public GameFrame () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(width,height);
setResizable(false);
setLocationRelativeTo(null);
setTitle("Time Based Fast Paced Top Down Shooter Demo");
gp = new GamePanel();
add(gp);
setVisible(true);
}
public static void main (String[] args) {
GameFrame gf = new GameFrame();
}
}
GamePanel.java
package net.magnusfrater.tds.game;
import net.magnusfrater.tds.input.Keyboard;
import javax.swing.*;
import java.awt.*;
public class GamePanel extends JPanel implements Runnable {
//panel
private Thread thread;
private static boolean running;
private boolean fpsLock;
//input
private Keyboard kb;
//game
private Game game;
public GamePanel () {
//panel
thread = new Thread(this, "Time Based Fast Paced Top Down Shooter Demo");
running = true;
fpsLock = true;
//input
//kb = new Keyboard();
//addKeyListener(kb);
//game
//game = new Game(1);
thread.start();
}
public void run () {
long iTimeNS = System.nanoTime();
int tickRate = 60;
long ns = 1000000000 / tickRate;
int ups = 0;
int fps = 0;
long iTimeS = System.nanoTime();
long s = 1000000000;
while (running) {
long fTimeNS = System.nanoTime();
if (fTimeNS - iTimeNS >= ns){
iTimeNS = System.nanoTime();
tick();
ups++;
if (fpsLock){
repaint();
fps++;
}
}
if (!fpsLock){
repaint();
fps++;
}
long fTimeS = System.nanoTime();
if (fTimeS - iTimeS >= s){
iTimeS = System.nanoTime();
System.out.println("ups: " + ups + "\tfps: " + fps);
ups = 0;
fps = 0;
}
}
System.exit(0);
}
public void tick () {
if (kb != null)
kb.tick();
if (game != null)
game.tick();
}
#Override
public void update (Graphics g) {
paint(g);
}
#Override
public void paint (Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0,0,GameFrame.width, GameFrame.height);
//if (game != null)
//game.paint(g);
}
public static void quitGame () {
running = false;
}
}
I originally thought that the issue was because of the way that I was loading images for spritesheets or maybe the way I was loading text files for the level design but after reworking both of those, the issue remained.
That left me curious and a little bit fed up so I tried finding out more about the explanation for the crash. First I read more from the popup but it didn't say anything useful: (See below)
Second I looked at the exit code given by Intellij: (See below)
I looked up what exit code 255 was but there wasn't anything useful. The best explanation I could find was that exit code 255 meant that the real exit code was out of range: (See below)
I was out of ideas at this point so I just started plain old googling everything I could think of. The problem with googling "Java(TM) Platform SE Binary has stopped working" is that almost every suggested link is a question about Minecraft. Limiting my search to Stack Overflow yielded me some results, but nothing conclusive. Some of the fixes I found were stuff I already tried (such as not handling input streams properly, not handling buffered reader properly, not disposing of elements, etc). I found these links but none of them were truly related to my issue:
(See below)
(See below)
(See below)
(See below)
(See below)
(See below)
The last fix I tried was to re-install Java SE Development Kit 8u101 AND Java SE Development Kit 8u102. I then restarted Intellij. I then restarted my computer.
Nothing worked.
At this point I think I'm just dumb. I've overlooked something easy I can tell. What am I missing?
(ps~ This is a possibly related issue. So if I run my game with almost no content in it with the fps not locked to 60, I get really absurd numbers of frames per second. I didn't think that fps as high as 7,000,000 was possible. I think. I don't know. Have I programmed that wrong as well? Here is a related picture of my ups/fps output: [see below])
(SEE HERE) So Stack Overflow doesn't allow members with a score within a certain threshold post more than 2 links and allows absolutely no posting of images. So here is a link to a google doc with all of the links and images I mentioned above:
https://docs.google.com/document/d/1XrBuVio19GmkFz0EfRzXVp5AJmM5zPfVO6vK3oS3Eaw/edit?usp=sharing
Try and set your -Xmx to something like 2G and see if it runs longer. If so, something is allocating memory and maybe you have that other setting set that exits instead of garbage collecting for some reason.
Also, try changing your code to limit things using Guava's RateLimiter.
…
// class level
final RateLimiter frameLimiter = RateLimiter.create(60.0);
final RateLimiter outputLimiter = RateLimiter.create(1.0);
…
// in run method
while (running) {
frameLimiter.acquire();
repaint();
fps++;
if (outputLimiter.tryAcquire()){
System.out.println("fps: " + fps);
fps = 0;
}
}
I've removed ups and tick(). You should do your work after repainting and I don't think you want to do more work than needed for the next frame, which at the soonest should be at your max rate. Later you'll need to add logic to handle skipping work when frames are being skipped. I might make more sense to increment the fps within repaint.
You could put the output in its own thread and only acquire that limiter if you synchronized the increments and resetting of fps.

JAVACV videocapture read stops taking new pictures and just repeats the same one, why is it doing this?

I am currently using the Java Open Cv Library to take a series of consecutive images from a camera. The frame that is captured is then passed to another thread which saves the image.
But, for some reason after it takes a certain amount it stops taking new images and instead just repeats the previous one.
If i ask it to take 10 it stops at 5, and for 20 it stops at 11, so it isn't the same value each time.
The code is currently inside of a thread but i do not think that this is affecting it in any way.
Here is the current code.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camera = new VideoCapture(0);
camera.open(0);
Mat frame = new Mat();
for (int i = 0; i < 20; i++) {
camera.read(frame);
fileName = "Captures/" + timetoNano + ".png";
fileTime = timetoNano;
fileToSave = frame;
ImageProperties newProperties = new ImageProperties(fileName,
fileToSave, fileTime);
bufferImageProps.add(newProperties);
}
If i put camera.open(0) inside of the for loop, this does fix the issue, it does however decrease performance greatly and i don't think it has to be there as it works up until this "breaking point".
Any feedback would be greatly appreciated.
I think i have found the solution. I moved the line
Mat frame = new Mat();
Inside of the for loop.
Because of this it means that each time you capture a frame you are capturing it onto a null frame, this seems to fix the issue.

Can't play gif when using freeTTS Voices - Java

I am using freeTTS to speak out some text, in the background i want a animated gif to keep playing
When i try this: as soon as the voice starts speaking, the image in background gets hanged even if i keep it in some other JFrame... and after the speech is completed it starts moving. I want it to run properly without pauses.
I am placing a animated gif in a label by importing it to my application and changing the icon to that image in label' properties.
Edit
Here is my code:
private void RandomjBActionPerformed(java.awt.event.ActionEvent evt) {
Voice voice;
voice = voiceManager.getVoice(VOICENAME);
voice.allocate();
voice.speak("Daksh");
}
I am actually using a lot of setVisible, setText, declaration of integers, calculating on them but i have removed them to simplify the code for you to understand. Still it gives the same problem if executed.
The button 'RandomjB' is clicked from another button by the following code:
final Timer timer = new Timer(zad, new ActionListener() {
int tick = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + ++tick);
RandomjB.doClick();
final int col = Integer.parseInt(t3.getText());;
if (tick >= col) {
((Timer) e.getSource()).stop();
for(int g=0; g<col; g++){
jButton2.setVisible(true); // Check Button -> Visible
}
}
}
});
timer.setInitialDelay(0);
System.out.format("About to schedule task.%n");
timer.start();
System.out.format("Task scheduled.%n");
It is hard to tell without the code, I however assume that you loop the speech synthesis within the one and only Swing-Thread and therefore block all kind of window updates as long as the speech loop is in progress.
As stated by Shaun Wild: you need to use a second Thread for the speech loop.
You may want to do some research on Threads and Concurrency
These allow two things to operate simultaneously, this is just my assumption.
Assuming that you instantiate some kind of class for the FreeTTS you may want to do something like this
FreeTTSClass tts;
new Thread(new Runnable(){
public void run(){
tts = new FreeTTSClass();
}
}).start();

How do you Scale and display specific sections of an image using Java

So I took it upon myself to learn Java.
A decision I regret more with every crash of Elipse.
Fortunately I have actually managed to get this block of my self inflicted project to actually 'work' but obviously being self taught I am quite sure I have made a lot of errors in my layout and
In total, the program will create a JFrame then stick a JscrollPane inside that into which it inserts a a JPanel (wrapPage). It then loops through a process that generates an array of TMTile Objects which are extended JPanels containing the tile images which are drawn from a source folder of jpg images. Once that has finished it places that array as a grid using the GridBagLayout within the wrapPage Jpanel resulting in a nice little perfect maze.
That all works perfectly, but the big let down is that the size of the image used to create the tiles is dictating everything. I can't for the life of me figure out how to scale the image and efforts to find a suitable process have only got me methods of creating new image files or alternating between stretching and tiling images to fit a within their containing component or suggestions I just couldn't follow to save my life.
Fortunately. The image handling is part of the TMTile class file! This means I can show you the entire relevant bit of script;
The following are imported for use in this file
from java.awt: Color, GridBagConstraints, GridBagLayout, Insets
from javax.swing: ImageIcon, JLabel, JPanel
public class TMTile extends JPanel
{
private static final long serialVersionUID = 1L;
private int paths; // values 0 to 15, uses bitwise & | to set or check open paths
private JLabel tileWrap; // to contain the ImageIcon
private ImageIcon tileImg; // the image to be used
GridBagConstraints bag;
public TMTile( int inDir ) // called by maze constructor
{
paths = inDir;
this.setBackground( Color.RED ); // so I can tell if the image didn't load right
this.setLayout( new GridBagLayout() ); // GridBagLayout is probably overkill but it what I am most familiar with now.
bag = new GridBagConstraints();
bag.insets = new Insets( 0, 0, 0, 0 );
tileImg = tileImage( paths );
tileWrap = new JLabel( "", tileImg, JLabel.CENTER );
this.add( tileWrap, bag );
}
public void open( int inDir ) // called by maze constructor when tile value changes resulting from the perfect maze backtrack method
{
paths = paths | inDir;
tileImg = tileImage( paths );
tileWrap.setIcon( tileImg );
}
private ImageIcon tileImage( int paths ) // created to cut down on duplicate code and make updating easier
{
String inEnd;
if(paths < 10)
{
inEnd = "0"+ paths;
}
else
{
inEnd = ""+ paths;
}
ImageIcon tileImg = new ImageIcon( "imgs/MAZE_"+ inEnd +".jpg" );
System.out.println( "imgs/MAZE_"+ inEnd +".jpg" );
Image newimg = tileImg.getImage().getScaledInstance( 40, 40, java.awt.Image.SCALE_DEFAULT );
tileImg = new ImageIcon( newimg );
return tileImg;
}
public int getOpen()
{
return paths;
}
}
Thanks to nachokk and MadProgrammer I now once again have a working maze program and the maze tiles are scalable. That just leaves the final goal of doing away with individual tile .jpgs and switching to a single image file with all 16 stored within in.
What I would love to have is the ability to utilize a single large image file which is divided into 16 sections, 1 section for each tile value. I started out working toward this goal but had to abandon it fairly quickly as I couldn’t figure out how to only display the section of the image needed which would also need to be scaled in the way described above.
Since I am very much still learning Java advice on any alternatives is welcome but ideally I would love to know how to accomplish this as planned.

Categories

Resources