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ł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ł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ątek Kucharz
new Thread( this ).start();
}
/** metoda run wą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.