ImageIcon and refresh

I want to make a simple animation using ImageIcon and threats but my Image isn't refreshing. It is loading first one and it stops.

Here is my code.

import java.awt.*;

import java.awt.event.*;

import java.util.concurrent.Semaphore;

import javax.swing.*;

import javax.swing.event.* ;

import java.util.Hashtable;

publicclass LudozercySwing

implements ActionListener, ItemListener{

JFrame frame;

JScrollPane scrollPane;

JTextArea output;

ImageIcon obraz;

.....................................

.....................................

.....................................

/** klasa Kucharz */

class Kucharzimplements Runnable

{

/** zas骲 Misjonarz */

Misjonarz misjonarz;

publicint porcje;

/** konstruktor

*@param Misjonarz referencja do zasobu */

Kucharz(int porcje, Misjonarz misjonarz )

{

this.misjonarz = misjonarz;

this.porcje = porcje;

// uruchom w箃ek Kucharz

new Thread(this ).start();

}

/** metoda run w箃ku Kucharza

* Kucharz powinien

* - zabrac dostepnego Misjonarza

* - pokroic go na n czesci */

publicvoid run()

{

/** "kroimy" misjonarzy **/

int iloscMisjonarzy = tab[1];// brak w zalozeniach ilosci misjonarzy dlatego bedzie ich 7

for(int i=0;i<iloscMisjonarzy;i++)

{

/**Ustaw w kolejce Ludozercow**/

output.append("\nUstawiam nowa kolejke do zjedzenia..."+(int)(i+1)+" Misjonarza");

/** jesli pusty zasob to pokruj misjonarz*/

output.append("\nKroimy misjonarza na "+porcje+" porcji");

obraz =new ImageIcon("ikony/kot.jpg");

for(int j=1; j><=porcje; j++ )

misjonarz.put( j );// kroimy na porcje misjonarza i wrzucamy do kotla

misjonarz.KucharzDone();// misjonarz w calosci pokrojony

/** Kucharz przysypia */

if(!misjonarz.PorcjeEmpty)

try

{

Thread.sleep(200);// Usypianie watku kucharza

output.append("\nKucharz wstaje.");

}

catch( InterruptedException e )

{}

}

output.append("\nKONIEC gotowania");

obraz =new ImageIcon("ikony/kucharz1.jpg");

}

}

Thanks for help :-)

[4196 byte] By [Lukasz_1981a] at [2007-10-3 4:18:27]
# 1

A few things...

1. I'm not sure if your loops are just exiting - what is the value of "tab[1]" that controls your outer loop? What is the value of "porcje" that controls the inner one? Once those loops are finished the thread will die.

2. You're loading the same image ("ikony/kot.jpg") on every iteration so it'll never look any different.

3. You don't seem to be reapinting anything.

I would suggest that you might be better off preloading the images and using a javax.swing.Timer for update as well, though it's hard to see what you're doing as it all seems to be in Polish or something :o)

itchyscratchya at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 2

This is not whole code. Loops are working without problem, and in tab[1] I put number of missionary beacuse whole program must show how cannibal eat missionary in threats, so I only put a part of code to show that ImageIcon doesn't seem to change.

I thought it will be when i put only obraz = new ImageIcon("ikony/kot.jpg"); and change image to different.

Could you tell me how to refresh Icons? I must creat new image or only refresh it?

Lukasz_1981a at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 3

> This is not whole code.

And that would be the problem. Posting bits and pieces doesn't show us the context of how the icon is actually used in your program.

a) Are you adding the icon to a label so it can be painted? If so then you need to use label.setIcon(....);

b) Do you have a custom paintComponent() method that is drawing the image of the Icon. If so then you need to invoke your paint logic.

If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program[/url] that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags[/url] so the code retains its original formatting.

camickra at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 4

Here is whole code

import java.awt.*;

import java.awt.event.*;

import java.util.concurrent.Semaphore;

import javax.swing.*;

import javax.swing.event.* ;

import java.util.Hashtable;

public class LudozercySwing

implements ActionListener, ItemListener{

JFrame frame;

JScrollPane scrollPane;

JTextArea output;

ImageIcon obraz;

String newline = "\n";

int tab[] = new int[3];

int addtime;

/** tablica Ludozercow */

/*

Ludozerca tabLudozerca[];

new Kucharz (m,misjonarz); // kroimy misjonarza na m porcji

tabLudozerca = new Ludozerca[n];// tablica n ludozercow ktorzy beda ucztowac przy kotle

for (int i=0; i<n; i++)// wype&#322;nienie tablicy ludozercami

tabLudozerca[i] = new Ludozerca ("Ludozerca "+(int)(i+1), misjonarz,n);

*/

public JMenuBar stworzMenuBar()

{

// tworzymy komponenty potrzebne do menu

JMenuBar menuBar;

JMenu menu;

JMenuItem menuItem;

JCheckBoxMenuItem cbMenuItem;

//tworzymy menu

menuBar = new JMenuBar();

//budujemy pierwsze menu

menu = new JMenu("Ustawienia");

//kalwisz skrotu

menu.setMnemonic(KeyEvent.VK_U);

menu.getAccessibleContext().setAccessibleDescription(

"Ustawienia programu");

menuBar.add(menu);

//grupa elementow JMenuItems

menuItem = new JMenuItem("Start programu",

KeyEvent.VK_S);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_S, ActionEvent.ALT_MASK));

menuItem.addActionListener(this);

menuItem.setActionCommand("Start");

menu.add(menuItem);

menu.addSeparator();

menuItem = new JMenuItem("Ilosc porcji",

KeyEvent.VK_P);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_P, ActionEvent.ALT_MASK));

menuItem.getAccessibleContext().setAccessibleDescription(

"Na ile porcji pokroic misjonarza");

menuItem.setActionCommand("Ilosc porcji");

menuItem.addActionListener(this);

menu.add(menuItem);

menuItem = new JMenuItem("Ilosc misjonarzy",

KeyEvent.VK_M);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_M, ActionEvent.ALT_MASK));

menuItem.setActionCommand("Ilosc misjonarzy");

menuItem.addActionListener(this);

menu.add(menuItem);

menuItem = new JMenuItem("Ilosc ludozercow",

KeyEvent.VK_L);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_L, ActionEvent.ALT_MASK));

menuItem.setActionCommand("Ilosc ludozercow");

menuItem.addActionListener(this);

menu.add(menuItem);

//check box menu

menu.addSeparator();

cbMenuItem = new JCheckBoxMenuItem("Informuj o zjedzeniu misjonarza");

cbMenuItem.setMnemonic(KeyEvent.VK_I);

cbMenuItem.addItemListener(this);

menu.add(cbMenuItem);

menu.addSeparator();

menuItem = new JMenuItem("Pokaz parametry",

KeyEvent.VK_P);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_P, ActionEvent.ALT_MASK));

menuItem.setActionCommand("Pokaz parametry");

menuItem.addActionListener(this);

menu.add(menuItem);

menuItem = new JMenuItem("Koniec",

KeyEvent.VK_X);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_X, ActionEvent.ALT_MASK));

menuItem.setActionCommand("Koniec");

menuItem.addActionListener(this);

menu.add(menuItem);

//drugie menu w pasku menu.

menu = new JMenu("O programie..");

menu.setMnemonic(KeyEvent.VK_O);

menu.getAccessibleContext().setAccessibleDescription(

"O Autorach");

menuBar.add(menu);

//dodajemy obiekt do menu

menuItem = new JMenuItem("Informacje",

KeyEvent.VK_I);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_I, ActionEvent.ALT_MASK));

menuItem.setActionCommand("Informacje");

menuItem.addActionListener(this);

menu.add(menuItem);

return menuBar;

}

public Container createContentPane(){

JButton start,ludozerca,misjonarz,porcje,informacje;

JPanel contentPane = new JPanel(new BorderLayout());

contentPane.setOpaque(true);

//utworzenie paska toolbar

JToolBar toolBar = new JToolBar("Still draggable");

//pobranie ikon dla przyciskow

ImageIcon iconStart = createImageIcon("ikony/eating.jpg");

start = new JButton("Start");

start.setActionCommand("Start");

start.setIcon(iconStart);

start.addActionListener(this);

start.setToolTipText("Rozpoczecie programu po wprowadzeniu danych");

toolBar.add(start);

//separator

toolBar.addSeparator();

//pobranie ikon dla przyciskow

ImageIcon iconPorcje = createImageIcon("ikony/meat.jpg");

porcje = new JButton("Porcje");

porcje.setActionCommand("Ilosc porcji");

porcje.setIcon(iconPorcje);

porcje.setToolTipText("Na ile porcji pokroic posilek");

porcje.addActionListener(this);

toolBar.add(porcje);

//pobranie ikon dla przyciskow

ImageIcon iconMisjonarz = createImageIcon("ikony/pope.jpg");

misjonarz = new JButton("Misjonarze");

misjonarz.setActionCommand("Ilosc misjonarzy");

misjonarz.setIcon(iconMisjonarz);

misjonarz.setToolTipText("Ile misjonarzy bedzie jesc posilek");

misjonarz.addActionListener(this);

toolBar.add(misjonarz);

//pobranie ikon dla przyciskow

ImageIcon iconLudozerca = createImageIcon("ikony/exp_04.gif");

ludozerca = new JButton("Ludozercy");

ludozerca.setActionCommand("Ilosc ludozercow");

ludozerca.setIcon(iconLudozerca);

ludozerca.setToolTipText("Ile misjonarzy bedzie jesc posilek");

ludozerca.addActionListener(this);

toolBar.add(ludozerca);

//separator

toolBar.addSeparator();

//pobranie ikon dla przyciskow

ImageIcon iconHelp = createImageIcon("ikony/info.jpg");

informacje = new JButton("Informacje");

informacje.setActionCommand("Informacje");

informacje.setIcon(iconHelp);

informacje.setToolTipText("Autorzy programu");

informacje.addActionListener(this);

toolBar.add(informacje);

//jesli bedzie true to mozna pasek przeciagac po ekranie

toolBar.setFloatable(false);

toolBar.setRollover(true);

contentPane.add(toolBar, BorderLayout.PAGE_START);

//Create the slider

addtime = 1000;

JSlider szybkosc = new JSlider(JSlider.HORIZONTAL, 0, 2000, 1000);

szybkosc.addChangeListener(new SliderListener());

szybkosc.setMajorTickSpacing(100);

szybkosc.setPaintTicks(true);

contentPane.add(szybkosc, BorderLayout.PAGE_END);

//Create the label table

Hashtable etykiety = new Hashtable();

etykiety.put( new Integer( 0 ), new JLabel("Szybciej") );

etykiety.put( new Integer( 1000 ), new JLabel("Normalnie") );

etykiety.put( new Integer( 2000 ), new JLabel("Wolniej") );

szybkosc.setLabelTable( etykiety );

szybkosc.setPaintLabels(true);

szybkosc.setBorder(BorderFactory.createEmptyBorder(0,0,0,10));

//Create the label for the animation

obraz = new ImageIcon("ikony/kucharz.jpg");

JLabel picture = new JLabel(obraz, JLabel.CENTER);

picture.setAlignmentX(Component.CENTER_ALIGNMENT);

picture.setBorder(BorderFactory.createCompoundBorder(

BorderFactory.createLoweredBevelBorder(),

BorderFactory.createEmptyBorder(10,10,10,10)

));

contentPane.add(picture, BorderLayout.EAST);

//Tworzymy scrolowany obszar tekstowy

output = new JTextArea(5, 30);

output.setEditable(false);

scrollPane = new JScrollPane(output);

//Dodaje obszat tekstowy do content pane'a.

contentPane.add(scrollPane, BorderLayout.CENTER);

return contentPane;

}

/** Listens to the slider. */

class SliderListener implements ChangeListener

{

public void stateChanged(ChangeEvent e)

{

JSlider source = (JSlider)e.getSource();

if (!source.getValueIsAdjusting())

{

int fps = (int)source.getValue();

// wprowadzamy opozninienie

addtime = fps;

output.append("Wolniej o "+fps+" [s]"+newline);

}

}

}

public void createPopupMenu() {

JMenuItem menuItem;

//Create the popup menu.

JPopupMenu popup = new JPopupMenu();

menuItem = new JMenuItem("Start");

ImageIcon iconStart = createImageIcon("ikony/eating.jpg");

menuItem.setActionCommand("Start");

menuItem.setIcon(iconStart);

menuItem.addActionListener(this);

popup.add(menuItem);

menuItem = new JMenuItem("Pokaz parametry");

ImageIcon iconParametry = createImageIcon("ikony/hamburger.jpg");

menuItem.setIcon(iconParametry);

menuItem.setActionCommand("Pokaz parametry");

menuItem.addActionListener(this);

popup.add(menuItem);

//Add listener to the text area so the popup menu can come up.

MouseListener popupListener = new PopupListener(popup);

output.addMouseListener(popupListener);

}

// Shows Information dialog

void createMessageDialog(String tekst){

JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(scrollPane),tekst);

}

/*

// Shows Input Dialog

void createInputDialog(String tekst,int which)

{

String ilosc = (String)JOptionPane.showInputDialog(JOptionPane.getFrameForComponent(scrollPane),tekst);

try{

int dane = Integer.parseInt(ilosc);

if(dane><0)

{

createMessageDialog("Wpisz liczbe bez minusa");

}

else

{

output.append("Wpisano "+tekst+" "+ilosc+newline);

createMessageDialog("Wpisano "+tekst+newline+ilosc);

paramInfo(dane,which);

}

}

catch(NumberFormatException e){

createMessageDialog("Zly wpis");

}

}

*/

int createYesNoDialog(String tekst)

{

Object[] options = {"Tak", "Nie"};

int i = JOptionPane.showOptionDialog(JOptionPane.getFrameForComponent(scrollPane),

tekst,

"Okno wyboru",

JOptionPane.YES_NO_OPTION,

JOptionPane.QUESTION_MESSAGE,

null,

options,

options[0]);

return i;

}

class createSpinner

implements ActionListener{

JFrame frame;

JPanel panel;

JButton stan;

JSpinner spinner;

SpinnerModel newModel;

/** metoda obslugujaca zdarzenie typu ActionEvent

*@param e nadchodzace zdarzenie ActionEvent

*/

public void actionPerformed(ActionEvent e) {

frame.setVisible(false);

}

//frame.setSize(100,100);

// add to panel

createSpinner(String label){

frame = new JFrame(label);

panel = new JPanel(new GridLayout(3,1));

stan = new JButton("OK");

//zamykanie okna

stan.addActionListener(this);

frame.add(panel);

Integer value = new Integer(0);

Integer min = new Integer(0);

Integer max = new Integer(20);

Integer step = new Integer(1);

newModel = new SpinnerNumberModel(value, min, max, step);

spinner = new JSpinner(newModel);

//spinner.addChangeListener(this);

spinner.getEditor();

spinner.setValue(min);

//add a change listener

if (label == "Ilosc porcji")

newModel.addChangeListener(

new ChangeListener() {

public void stateChanged(

ChangeEvent e) {

int wartosc = Integer.parseInt(((Integer)newModel.getValue()).toString());

tab[0] = wartosc;

output.append("Ilosc porcji po zmianie: "+wartosc+newline);

}

});

else if (label == "Ilosc misjonarzy")

newModel.addChangeListener(

new ChangeListener() {

public void stateChanged(

ChangeEvent e) {

int wartosc = Integer.parseInt(((Integer)newModel.getValue()).toString());

tab[1] = wartosc;

output.append("Ilosc misjonarzy po zmianie: "+wartosc+newline);

}

});

else if (label == "Ilosc ludozercow")

newModel.addChangeListener(

new ChangeListener() {

public void stateChanged(

ChangeEvent e) {

int wartosc = Integer.parseInt(((Integer)newModel.getValue()).toString());

tab[2] = wartosc;

output.append("Ilosc ludozercow po zmianie: "+wartosc+newline);

}

});

panel.add(spinner);

panel.add(new JLabel(label));

panel.add(spinner);

panel.add(stan);

frame.setSize(150, 100);

frame.setVisible(true);

}

}

public void actionPerformed(ActionEvent event){

if("Start".equals(event.getActionCommand())){

output.append("Wcisnieto START"+newline);

//createMessageDialog(source.getText());

Ludozercy nowy = new Ludozercy();

}

if("Ilosc porcji".equals(event.getActionCommand())){

output.append("Wcisnieto Ilosc Porcji"+newline);

createSpinner porcje = new createSpinner("Ilosc porcji");

//createInputDialog(source.getText(),0);

}

if("Ilosc misjonarzy".equals(event.getActionCommand())){

output.append("Wcisnieto Ilosc misjonarzy"+newline);

//createInputDialog(source.getText(),1);

createSpinner misjonarze = new createSpinner("Ilosc misjonarzy");

}

if("Ilosc ludozercow".equals(event.getActionCommand())){

output.append("Wcisnieto Ilosc ludozercow"+newline);

//createInputDialog(source.getText(),2);

createSpinner ludozercy= new createSpinner("Ilosc ludozercow");

}

if("Koniec".equals(event.getActionCommand())){

output.append("Wcisnieto Koniec"+newline);

int i = createYesNoDialog("Koniec");

if(i==0)

System.exit(0);

else

output.append("Wracam do proramu"+newline);

}

if("Pokaz parametry".equals(event.getActionCommand())){

output.append("Wcisnieto Pokaz parametry"+newline);

createMessageDialog("Dane pobrane\n"+"porcje "+tab[0]

+newline+"misjonarze "+tab[1]+newline+"ludozercy "+tab[2]);

}

if("Informacje".equals(event.getActionCommand())){

createMessageDialog("Informacje o autorach:\nPodsiadlo Lukasz\nMittman Przemyslaw\nKowalski Zenon");

}

/*

if ("OK".equals(event.getActionCommand())) {

output.append("wprowadzono dane");

System.exit(1);

}

*/

}

public void itemStateChanged(ItemEvent e) {

JMenuItem source = (JMenuItem)(e.getSource());

String s = "Pokaz komunikat po zjedzeniu pojedeynczgo misjonarza"

+ newline

+ source.getText()

+ newline

+ "Wybrano: "

+ ((e.getStateChange() == ItemEvent.SELECTED) ?

"zaznaczone":"niezaznaczone");

output.append(s + newline);

output.setCaretPosition(output.getDocument().getLength());

}

// Returns just the class name -- no package info.

protected String getClassName(Object o) {

String classString = o.getClass().getName();

int dotIndex = classString.lastIndexOf(".");

return classString.substring(dotIndex+1);

}

/** Returns an ImageIcon, or null if the path was invalid. */

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = LudozercySwing.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("Couldn't find file: " + path);

return null;

}

}

/**

* Create the GUI and show it. For thread safety,

* this method should be invoked from the

* event-dispatching thread.

*/

private static void createAndShowGUI() {

//Make sure we have nice window decorations.

JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.

JFrame frame = new JFrame("Ludozercy");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create/set menu bar and content pane.

LudozercySwing demo = new LudozercySwing();

frame.setJMenuBar(demo.stworzMenuBar());

frame.setContentPane(demo.createContentPane());

//Create and set up the popup menu.

demo.createPopupMenu();

//Create and set up spinner.

//JDesktopPane desktop;

//desktop = new JDesktopPane(); //a specialized layered pane

//frame.setContentPane(desktop);

//Display the window.

frame.setSize(500, 300);

frame.setVisible(true);

}

/** gł體na klasa programu */

class Ludozercy

{

/** zas骲 Misjonarz */

Misjonarz misjonarz = new Misjonarz();

Ludozercy()

{

output.append("m - porcji:"+tab[0]+"\nn - ludozercow"+tab[2]+newline);

Ludozerca tabLudozerca[];

new Kucharz (tab[0],misjonarz); // kroimy misjonarza na m porcji

tabLudozerca = new Ludozerca[tab[2]];// tablica n ludozercow ktorzy beda ucztowac przy kotle

for (int i=0; i<tab[2]; i++)// wype&#322;nienie tablicy ludozercami

tabLudozerca[i] = new Ludozerca ("Ludozerca "+(int)(i+1), misjonarz,tab[2]);

}

/** klasa Kucharz */

class Kucharz implements Runnable

{

/** zas骲 Misjonarz */

Misjonarz misjonarz;

public int porcje;

/** konstruktor

*@param Misjonarz referencja do zasobu */

Kucharz(int porcje, Misjonarz misjonarz )

{

this.misjonarz = misjonarz;

this.porcje = porcje;

// uruchom w&#261;tek Kucharz

new Thread( this ).start();

}

/** metoda run w&#261;tku Kucharza

* Kucharz powinien

* - zabrac dostepnego Misjonarza

* - pokroic go na n czesci */

public void run()

{

/** "kroimy" misjonarzy **/

int iloscMisjonarzy = tab[1];// brak w zalozeniach ilosci misjonarzy dlatego bedzie ich 7

for(int i=0;i<iloscMisjonarzy;i++)

{

/**Ustaw w kolejce Ludozercow**/

output.append("\nUstawiam nowa kolejke do zjedzenia..."+(int)(i+1)+" Misjonarza");

/** jesli pusty zasob to pokruj misjonarz*/

output.append("\nKroimy misjonarza na "+porcje+" porcji");

obraz = new ImageIcon("ikony/kot.jpg");

for( int j=1; j><=porcje; j++ )

misjonarz.put( j );// kroimy na porcje misjonarza i wrzucamy do kotla

misjonarz.KucharzDone();// misjonarz w calosci pokrojony

/** Kucharz przysypia */

if(!misjonarz.PorcjeEmpty)

try

{

Thread.sleep(200);// Usypianie watku kucharza

output.append("\nKucharz wstaje.");

}

catch( InterruptedException e )

{}

}

output.append("\nKONIEC gotowania");

obraz = new ImageIcon("ikony/kucharz1.jpg");

}

}

/** klasa Ludozerca */

class Ludozerca implements Runnable

{

/** zas骲 */

Misjonarz misjonarz;

/** nazwa ludozerca **/

String nazwa;

int ilosc;

/** konstruktor

*@param Misjonarz referencja do zasobu */

public Ludozerca(String nazwa,Misjonarz misjonarz,int n)

{

this.misjonarz = misjonarz;

this.nazwa = nazwa;

this.ilosc = n;

/** uruchom wątek konsumenta */

new Thread( this ).start();

}

/** metoda run wątku Ludozerca

* - Je porcje z misjonarza

* - Sygnalizuje brak porcji*/

public void run()

{

int i=1;

/** najpierw tworzymy ludozercow **/

for(;;)

{

try

{

int time = (int)Math.round(Math.random()*200)+addtime; // kazdy w zmiennym czasie bedzie spozywal posilek

output.append("\nGlodny "+nazwa+" czeka na swoja "+(i++) +" kolejke: "+time+"[ms]");

obraz = new ImageIcon("ikony/kucharz.jpg");

Thread.sleep(time); // uśpij Ludozercow

}

catch( InterruptedException e )

{}

/**zjedz misjonarza**/

misjonarz.doPorcji();// Porcje do kolejki - semafor zastosowany w celu wstrzymania posilku tylko dla jednego Ludozercy by mogl spokojnie zjesc

misjonarz.PorcjeMisjonarza(nazwa);// Zjadanie posilku w zaleznosci od czasu wygenerowanego - kto pierwszy ten lepszy

}

}

}

/** klasa zasobu Misjonarzy */

class Misjonarz

{

LudozercySwing grafika = new LudozercySwing();

Object obj = new Object();

/** na poczatku zakladamy ze misjonarz nie jest pokrojony i brak w kotle*/

boolean KucharzDone = false;

boolean PorcjeEmpty = true;

int porcje;

/** Semafor dla pierwszego ludozercy **/

Semaphore semaforPorcja = new Semaphore(1);

/**Wstawia posilek do kolejki*/

/**Blokowanie posilku dla

* tylko jednego Ludozercy */

public void doPorcji()

{

//Kolejka Ludozercow czekajaca na posilek

try

{

semaforPorcja.acquire();

}

catch(InterruptedException e)

{

}

}

/** Metoda wywolana po pokorojeniu misjonarza przez Kucharza*/

public void KucharzDone()

{

KucharzDone = true;

}

/** umieszczanie liczby porcji z misjonarza w zasobie

*@param number liczba umieszczana w zasobie */

synchronized void put( int porcje )

{

if( !PorcjeEmpty )// zas骲 nie jest pusty - misjonarz nie zjedzony

try

{

output.append( "\nKucharz wklada cos do kotla...");

wait();// czekaj aż zjem

}

catch( InterruptedException e )

{}

// przekazuje stan porcji

this.porcje = porcje;

PorcjeEmpty = false;

notify();

}

/** Ilosc porcji z misjonarza - zjadana

*@return liczba przechowywana w zasobie */

synchronized int PorcjeMisjonarza(String nazwa)

{

if( PorcjeEmpty )// jeśli zas骲 jest pusty

{

if( KucharzDone )// Skonczyl sie posilek powiadamiamy Kucharza

{

//Tu kucharz ktory mial przysypiac budzi sie i widzac pusty kociol doklada do niego

//notify(); - zbedne Kucharz nie czaeka tylko przysypia

}

try

{

//output.append(nazwa+" Ludozerca czeka...na porcje");

wait();// czekaj aż pojawi się liczba w zasobie

}

catch( InterruptedException e )

{}

}

// pobierz liczbę z zasobu

int porcje = this.porcje;

double time = Math.round(Math.random()*50);

output.append(newline+nazwa+" zjedzona porcja:\t"+porcje+" w czasie:"+time+"[sec]");

semaforPorcja.release();

/** zjadlem i wpuszczam nastepnego ludozerce */

PorcjeEmpty = true;

notify();

return porcje;

}

/**Konstruktor bezparametryczny*/

public Misjonarz()

{

}

}

}

public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

class PopupListener extends MouseAdapter {

JPopupMenu popup;

PopupListener(JPopupMenu popupMenu) {

popup = popupMenu;

}

public void mousePressed(MouseEvent e) {

maybeShowPopup(e);

}

public void mouseReleased(MouseEvent e) {

maybeShowPopup(e);

}

private void maybeShowPopup(MouseEvent e) {

if (e.isPopupTrigger()) {

popup.show(e.getComponent(),

e.getX(), e.getY());

}

}

}

}

I don't have any custom paintComponent() method and i didn't use it before, beacuse i thought when i create new ImageIcon using

obraz = new ImageIcon("ikony/kucharz1.jpg");

it will be refreshed and it will look like animation when a new threat start.

Lukasz_1981a at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 5

> Here is whole code

Did you read my reply?

I didn't ask for 200 lines of code. I asked for demo code that showed the problem. Why do I care about the code that creates 20 menu items. it has nothing to do with your problem. Read my repy to find out what an SSCCE is.

Why did you post the code anyway? I already gave you the answer. If it isn't the answer then post your SSCCE.

camickra at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 6

class LudozercySwing implements ActionListener, ItemListener{

JLabel picture;//<move to here

JFrame frame;

//JLabel picture = new JLabel(obraz, JLabel.CENTER);//<--remove JLabel

picture = new JLabel(obraz, JLabel.CENTER);

//obraz = new ImageIcon("ikony/kot.jpg");//<change all of these, to

picture.setIcon(new ImageIcon("ikony/kot.jpg"));

createSpinner(String label){

...

//if (label == "Ilosc porcji")//<change all of these, to

if(label.equals("Ilosc porcji"))

I don't know what its supposed to do, but it now changes the icon adjacent to

the text area (but only once)

Michael_Dunna at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 7
I change it as you written to me but it doesn't work properly, when i start my app. on the right i got image, after setting all parametrs and start threats image on the right is dissapiring. What could be wrong?
Lukasz_1981a at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 8

> What could be wrong?

I have no idea - I don't know what the program is supposed to do.

As suggested earlier, the best thing you can do now is to create a sample program.

just a frame with a button, a label, a couple of images, and the actionperformed code.

just enough to compile and run, and a description of what it is supposed to do,

then we can see for ourselves - unfortunately your 750+ line earlier post is way

too long to read through to find out what is going on

Michael_Dunna at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 9

I thought it will be when i put only obraz = new ImageIcon("ikony/kot.jpg"); and change image to different.

I think I know what mistake you're making, though we'd be spotting it straight away (as, I suspect, would you) if you'd just put an SSCCE together.

"obraz" is a reference. It's a reference held by your object (I assume so anyway, I can't be bothered to read your huge pile of code). If you change that reference, it does not change the reference held by whatever you're using (a JLabel?) to render that icon on the screen.

You need to call "setIcon()" on the label for it to be updated.

But, like I said, you're just loading the same image every time. So I'm not sure what change you're expecting.

itchyscratchya at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 10

I put compiled app. on this link

lupos.republika.pl/canibal.jar

First of all you need to set any value for:

Porcje (missionary parts)

Misjonarze (missionary)

Ludozercy (canibals)

On the left there is a JLabel

with picture (chief) but when i start app (press start button) he dissaper. It should be load different picture with

picture.setIcon(new ImageIcon("ikony/kucharz.jpg"));

First picture is load in class

public Container createContentPane(){

obraz = createImageIcon("ikony/kucharz.jpg");

picture = new JLabel(obraz, JLabel.CENTER);

When the new threat is starting I refresh picture using

picture.setIcon(new ImageIcon("ikony/kucharz.jpg"));

using different images but it doesn't work.

Lukasz_1981a at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 11
when you made your changes to picture.setIcon(..), did you also change this//JLabel picture = new JLabel(obraz, JLabel.CENTER);//<--remove JLabelpicture = new JLabel(obraz, JLabel.CENTER);
Michael_Dunna at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 12

First picture is load in class

public Container createContentPane(){

obraz = createImageIcon("ikony/kucharz.jpg");

picture = new JLabel(obraz, JLabel.CENTER);

When the new threat is starting I refresh picture using

picture.setIcon(new ImageIcon("ikony/kucharz.jpg"));

But you're loading the same image :o)

itchyscratchya at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 13
I removed JLabed and I test it on different picture but they disapper, they aren't displayed, just blank space. Pls check my code on lupos.republika.pl/canibal.jarMessage was edited by: Lukasz_1981
Lukasz_1981a at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 14

they disapper, they aren't displayed, just blank space

Right, so that's a completely different thing to what you originally said, which was "my Image isn't refreshing."

If your labels are being updated with 'empty' images then it seems your app is failing to load the images in question. Maybe they're missing from the jar, maybe you're just not referencing them properly. My advice would be to use getClass().getResource() to obtain a URL to your icon within the classpath. Use a preceding slash in the parameter to navigate to the root of the path, or omit it to specify a path relative to the class's package.

Pls check my code on lupos.republika.pl/canibal.jar

No, because that's a compiled app, not source code, and it won't tell me anything really. Besides which, if you want the bug fixed, do what's been suggested several times and write a small application which just tests the functionality which isn't working. Chances are you'll spot the problem, and if you don't then at least we'll be inclined to take a look at it for you because we'll be able to see the whole code, rather than having to guess what's going on in the rest of your app.

itchyscratchya at 2007-7-14 22:20:09 > top of Java-index,Desktop,Core GUI APIs...
# 15
14 replies and the problem still isn't solved.Thats why I ask for an SSCCE up front.
camickra at 2007-7-21 10:27:20 > top of Java-index,Desktop,Core GUI APIs...
# 16
It does also help to state the problem you're having, rather than a completely different problem that you're not having. Ho hum.
itchyscratchya at 2007-7-21 10:27:20 > top of Java-index,Desktop,Core GUI APIs...
# 17

> It does also help to state the problem you're having, rather than a

> completely different problem that you're not having. Ho hum.

Thats a given. Which is another reason why code is important. People can't always express the problem with words, especially if english is their second language. Having a verbal description along with the code helps reduce the confusion.

I know you understand that, I just which the people who post the questions would understand it.

camickra at 2007-7-21 10:27:20 > top of Java-index,Desktop,Core GUI APIs...
# 18
Agreed - I'm just rubbing it in for the OP :o)
itchyscratchya at 2007-7-21 10:27:20 > top of Java-index,Desktop,Core GUI APIs...
# 19
Thx everybody for help. I found my problem, as sb. wrote the reference wasn't changed.obraz = createImageIcon("ikony/kucharz1.jpg");picture.setIcon(obraz);
Lukasz_1981a at 2007-7-21 10:27:20 > top of Java-index,Desktop,Core GUI APIs...