Good day to everyone.
I need help. Have to make more of these and need someone to show me how.
My code doesn't work the way it should.
It would have to
- wait for you to click jbutton and then:
- disable jbutton
- roll die, then start timer loop to move jlabel, then stop timer and chek if die number was six, then
- roll die again, start timer loop to move jlabel, stop timer, check if it was 6,
- if not then
- re-enable the jbutton, waiting for next click.
(Originally there was FOR loop instead of timer loop.)
I tried several things to change in the code, nothing works.
Button is either permanently disabled or not at all.
If 6 is rolled second timer starts over the first one without waiting to finish, messing with jlabel moving,
if you click jbutton during that, third is overlapping them and make jlabel moves even messier
I would be grateful if someone could paste the code in their IDE, see the problem, and show me what to change.
Thanks in advance.
Here's the code:
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.Math.random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.Timer;
public class RunPhysics extends JFrame {
private final int waits = 200;
private JLabel blackBoard = new JLabel();
private JLabel label = new JLabel("F=m*a -> O");
private JButton roll = new JButton("Roll");
private int labelX = 10;
private int labelY = 60;
private int die;
private Timer timer;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable () {
@Override
public void run() {
new RunPhysics();
}
});
}
public RunPhysics() {
setSize(1000, 200);
setTitle("Running Physics");
setLayout(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
getContentPane().add(blackBoard);
blackBoard.setBounds(10, 10, 980, 280);
blackBoard.add(label);
blackBoard.add(roll);
label.setBounds(30, 50, 100, 20);
roll.setBounds(10, 10, 60, 30);
roll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent roller) {
do {labelX = 10;
die = (int)(random()*6+1);
roll.setEnabled(false);
System.out.println(die + " was rolled.");
timer = new Timer( waits, new ActionListener() {
@Override
public void actionPerformed(ActionEvent mover) {
Toolkit.getDefaultToolkit().beep();
label.setLocation(labelX, labelY);
if (labelX >= 900) {((Timer)mover.getSource()).stop();}
else { labelX+=36; }
}
});
timer.start();
roll.setEnabled(true);
} while (die == 6); // “Dice” is the plural form of the singular noun “Die”.
roll.setEnabled(true);
System.out.println("~~~~~~~~~~~~~~~~~~~~");
}
});
}
}