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++;
}
}
3
  • 1) For better help sooner, post an MCVE (Minimal Complete Verifiable Example) or SSCCE (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. Commented Apr 8, 2015 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. Commented Apr 8, 2015 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 ? Commented Apr 8, 2015 at 16:39

2 Answers 2

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

        }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I did it, but now timer works only for presentTime. Also I used two Timer(for presentDay and presentTime), but they work separately.
I'm sorry, I don't understand can you clarify?
I edit post, hope it will help you to understand me. In my last code presentTime is incremented with pausing. And it is right. presentDay is not incremented because of if statement. But if I replace if on while then presentDay immediately takes the value of numberOfDays.
great! Click my answer as the solution?
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 );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.