1

This is my first Swing application so I used NetBeans GUI Builder. There is a Start button to start simulation(two loops: the outer by days and the inner by hours). At each iteration the loop should pause. When you click on the Stop button simulation should stop. I tried to ways: 1)

private void StartActionPerformed(java.awt.event.ActionEvent evt) {                                      
    Timer timer = new Timer(5000, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            while(presentDay <= numberOfDays){
                jTextField2.setText(Integer.toString(presentDay));
                for(; presentTime <= 18; presentTime++){
                    jTextField6.setText(Integer.toString(presentTime));

                    StringBuilder res = new StringBuilder();

                    for(Event ev: schedule[presentDay-1].day){
                        if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
                            res.append(ev);
                            ev.setStatus(1);
                        }
                    }
                    currentEvent.setText(res.toString());
                    // Pause should here
                }
                presentTime = 9;
                presentDay++;
            }
        }
    });
    timer.start();
}

2) Add Timer in main class constructor

public PlanningSystem() {
    initComponents();
    ...
    timer = new Timer(5000, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            while(presentDay <= numberOfDays){
                jTextField2.setText(Integer.toString(presentDay));
                for(; presentTime <= 18; presentTime++){
                    jTextField6.setText(Integer.toString(presentTime));

                    StringBuilder res = new StringBuilder();

                    for(Event ev: schedule[presentDay-1].day){
                        if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
                            res.append(ev);
                            ev.setStatus(1);
                        }
                    }
                    currentEvent.setText(res.toString());
                    // Pause here
                }
                presentTime = 9;
                presentDay++;
            }
        }
    });
}
private void StartActionPerformed(java.awt.event.ActionEvent evt) {                                      

    timer.start();
}

But both ways did not work. I hope you help solve this problem. And sorry for my English :)

====================================================================== After editing :

private void StartActionPerformed(java.awt.event.ActionEvent evt) {                                      
if(presentDay <= numberOfDays){
    jTextField2.setText(Integer.toString(presentDay));
    Timer tim = new Timer (5000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
        if(presentTime <= 18){
            jTextField6.setText(Integer.toString(presentTime));
            StringBuilder res = new StringBuilder();
            for(Event ev: schedule[presentDay-1].day){
                if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
                    res.append(ev);
                    ev.setStatus(1);
                }
            }
            currentEvent.setText(res.toString());
            presentTime++;
        }
        }
    });            
    tim.start();
    presentTime = 9;
    presentDay++;
}
}
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. – Andrew Thompson Apr 08 '15 at 14:53
  • As far as I can tell, you simply need to replace, first two loops with `if` blocks, like `if ( presentDay <= numberOfDays ) { if ( presentTime <= 18 ( ) { DO WHAT YOU DOING, HERE } }`. This should work. Since you be calling this action after a specified time, as described while initializing the `Timer` object reference. – nIcE cOw Apr 08 '15 at 15:05
  • @nIcEcOw I replace loops with if blocks, but now timer works only for if(presentDay <= numberOfDays) branch. Not for presentTime. Maybe I should use two Timer ? – Alexandr Shevelev Apr 08 '15 at 16:39

2 Answers2

1

Your while loop is the problem. You are incrementing presentDay to numberOfDays the first time your timer is called. After that, nothing is ever going to change again.

I believe (though because of the partial code you posted, I can't be sure) that if you take out the while loop, it will work as you desire

Edit: (Better understanding of what you're doing)

Using two timers is wrong. Just use one timer, and update both your presentDay and presentTime there.

Timer tim = new Timer (5000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
           presentTime++;
           if (presentTime == 24) {
             presentTime = 0;
             presentDay++;
           }
           //times how now been set
           //update your GUI here

        }
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

See if this helps, though, in order to mimic the use of two loops, I used a BubbleSort algorithm. Though as already stated, removal of single while loop will do that thingy. Since in this case it is working as expected, though how will it work, in case of a long list is doubtful. Else you can look at SwingWorker.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TimerExample {

    private JLabel [] labels;
    private static final int TOTAL_VALUES = 5;
    private static final int GAP = 5;
    private JButton startButton;
    private JButton stopButton;
    private Timer timer;

    private int [] values = {
        5, 10, 20, 2, 8
    };
    private int pass;
    private int i;

    private ActionListener timerActions = new ActionListener () {
        @Override
        public void actionPerformed ( ActionEvent ae ) {
            if ( pass <= TOTAL_VALUES - 1 ) {
                System.out.println ( "Pass: " + pass );
                for ( int i = 0; i <= TOTAL_VALUES - 1 - pass; ++i ) {
                    System.out.println ( "i: " + i );
                    try {
                        int left = Integer.parseInt ( labels [ i ].getText () );
                        int right = Integer.parseInt ( labels [ i + 1 ].getText () );
                        System.out.println ( "[ " + i + " ] " + left + " [ " + ( i + 1 ) + " ] " + right );
                        if ( left > right ) {
                            String value = labels [ i ].getText ();
                            labels [ i ].setText ( labels [ i + 1 ].getText () );
                            labels [ i + 1 ].setText ( value );
                        }
                    } catch ( Exception ex ) {
                        ex.printStackTrace ();
                    }
                }
                ++pass;
            }
        }
    };

    public TimerExample () {
        pass = 1;
        i = 0;
    }


    private void displayGUI () {
        JFrame frame = new JFrame ( "" );
        frame.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );

        JPanel contentPane = new JPanel ();
        contentPane.setLayout ( new BorderLayout ( GAP, GAP ) );

        JPanel topPanel = new JPanel ();
        createLabels ( topPanel );
        contentPane.add ( topPanel, BorderLayout.CENTER );

        JPanel bottomPanel = new JPanel ();
        startButton = new JButton ( "Start" );
        startButton.addActionListener ( new ActionListener () {
            @Override
            public void actionPerformed ( ActionEvent ae ) {
                if ( !timer.isRunning () ) {
                    timer.start ();
                }
            }
        } );
        stopButton = new JButton ( "Stop" );
        stopButton.addActionListener ( new ActionListener () {
            @Override
            public void actionPerformed ( ActionEvent ae ) {
                if ( timer.isRunning () ) {
                    timer.stop ();
                }
            }
        } );
        bottomPanel.add ( startButton );
        bottomPanel.add ( stopButton );
        contentPane.add ( bottomPanel, BorderLayout.PAGE_END );

        frame.setContentPane ( contentPane );
        frame.pack ();
        frame.setLocationByPlatform ( true );
        frame.setVisible ( true );

        timer = new Timer ( 1000, timerActions );
    }

    private void createLabels ( JPanel contentPane ) {
        labels = new JLabel [ TOTAL_VALUES ];
        for ( int i = 0; i < TOTAL_VALUES; ++i ) {
            labels [ i ] = new JLabel ( "" + values [ i ], JLabel.CENTER );
            contentPane.add ( labels [ i ] );
        }
    }

    public static void main ( String [] args ) {
        Runnable runnable = new Runnable () {
            @Override
            public void run () {
                new TimerExample ().displayGUI ();
            }
        };
        EventQueue.invokeLater ( runnable );
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143