Progress Bar Java exit - java

i am doing a quiz in java and i figured out everything except i want to put in a progressbar.I want to exit my actual frame(or to show something) when the progress bar is filled(i used it as a timer), how can i do it? I don't know how to do something when the bar is filled. The code i have so far, it's a progress bar that fills for 30 secs or something very close to that.
al=new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(jProgressBar1.getValue()<100){
jProgressBar1.setValue(jProgressBar1.getValue()+5);
}
else{t.stop();}
}
};
t=new Timer(1500,al);

Simple, put more code into this else{t.stop();} block. Here is where you would exit whatever it is you wish to exit.
else {
t.stop();
// exit whatever window you wish to exit
}
Note that this is as about as detailed as we can go since you've not given more information about your current code.
Obligatory link: The Use of Multiple JFrames, Good/Bad Practice?

Related

Not able to delay between displaying icons

When the actionPerformed method is invoked I would like it to display the desired icon on the first button, delay for 1 second and then display the icon on the second button. The icons always display simultaneously? Not sure how to correct this.
#Override public void actionPerformed(ActionEvent e)
{
btnTest1.setIcon(img2);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
btnTest2.setIcon(img2);
}
I'm assuming this is for JavaFX / Java Swing. I'm not too familiar with it, but I believe the threads aren't working is because there are concurrency rules related to using threads in swing apps. I've had similar issues and wrote a question about how to delay something using threads. I found sources for using a timer object. It might be better to implement the timer by doing:
import javax.swing.Timer;
I'm sure other more advanced users may give more detail. This is maybe another option. Oracle might help too:
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
The buttons' icons are set with setIcon, but that doesn't mean they are painted immediately. Both icons will only be painted after you return from your actionPerformed method. What you need to do is set the icon for the first button, then use Timer (see zOrigin_'s answer) and after the timer elapses, set the second button's icon.

Value of JLabel is not being updated using setText() in Java

I know many people have asked this question before but I couldn't find any answer that solved my problem. My code is like this:
public void mouseClicked(MouseEvent arg0) {
TEXT.setText("ON");
myfunction(); //runs for a very long time
}
The original text of JLabel is "OFF". Now I want to change the text to "ON" when the mouse is clicked but the text doesn't set until myfunction() is complete (which may take several minutes).
I have tried the invalidate function, making a separate function for setting the text but nothing is working.
Please help me with this problem!
The problem is that mouseClicked(...) is executed on the UI Thread. That is the Thread that is responsible for handling all sorts of user actions (like a mouse click) and also the drawing of components (like updating the text of the label on screen). If you execute your long running method call on the UI thread, it will be blocked and can't draw anything until execution is complete. You'll have to use multi threading to get around this problem.
The following might not be the most elegant solution, but if you are new to multi threading it will get the job done:
public void mouseClicked(MouseEvent arg0) {
TEXT.setText("ON");
(new Thread() {
public void run() {
myfunction();
}
}).start();
}
It will spawn a new Thread that handles your method, which will let the UI Thread continue doing its thing. consider deactivating the button that has just been clicked, so the user can't start the execution while it is already in progress (which usually is what you want..)

How to see if a button has been pressed from another class

I have a dilema. This might sound stupid but i have no idea how to do this.
I have a password class and a main screen. My main screen has a button that when pressed pops up the password class. Here is the call to the passwordClass from an actionlistener on my main class.
public PasswordClass login(){
pressMe.setVisible(true);
String player="?";
final String playerT = player;
boolean nameCorrect = false;
final PasswordClass hold = new PasswordClass(null);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
PasswordClass.createAndShowGUI();
}
});
return hold;
}
the return statement isn't anything related to this I never used it but I had it their for testing purposes. In my password class i have a boolean that tells me if the user input matches the correct login info. i call it worked i run the password class and i had the problem that while the window is popping up my code to check if it worked is running simultaneously. This is a problem because i only want to check if it worked after the user has pressed ok. Here is the code
public void actionPerformed(ActionEvent ae)
{
else if(ae.getActionCommand().equals("Login")){
login();
}
else if(ae.getActionCommand().equals("Press Me To Continue")){
if(PasswordClass.worked){
//worked is a static variable from the PasswordClass class
}
pressMe.setVisible(false);
}
}
So whenever OK is pressed on The PasswordClass JFrame a little button pops up and asks a SECOND time for it to save. I want it to save from the first OK button. The reason i make another button is because i don't know how to stop and wait for the OK button to be pressed. My if loop to check if it worked already returns false automatically before the user presses OK. That is my problem and I am really confused on how to solve it.
Any help? If any more code is needed I will provide it but i think this is enough.
The reason i make another button is because i don't know how to stop and wait for the OK button to be pressed
Use a modal dialog of some kind, see How to Make Dialogs for more details
Conceptually, you want to display a modal dialog, which prompts the user for some information, while blocking at the point in your code that the dialog was made visible. When the dialog is dismissed (for what ever reason), you'll want to check the results from the dialog and take appropriate actions based on what the user did
There needs to be some form of synchronization between the objects (not necessarily related to the statement of that name).
If the code that wants to check the result wants to block until the result is set, you could use a CountDownLatch: the actionPerformed method calls CountDownLatch.countDown() while the other code calls CountDownLatch.await().
On the other hand, if the code checking the result does not want to block, then a simple two-boolean approach would work well. Have one boolean indicate whether the button press complete and the other to tell whether OK was the button pressed.

actionPerformed(ActionEvent e) {

I am building a grpahic interface with different buttons,
and when user clicks a button I use :
actionPerformed(ActionEvent e) {
Object source = e.getSource();
if
else if
else if
...
}
The problem is that when the user clicks a button, actionPerformed(ActionEvent e) is called, and it enter in the if corresponding to e.getSource();.
And it executes all instructions in the corresponding if. But I want to make possible that the user clicks different buttons, so that a actionPerformed(ActionEvent e) { is called, even if the instructions of the previous actionPerformed(ActionEvent e) { is not finish yet.
I don't know if you understand, but thank you if you can help me !
You will need to use background threads if you want the GUI to be responsive while a long-running process is occurring. A SwingWorker works well for this in Swing GUI's. Please check out Concurrency in Swing for all the gory details on this.
Examples:
mvc-progress-bar-threading
why-does-swingworker-stop-unexpectedly
Google Search
You need to use SwingWorker . It does the work in background without freezing the UI.
Here is the question you can have a look for how to use them.
Or you can use official oracle documentation for SwingWorker.

How to have program wait for a button press in Java

Now, I'm not sure if this is possible or even the best way to accomplish what I'm trying to do, but basically I'm creating a very simple simulation program with a very simple Swing GUI.
After each round of the simulation, some buttons on the interface are enabled for the user to make changes and then the user can press the "continue" button to start the simulation again. The simulation itself is basically a while loop that needs to wait for the user action before continuing. My question is how can I have the program stop and wait until the user presses the "continue" button? Please let me know if there are any more details I can provide if this is unclear!
Edit:
I'm going to add some simplified code here so maybe this will make more sense. The program is in two parts, the simulation class and the view. So the button to be pressed is in the view class while the simulation is happening in its class.
Simulation class:
SimulationView view = new SimulationView(); // extends JFrame
while (!some_condition) {
// code
// need user action via button press here before continuing!
}
Most likely the best way to go is enclose one round of the simulation in a method, that would then be executed from the action listener attached to the button you want.
After edit:
Somebody needs to control the simulation in the first place, so you could do the following:
SimluationClass
{
public int startSim()
{
...
}
}
class SimulationView
{
SimulationClass sim = new SimulationClass();
private void init()
{
JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
void actionPerformed(...)
{
sim.startSim()
}
});
}
}
Keep in mind though that this will freeze your gui as the sim method will be executed from the event thread.

Categories