Java wait for component to be painted - java

I'm trying to create a program in Java that would display set of images one after another adjusting the size of the frame for each one.
I'm extending JPanel to display an image like this:
public class ImagePanel extends JPanel{
String filename;
Image image;
boolean loaded = false;
ImagePanel(){}
ImagePanel(String filename){
loadImage(filename);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null && loaded){
g.drawImage(image, 0, 0, this);
}else{
g.drawString("Image read error", 10, getHeight() - 10);
}
}
public void loadImage(String filename){
loaded = false;
ImageIcon icon = new ImageIcon(filename);
image = icon.getImage();
int w = image.getWidth(this);
int h = image.getHeight(this);
if(w != -1 && w != 0 && h != -1 && h != 0){
setPreferredSize(new Dimension(w, h));
loaded = true;
}else{
setPreferredSize(new Dimension(300, 300));
}
}
}
Then in event thread I'm doing main work:
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
createGUI();
}
});
In createGUI() I'm going through the set of images:
ImagePanel imgPan = new ImagePanel();
add(imgPan);
for(File file : files){
if(file.isFile()){
System.out.println(file.getAbsolutePath());
imgPan.loadImage(file.getAbsolutePath());
pack();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that my program does the resizing properly, so images are loaded correctly but it doesn't display anything.
If I display only 1 image it works also it works for the last image. I think the problem is that Thread.sleep() is called before image painting is finished.
How can I wait for my ImagePanel to finish painting and start waiting after that?
Or is there another way to solve the problem?
Thanks!
Leonty

All of your code is executing on the Event Dispatch Thread. This effectively causes all user interaction to sleep, since the Event Dispatch Thread is responsible for all user interaction - both input (events) and output (painting).
You need to get your waiting to happen outside of the EDT. You need to know how to execute events on and off the EDT. You do this by creating a new Runnable and then either calling new Thread(runnable) to execute it off the EDT or SwingUtilities.invokeLater(runnable) to make it execute on the EDT. All interaction with Swing components need to take place on the EDT, since Swing objects are not thread safe. All sleeping, waiting, file access, network access, database access, or anything else that may block for indeterminate periods of time must take place off the EDT.
There are many questions on Stack Overflow having to do with the Event Dispatch Thread. I recommend you review these to find more information and code samples to do what you are looking to do in different ways.

Instead of making the thread sleep use a timer and kick off the next image as an event.

It sounds like you want to images appear one by one as they gets loaded (ie as in a web page), is that correct? If so, you wouldn't get that effect with your current code because your UI won't be updated until all images are loaded, this is because you're loading images on EDT (Event Dispatch Thread) which is the same thread that'll do the painting. Painting occurs "when there's time", which in this case means after all images are loaded.
To solve your problem, I'll suggest you create a sub class of SwingWorker like:
public class MyImageLoader extends SwingWorker<Void, String>
{
// Is executed in background thread, EDT can meanwhile load and paint images
#Override
protected Void doInBackground() throws Exception
{
for(File file : files)
{
if(file.isFile()) // Maybe some more check to see if it's an image
{
publish(file.getAbsolutePath());
Thread.sleep(500);
}
}
}
// Executed on EDT
#Override
protected void process(List<String> filePaths)
{
for(String path : filePaths)
{
// Load ImageIcon to UI
}
}
}

Related

Understanding the EDT in a real model with frequent updates

I am writing the Sugarscape simulation in Java and need a working GUI. Sugarscape is a spatial landscape consisting of tiles (of sugar), and agents moving and consuming sugar. For simplicity, I have only one agent and no sugar- I just want to see the agent moving.
For the past 2 weeks I have read into painting in java, concurrency in java, concurrency in swing, I have read filthy rich clients and countless StackOverflow threads, but I must resort to asking a question here.
I need my model separate from the GUI. This presents a problem since 99% of tutorials suggest to call for repaint within other methods. My idea was to run one "tick" of the simulation: all agents move, and then send an Event (my GUI class extends Observer) which then triggers a repaint(); request and update the GUI. However the problem (the misunderstanding) lies with the SwingUtilities.InvokeLater method. My code is:
public void setupGUI()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
System.out.println("GUI is being setup, on EDT now? " + SwingUtilities.isEventDispatchThread());
SugarFrame frame = new SugarFrame(simulation.getWorld());
frame.setVisible(true);
}
});
}
For understanding what is happening I have inserted println's everywhere. The order of events is what confuses me:
Console output:
1.Agent created. Starting Position: X= 19 Y= 46 // This is in the Agent constructor
2.Simulation start. Experiment number: 0
GUI is being setup, on EDT now? true // As you see above, this is WITHIN the SwingUtilities.InvokeLater section. But then the EDT pauses and the real model continues:
Tick number 0
Invoke Agent Actions, fire TickStart Event
TickStartEvent created
Invoke Agent Actions, for-loop starting now
Agent number 0 moving now:
Consuming Sugar now.
Moving now.
Sleeping now.
The Sugarframe has been created and Grid added. All on EDT? true // And there it is back again. The paint component follows and the window with the Agent visible appears.
paintComponent called, on EDT? true
Now, I have read that by putting the main thread to sleep, you give the EDT time to run the repaint. However, this only happens once. Repaint is never called again, and I only ever see one iteration of the model.
I simply do not understand what piece of information I am missing to work with the EDT properly. Swingworker and Swingtimer are suggested regularly, but for every suggestion there is a notion that they are not needed for a model such as mine. Either paintComponent is not called at all, or queued up until the end (and then still not repainting, even if I use thread.sleep).
I'd appreciate any help. Apologies for the long post.
//Edit: as per request some more code.
The entire main method:
public class SimulationController {
static Simulation simulation;
public static final int NUM_EXPERIMENTS = 1;
public SimulationController()
{
Random prng = new Random();
SimulationController.simulation = new Simulation(prng);
}
public void run() {
setupGUI();
for(int i=0; i<NUM_EXPERIMENTS; i++) {
System.out.println("Simulation start. Experiment number: " + i);
simulation.getWorld().addObserver(simulation);
simulation.addObserver(simulation.getWorld());
simulation.run();
}
}
public void setupGUI()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
System.out.println("GUI is being setup, on EDT now? " + SwingUtilities.isEventDispatchThread());
SugarFrame frame = new SugarFrame(simulation.getWorld());
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
SimulationController controller = new SimulationController();
controller.run();
}
}
The paint override in my JPanel class:
#Override
public void paintComponent(Graphics g) {
System.out.println(">>>>>>>>paintComponent called, on EDT? " + SwingUtilities.isEventDispatchThread()+"<<<<<<<<<<");
super.paintComponent(g);
//g.clearRect(0, 0, getWidth(), getHeight());
rectWidth = getWidth() / world.getSizeX();
rectHeight = getHeight() / world.getSizeY();
for (int i = 0; i < world.getSizeX(); i++)
{
for (int j = 0; j < world.getSizeY(); j++)
{
// Upper left corner of this terrain rect
x = i * rectWidth;
y = j * rectHeight;
Tile tile = world.getTile(new Position(i, j));
if (tile.hasAgent())
{
g.setColor(Color.red);
} else
{
g.setColor(Color.black);
}
g.fillRect(x, y, rectWidth, rectHeight);
}
}
}
JPanel class again, update methods:
public void update(Observable o, Object arg)
{
if (arg instanceof TickEnd)
{
TickEvent tickEndevent = new TickEvent();
this.addTickEvent(tickEndevent);
}
}
}
private final BlockingQueue<TickEvent> TICK_EVENTS = new LinkedBlockingQueue<TickEvent>();
/**Runnable object that updates the GUI (I think)**/
private final Runnable processEventsRunnable = new Runnable()
{
public void run()
{
TickEvent event = new TickEvent();
while ((event = TICK_EVENTS.poll()) != null)
{
System.out.println("This is within processEventsRunnable, inside the While loop. Repaint is called now.");
repaint();
}
}
};
/**Add Event to the processing-Events-queue**/
public void addTickEvent(TickEvent event)
{
//System.out.println("This is in the Add TickEvent method, but before the adding. "+TICK_EVENTS.toString());
TICK_EVENTS.add(event);
System.out.println("TickEvent has been added! "+TICK_EVENTS.toString() + "On EDT?" + SwingUtilities.isEventDispatchThread());
if (TICK_EVENTS.size() >= 1)
{
SwingUtilities.invokeLater(processEventsRunnable);
}
}
And last but not least, the JFrame constructor:
/** Sugarframe Constructor**/
public SugarFrame(World world)
{
super("Sugarscape"); // creates frame, the constructor uses a string argument for the frame title
grid = new Grid(world); // variable is declared in the class
add(grid);
setDefaultCloseOperation(EXIT_ON_CLOSE); // specifies what happens when user closes the frame. exit_on_close means the program will stop
this.setContentPane(grid);
this.getContentPane().setPreferredSize(new Dimension(500, 500));
this.pack(); // resizes frame to its content sizes (rather than fixed height/width)
System.out.println("The Sugarframe has been created and Grid added. All on EDT? "+ SwingUtilities.isEventDispatchThread());
this.setVisible(true); // makes the Frame appear on screen
}
The sentences,
I need my model separate from the GUI. This presents a problem since 99% of tutorials suggest to call for repaint within other methods.
and
Now, I have read that by putting the main thread to sleep, you give the EDT time to run the repaint.
don't sound quite right to me, so I'll try to clear things up a bit and maybe If you reevaluate the fundamental ideas you had behind those statements you can find the piece of information that you were missing.
First of all, always keep in mind this scheduling model that we were talking about. You can not say "EDT do this for me now!". It is always "EDT here's one more task you need to do, do it when you are done with whatever you are doing". So the EDT has a queue of "tasks" to do and goes through it consuming one by one.
These tasks are usually created by events: pressing a button gives the EDT a task to do, when the state of a component of the GUI changes some listeners may be notified and enqueue some work in the EDT. However, you can also straight up say "EDT execute this piece of code, later". This is what you do with invokeLater, you schedule a work to do in the EDT whenever it's free. Even if you call invokeLater from the EDT the task is scheduled, not executed at the moment.
The same happens with invokeAndWait yes, the code is executed sequentially as if it was executed at the moment, but it is still an scheduled work. So repaint() is no exception to this. repaint() doesn't repaint the GUI, but rather schedules the repainting of the GUI.
However repaint() is exceptional in the sense that it can be called from outside the EDT! This is not surprising now that we know that the only thing that does is scheduling a certain work, it does not actually mess with the GUI so you can call it wherever you want.
This means that the line
SwingUtilities.invokeLater(processEventsRunnable);
where processEventsRunnable basically executes a repaint() is meaningless and the whole tick system overly complex and unnecesary. You just have to call repaint() when you change something on the GUI or on the data that the GUI feeds on so the changes are reflected on the screen.
Furthermore, if you wanted to do something that needs to be executed in the EDT (like changing the text of a Label with the score) you can just put that code in an invokeLater block in your main thread. That will queue and execute the task properly, you don't need to do your own event queue system.
Keeping all this in mind the following makes no sense:
I have read that by putting the main thread to sleep, you give the EDT time to run the repaint
The GUI will be updated on its own shortly after you call repaint(). The main doing a lot of things and calling a lot of repaints does not prevent the GUI from being updated. However, if you want to "sleep" the main so the pace of the changes is slow so the user can appreciate it on the screen, you should use a timer.
So, as long as your main is not accessing GUI values and methods, feel free to call repaint whenever you are done changing the data, periodically or not.
Edit: Also it sounds a little bit weird that you have a main thread doing things. As you read in the concurrency chapter, usually you just create the GUI in the EDT and then the application is mostly event-driven when buttons are pressed and such. If you need to do changes periodically use a timer. You can use auxiliar threads to do specific non-GUI related heavy work, like reading a file. But you don't usually have an auxiliar thread permanently active as part of the design.
The following is a very simple program that moves an square periodically. I just use a timer to change the data and call repaint(). Note that I'm using a SwingTimer (it is executed in the EDT) since I wanted to check the panel width. Otherwise I could run the code of the timer in any thread.
In your case you probably have your "map" stored independently of the GUI, so you just need to check that data to properly move the coordinates of the agent whenever you want (on keyboard press, periodically...).
It looks like this:
Full code:
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MovingSquareTest
{
int x, y, size, step;
MyPanel panel;
Timer timer;
public static final void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
MovingSquareTest app = new MovingSquareTest();
app.createAndShowGUI();
app.timer.start();
}
});
}
public MovingSquareTest()
{
x = 0;
y = 150;
size = 50;
step = 50;
timer = new Timer(500, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
x += step;
if (x < 0) x = 0;
if (x + size > panel.getWidth()) x = panel.getWidth() - size;
if (x == 0 || x + size == panel.getWidth()) step *= -1;
panel.repaint();
}
});
}
public void createAndShowGUI()
{
JFrame frame = new JFrame("Dance, my square!");
panel = new MyPanel();
frame.add(panel);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private class MyPanel extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(x, y, size, size);
}
}
}

Image not drawing after sleep java

I am trying to have a background image draw then have a character draw over it. My code was working until I added sleep do I didn't get 1500 fps.
package sylvyrfysh.screen;
import javax.swing.*;
import java.awt.*;
import game.infos.Information;
public class ImageLoadDraw extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(){
DisplayMode dm=new DisplayMode(Information.sX,Information.sY,16,DisplayMode.REFRESH_RATE_UNKNOWN);
ImageLoadDraw i = new ImageLoadDraw();
i.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial",Font.PLAIN,24));
s=new Screen();
try{
loadpics();
s.setFullScreen(dm,this);
try{
Thread.sleep(10000);
}finally{
doRun=false;
s.restoreScreen();
}
}catch(Exception e){
e.printStackTrace();
}
}
private void loadpics() {
bg=new ImageIcon("src/sylvyrfysh/screen/maze_icon.png").getImage();
chara=new ImageIcon("src/sylvyrfysh/screen/char.png").getImage();
repaint();
}
public void paint(Graphics g){
if(g instanceof Graphics2D){
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
while(true&&doRun){
g.drawImage(bg,0,0,null);
g.drawImage(bg,0,480,null);
g.drawImage(bg,360,0,null);
g.drawImage(bg,360,480,null);
g.drawImage(bg,720,0,null);
g.drawImage(bg,720,480,null);
g.drawImage(chara,imgX,imgY,null);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Screen s;
public static int imgX=0;
private int imgY=525;
private Image bg,chara;
private Boolean doRun=true;
}
Any ideas on what is causing it and how to fix it? Like I said, with no sleep it works fine.
Swing is an single threaded framework. That is all UI interactions and modifications are expected to be executed within the content of the Event Dispatching Thread, including repaint requests.
Anything that stops, blocks or otherwise prevents this thread from running will prevent the EDT from processing new events, including repaint requests. This will, essentially, make it appear that you program has hung (or stopped responding), because it has.
In your run method you are calling Thread.sleep. This is likely stopping the EDT from processing new events, but because you've actually called the method from the "main" thread, it might actually work, however...
In you paint method, you have an infinite loop AND a Thread.sleep call. These WILL stop the EDT from running, as paint is called from within the context of the EDT.
Painting won't always occur immediately, on some systems, until the paint method returns, it may not be pushed to the device for output, so, even the idea of looping within the paint, regardless of the fact that it will cause problems for the EDT, is a bad idea any way.
Unlike some other UI frameworks, you do not need to implement a "main-loop", Swing takes care of this for you.
Instead, in your paint method, you should simply paint what you need to paint for that cycle and exit.
Instead, you should do something like...
public void paint(Graphics g){
// Painting is a complex series of chained methods, failing to call super.paint
// to cause significant issues
super.paint(g);
// Graphics is guaranteed to be an instance of Graphics2D since I think 1.4
// You should create a copy, so any changes you make are not carried onto the
// next component, Graphics is shared between all the components being painted
// in this paint cycle.
Graphics2D g2=(Graphics2D)g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawImage(bg,0,0,null);
g2.drawImage(bg,0,480,null);
g2.drawImage(bg,360,0,null);
g2.drawImage(bg,360,480,null);
g2.drawImage(bg,720,0,null);
g2.drawImage(bg,720,480,null);
g2.drawImage(chara,imgX,imgY,null);
// If you create, you should dispose of it...
g2.dispose();
}
...instead
Instead of Thread.sleep you should be making use of something like javax.swing.Timer, for example...
s=new Screen();
try{
loadpics();
s.setFullScreen(dm,this);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
s.restoreScreen();
}
});
timer.setRepeats(false);
timer.start();
}catch(Exception e){
e.printStackTrace();
}
Take a look at Concurrency in Swing for more details.
You should also avoid overriding top level containers and especially overriding paint. Painting a complex series of chained method calls, each one performing a particular job, building up on top of each other to produce a final result.
Instead, you should start with a custom component of some kind, extending from JPanel for example, and override it's paintComponent method, making sure you call super.paintComponent before you do any of you own painting.
Take a look at Performing Custom Painting for more details
Well this one Thread.sleep(10000); turn off EVERYTHING for 10 seconds. This is NOT what you want. Even doing it for 30 milisec (which is ~30frames/sec) is not what you want, because it stops even input etc.
You should use Timer. It runs timing in another thread and it sleeps and wake up only that thread automatically for given number of milisec, so it does not affect your program and it can call it only after 30milisec for example.
Still to have good application, this timer should have low value and you should count how long passed through System.nanoTime() and for example repaint once each 30milisec, however read input each 5milisec etc.
I THINK->This is because you need to call the loadpics() parallel, try this
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial",Font.PLAIN,24));
s=new Screen();
loadpics();
s.setFullScreen(dm,this);
try{
new Thread(new Runnable() {
#Override
public void run() {try {Thread.sleep(1000);doRun=false;s.restoreScreen();} catch (Exception e) {}
}
}).start();
}
also setting the doRun as volatile.
private Boolean doRun=true;

Regarding an indefinitely running widget in java

Optional Ref (Regarding bulding gui and widgets in java)
AS said here i am making a simple clock widget. I chose SWt because i found it easier to learn and implement. The widget consists of several layers of concentric circles to impart different colors to each layer. The color of each layer depends on the time of the day and is controlled by a color function. The layers are ready but color function still needs to be made.
I was going through the docs of Java and found that all graphic objects ( like rectangles and circles) must be manually disposed to free system resources. Now my basic problem is this :
Basically i want the widget to run indefinitely until the window containing widget is closed( because there is a minute layer and hour layer which change colors).
How will i free the system resources and will the widget be a memory monster coz of infinteness ? Please answer with ref to Swt.
Additionally i wanted to know if this tyoe of animation strategy is suitable for this widget ? If not please suggest other alternatives keeping in mind my beginner level.
For the clock you need:
A widget to display the time (for example org.eclipse.swt.widgets.Canvas with a PaintListener to draw the clock)
A (daemon) thread which redraws your clock each second. The redraw call must be delegated to the EDT (event dispatch thread)
The thread should run as long as your widget isn't disposed.
To clean up any resources (fonts, colors, etc.) when your widget is disposed, use DisposeListener.
Code template:
public class ClockWidget extends Canvas {
public ClockWidget (Composite parent, int style) {
super(parent, style | SWT.DOUBLE_BUFFERED);
addPaintListener(new PaintListener() {
#Override
public void paintControl (PaintEvent e) {
GC gc = e.gc;
// paint clock on the graphics context
}
});
addDisposeListener(new DisposeListener() {
#Override
public void widgetDisposed (DisposeEvent e) {
// dispose all fonts and colors you created
}
});
final Display display = Display.getCurrent();
Thread timer = new Thread() {
#Override
public void run () {
while (!isDisposed()) {
display.syncExec(new Runnable() {
#Override
public void run () {
if (!isDisposed()) {
redraw();
}
}
});
long msToNextSec = 1000 - (System.currentTimeMillis() % 1000);
try {
Thread.sleep(msToNextSec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
timer.setPriority(Thread.MIN_PRIORITY);
timer.setDaemon(true);
timer.start();
}
}

JTextField on Key Entered flashing black

I am making a game canvas using swing and decided to use JTextField's for the input of a username and password into the panel.
I am buffering an image then rendering it onto the screen instead of drawing everything directly onto the panel real-time.
I have ran into a problem though, I paint a background and have set both of my text fields to opaque, but it seems that whenever I go to enter something into those text field's it flashes a black box where the JTextField is.
It happens in both of my username and password fields. Any idea of what the cause of this could be?
Other helpful information: Whenever I click on a text box, both of the components flash black where the first character would be.
EDIT -- I just noticed that the login button I have also flashes black when MOUSE_ENTERED and MOUSE_EXIT.
public class GamePanel extends JPanel implements Runnable {
public GamePanel(int width, int height) {
this.pWidth = width;
this.pHeight = height;
setController(new LoginGameController(this));
setPreferredSize( new Dimension(pWidth, pHeight));
setBackground(Color.BLACK);
setFocusable(true);
requestFocus(); // the JPanel now has focus, so receives key events
// create game components
addMouseListener(this);
addKeyListener(this);
setLayout(null);
startGame();
}
private void startGame()
// initialise and start the thread
{ if (animator == null) {
animator = new Thread(this);
animator.start();
}
}
public void run() {
while(true) {
gameUpdate();
if(getGraphics() != null){
gameRender(); // render the game to a buffer
paintScreen(); // draw the buffer on-screen
}
try {
Thread.sleep(28);
} catch (InterruptedException e) {}
}
}
private void paintScreen() {
Graphics2D g = (Graphics2D) getGraphics();
if ((g != null) && (img != null))
g.drawImage(img, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
private void gameRender() {
if(getWidth() > 0 && getHeight() > 0)
img = createImage(getWidth(), getHeight());
if(img != null) {
Graphics2D g = (Graphics2D) img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.fillRect(0, 0, pWidth, pHeight);
getController().render(img);
paintComponents(img.getGraphics());
}
}
}
Here is text fields: (from a seperate class entirely calling to the GamePanel using getPanel()...)
//Setup Login fields
usernameTF = new JTextField();
usernameTF.setOpaque(false);
usernameTF.getCaret().setBlinkRate(0);
usernameTF.setForeground(Color.WHITE);
usernameTF.setBounds(USERNAME_FIELD);
usernameTF.setBorder(null);
getPanel().add(usernameTF);
passwordTF = new JPasswordField();
passwordTF.setOpaque(false);
passwordTF.getCaret().setBlinkRate(0);
passwordTF.setForeground(Color.WHITE);
passwordTF.setBounds(PASSWORD_FIELD);
passwordTF.setBorder(null);
getPanel().add(passwordTF);
loginBtn = new JButton();
loginBtn.setOpaque(false);
loginBtn.setBackground(null);
loginBtn.setBorder(null);
loginBtn.setBounds(LOGIN_BUTTON);
loginBtn.addMouseListener(getPanel());
getPanel().add(loginBtn);
Thanks!
The basic problem is, you circumventing Swings repaint process and not honoring the EDT when you up-date your graphics.
JComponent#getGraphics is a temporary/scratch buffer which will be re-draw on the next repaint. Also, if you didn't create the graphics, you shouldn't dispose it!
public void run() {
while(true) {
gameUpdate();
if(getGraphics() != null){
gameRender(); // render the game to a buffer
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
paintScreen(); // draw the buffer on-screen
}
});
} catch (Exception exp) {
exp.printStackTrace(); // please clean this up
}
}
try {
Thread.sleep(28);
} catch (InterruptedException e) {}
}
}
I don't know if this will fix it, but it can't hurt. (This WILL effect you FPS and you should be taking into consideration how long it took to paint and how long you want to wait)
Alternativly, rather then calling paintScreen(), you could call repaint (or have paintScreen do it) and override the paintComponent method to paint your buffer.
This would allow Swing to resume control over the paint process properly.
A window or component has at least three ways to repaint.
on demand from the operating system when it has lost a part of the window buffer.
on demand from a library component when it has changed its state.
manually by manipulating its own frame buffer.
normally, the following pathway is active:
The operating system may request a particular rectangle to be updated. This is picked up by the toolkit. Additionally, a component may signal its change to the toolkit as well through its repaint method. The toolkit keeps collecting an merging incoming repaint requests for a while then asks the window to repaint a particular rectangle. The default action for the window is to paint itself by calling its paintComponent method where it doesn't overlap with solid children and then paint its components recursively.
If you do your own rendering, the toolkit is doing it as well. Since you didn't override your paintComponent, when this method runs, it acts as default. The default action is to do nothing. The toolkit then picks up the empty frame buffer and paints the button (which doesn't paint its background) over it.
You can disable the toolkit's rendering process and do all rendering yourself (grab a buffer, paint into it, then submit). You can call the setIgnoreRepaint(true) method to ignore the requests by OS.

Is this simple Swing-based class thread-safe?

I'm making a proof-of-concept game in Java and decided (for practice but mostly for fun) to make my own simple component with thread-safe double buffering. However, I am not very experienced when it comes to concurrency (specially regarding Swing) and I'm wondering if there are any problems with my implementation that I'm missing.
Implementation as follows:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class GamePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private BufferedImage mBackImage = null;
private BufferedImage mFrontImage = null;
public BufferedImage getBackImage ()
{
return mBackImage;
}
public void swap ()
{
BufferedImage new_back;
//
synchronized (this)
{
new_back = mFrontImage;
mFrontImage = mBackImage;
}
//
int width = getWidth (), height = getHeight ();
if (width > 0 && height > 0)
{
if (new_back == null || new_back.getWidth () != width
|| new_back.getHeight () != height)
new_back = new BufferedImage (width, height,
BufferedImage.TYPE_INT_ARGB);
//
mBackImage = new_back;
}
else
mBackImage = null;
}
#Override
public void paintComponent (Graphics g)
{
synchronized (this)
{
if (mFrontImage == null)
super.paintComponent (g);
else
g.drawImage (mFrontImage, 0, 0, null);
}
}
}
I'm assuming that getBackImage() and swap() will only be called by a single thread (the game loop thread). The paints are triggered via a Swing timer and so are in the EDT. I believe that the simple synchronized-blocks around the use of mFrontImage should be enough to protect against unwanted behavior, allowing the game loop thread to render to the back image and call swap without worrying about the Swing redraws. Am I missing something?
In game thread:
BufferedImage image = gamePanel.getBackPanel();
gamePanel.swap();
Your program would now be in a state where the Event Dispatch Queue and the game thread can access the same image. Meaning funny things could be drawn to the panel if you were drawing to the image whilst the EDT was drawing the image to screen.
For the purposes of reading and writing to the frontImage field on its own then you're thread safe as all access is done inside synchronized blocks. However, the paintComponent method could be better written to reduce the amount of time spent in a synchronized block. That is:
#Override
public void paintComponent (Graphics g)
{
BufferedImage localFrontImage;
synchronized (this)
{
localFrontImage = mFrontImage;
}
if (localFrontImage == null)
super.paintComponent (g);
else
g.drawImage (localFrontImage, 0, 0, null);
}
Swing is pure single threaded and all event must be done on EDT, then I can't see reason for synchronized (this)
use Icon in the JLabel for dispaying Images in the Swing GUI
for any of swap's types, you have look at CardLayout

Categories