Custom JDialog, waiting for Button Press

I want to create a custom dialog so i can do the following:
Color yrColor = MyColorChooser().showDialog();
I can create the dialog just fine but i cant get it to return a value
on a button press.
Here is my code:
public class MyColorChooser extends JDialog implements ActionListener{
public MyColorChooser(){
super(Main.Frame, "Color Chooser", true);
// Gui Stuff
public Color showDialog(){
setVisible(true);
// ?? how do i have it wait for button press??
return YourColor;
public void actionPerformed(ActionEvent e) {
if( e.getSource() == Button ){
returnColor()
public void returnColor(){
Color YourColor;
JButton Button = new JButton();
}Im clueless when it comes to JDialogs.
I know i am probably approaching this all wrong.
I need guidance more in the approach rather than the code.
If anyone has any suggestions id appreciate it.
Thank you!

Maybe this simple example can give you some ideas. Note how I make the dialog modal. This will halt the program flow until the dialog is dismissed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleTextInputDialog extends JDialog implements ActionListener {
    private JTextField  inputField;
    private JButton     okButton;
    private JButton     cancelButton;
    private String      value;
    private SimpleTextInputDialog() {
        setTitle("Enter a value");
        setModal(true);
        inputField = new JTextField(20);
        JPanel textPanel = new JPanel();
        textPanel.add(inputField);
        getContentPane().add(textPanel, BorderLayout.CENTER);
        okButton = new JButton("OK");
        okButton.addActionListener(this);
        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(this);
        JPanel buttonPanel = new JPanel(
                new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(null);
    public void actionPerformed(ActionEvent e) {
        if( e.getSource() == okButton ) {
            value = inputField.getText();
        dispose();
    public static String getValue() {
        SimpleTextInputDialog dlg = new SimpleTextInputDialog();
        dlg.setVisible(true);
        return dlg.value;
    public static void main(String[] args) {
        String value = SimpleTextInputDialog.getValue();
        System.out.println("Entered value: " + value);
}And as always, you should study the tutorials:
"How to Make Dialogs":
http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html

Similar Messages

  • Wait for button press......

    I have a JButton with an action listener. What I want to happen is when
    the button is pressed and goes into the action performed part it should
    wait for the same button to be pressed again before it does anything.
    The problem is once it goes into the action performed part of the action
    listener the button cannot be pressed again until it leaves...
    Any ideas how this could be done?
    Thanks

    public void actionPerformed(ActionEvent e){
       Object o = e.getSource();
       //the button was pressed once
       if (o == button){
          if(  //count the number of times the button was pressed and then divide it by 2
              /*and if the remainder will be one*/){
             //do this;
          else{
             //this is what you do if there is no remainder meaning the number is divisible by 2
    }You should also try using mouse events.
    You can count the mouse clicks with it.
    Hope this helps you.

  • Custom FPM Event for Button row element

    Hi Expects,
    I have created a new button row element in standard screen, where I want to add custom FPM event and handle the same in get_data( ). But by default SAP is providing few event ID's in drop down.
    Please help me how to add custom FPM event for  button row element.
    Regards,
    Reny Richard

    Hi Remy,
    Process Event method does have any signature parameters in it which allow us to disable/enable buttons.
    We can handle this in Get data method.Get Data is always triggered after Process Event. So you can write that in Get Data instead.
    ****this is a sample code to do the same. You can do a read as well if single button needs tobe handled***
    LOOP AT CT_ACTION_USAGE INTO lw_action WHERE id = (your event id for the button).
        lw_action-enabled = abap_false.
        MODIFY CT_ACTION_USAGE FROM lw_action TRANSPORTING enabled.
        EV_ACTION_USAGE_CHANGED = 'X'.
    ENDLOOP.
    ***use field symbol to avoid modify if you want***

  • Switching Frames (cardsLayout), doing something, waiting for button

    Hi,
    I am switching JFrames in my application and each frame is to call a specific function and then wait for a button click.
    so the code would be:
    function(){
            cardsLayout.show();
            doSomeCalculations();
            waitForButtonClick
            continueWithSomething //depending on which Button was clicked
    }My problem is, how to realize the waitForButtonClick?
    What would you suggest? I have heard about synchronize. Is this the way to go, or is there an easier/better way?
    Besides a while(notClicked) way ;-)
    Thanks!

    pir wrote:
    it is not that I do not want to learn Java. Please understand that Java is not with what I am earning my living, it is a tool for me, to make some task easier, which I would have otherwise have to do step by step by hand. I will never be as good as someone who spends his time with Java every day. I also have only a specific task to perform in a given time, so I need only specific information - which I am definitely willing to learn - and not all there is about Java and Swing.You must understand that at its core, your question is not about anything specific but rather it boils down to: "how to create an event driven program in Swing".
    The only reasonable answer to this is to send you to the Swing tutorials where, if you have the interest, ability, and inclination, you can learn the tools needed to do Swing and event programming. If you choose not to do this, no one in this forum can help you. Period.
    I hope this clarifies the situation enough, to allow someone to have a heart and point me in the right specific direction, even knowing that I might use this knowledge only once.And once again, I recommend that you hit the Sun Swing tutorials and start learning. Accept this and follow this recommendation and you will find success. If not, well,... it's your choice.
    Thank you in advance for any specific help.This is as specific as it's going to get at this stage. Much luck.

  • Sony Australia -Very Dissapointing customer service** Waiting for months no resolution

    Good Morning I purchased a new sony bravia 65900b tv in November last year and have not been happy ever since. I have had this tv replaced 3 times and panel replaced once most recently with the repairer even commenting on how poor the screeen was and commenting on all the banding. As a result at the time sony comitted to replacing this with the new version on this unit when available. Now they have reneged after i have been waiting for release for MONTHS and are offering a tv that does NOT have local dimming at all and no premium speakers but offered to throw in a 200 sound bar. As the tv in question 900c is only in US at the moment they are saying they cannot use the spec on the US site as a guide as the Australian version may have local dimming  I KNOW it wont ...and what about my BLOODY SPEAKERS???...What a joke i purchased this "Premiuim TV" top end model in Australia retail stores as 950 not avaiable at JB HIFI and this is how sony standby their customers and products (Lesson learnt) NEVER AGAIN The Australian (Philippine's?) call centre is a joke , always promise to call back NEVER happens i always call back and i  have speant over 2 hours on the phone with them this week to be told to bad . My case NUMBER is 3191814 SOMEONE PLEASE HELP !!!!!!!!!!!!!!!!!!!!!!!!!!!

    Hi Jpw123, 
    Welcome to the Sony Community!
    We certainly empathize with your frustration and disappointment. We always appreciate customers who take the time to give us their feedback. You can check the specifications of the XBR-65X900C which is a US model for your reference. However, the specifications, features, and functionalities are subject to change change.
    Please click here
    For further assistance regarding your concern, please contact the Sony offices/Sony representative offices nearest to your place of residence in Asia Pacific region http://www.sony-asia.com/countryselector.html?hpid=countryselector:AsiaPacific. Due to proximity, they are in a better position to respond to your questions or concerns.
    If my post answers your question, please mark it as "Accept as Solution"

  • Waiting for button click

    Hi,
    I'm trying to create a program in which the program does nothing until one of the buttons is pressed, then acts accordingly. The way the program works, though, it can't just be by using the ActionPerformed method.
    Currently, I have a while() loop that cycles through until one of the buttons is pressed, which kicks it out of the loop and allows that button to be processed. The problem, however, is that when the program is run, the while() loop takes control over the program and doesn't allow any buttons to be clicked, therefore rendering the loop infinite.
    Basically what I need is a way for the while() loop to still be running, but at the same time for the buttons to be rendered able to be clicked so that the loop can end.
    Is this possible?
    Thanks in advance.

    You might want to post your code so we can see what's going on. I post my code here a lot. Just remember to post only the relevant parts, but if you feel that it's necessary to post the whole program, always put something like "Warning: long post" in the subject header.
    You might want to put your buttons in an array, and for each button, attach an ActionListener to it. Then have an inner ButtonHandler class. Here's how I would do it:
    for (i=0; i<buttonArray.length; i++)
      buttonArray.addActionListener(handler);
    Then at the end of your code, that is between the end of main and the last closing curly brace, try this:
    private class ButtonHandler implements ActionListener
      public void actionPerformed(ActionEvent e)
        buttonPressed = e.getActionCommand();
    I hope this sheds some light.  I don't know exactly what your code looks like, but hopefully, I'm making a good shot in the dark.  I don't see any need in using a while loop.  Just give this a shot, and if you still have problems, feel free to post your code and let us look at it.  Hope this helps! :-)
    Syster Tara

  • Wait for user input in middle of method

    I have a method in the middle of which I want to give the user a chance to click one of several Buttons. Here is the basic design of the method:
    Private Sub MyMethod()
    'Code before I need extra input
    'This is where I want to wait for the user to click a Button
    'This is where I will be using the results from the clicked Button
    'The waiting for input and using the results will happen multiple times inside a loop
    End Sub
    The code is in a loop, so exiting the method and putting the rest of the code in the Button handler would not be appropriate. How can I ask the user for input and then return that input to the method where I left? I seem to be tempted to use some kind of async
    method, but since the input will be coming from the user (not another method), that doesn't seem like it would be right (but I don't have a huge amount of experience with async, so I could be wrong about that). Can anybody help me? Thanks.
    Nathan Sokalski [email protected] http://www.nathansokalski.com/

    Hi Nathan,
    You're on the right track: you'll need to await an Async function to put a delay in the middle of your method. The button click will notify the async function to finish.
    You could write a custom function which returns a Task and waits for the notification from the button:
    Task WaitForButtonClickAsync()
    // wait for button click
    and then await that in your main function:
    async void BigNastyFunction()
    await WaitForButtonClickAsync();
    The next question is how to let the button click notify WaitForButtonClickAsync to return.
    We could spin up a worker thread and have it block waiting on a notification, but there is no need to complicate things like that: WaitForButtonClickAsync can just return
    Task.Delay(timeout, cancellation token) and then when the button click handler fires it can cancel the delay.
    See
    Asynchronous Programming with Async and Await and
    Async Cancellation: Bridging between the .NET Framework and the Windows Runtime for more information on cancelling a task.

  • Always need Disconnect power, press the power button wait for 10 seconds...

    I bought a HP computer for a couple of years ( Pavilion a6695it  ) It always works well. But in recent days, I can not start up it. I tried pressed power button on the front of the computer, nothing happend. Then I searched in hp site. finnally, I find this article http://h10025.www1.hp.com/ewfrf/wc/document?docname=c00241069&tmp_task=solveCategory&cc=it&dlc=it&lc...
    In english version the article is here: 
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=bph06788&cc=us&destPage=document&lc=en&product=3...
    Power supply light is on or flashes
    Perform the following steps, in order, until power is restored or it is determined that there is a hardware failure:
    CAUTION:This product contains components that are easily damaged by ElectroStatic Discharge (ESD). To reduce the chance of ESD damage, work over a non-carpeted floor, use a static dissipative work surface (like a conductive foam pad), and wear an ESD wrist strap that is connected to a grounded surface, like the metal frame of a PC.
    Disconnect everything from the computer, including the power cord.
    With the power cord disconnected , press the power button on the front of the computer and wait for ten seconds.
    This is work for me. But now, my computer always need this methond that it can be started up.
    Disconnect power -> press the power button and wait for ten seconds -> then the system will  start up
    So my question: where is the problem? Which part is broken and i should replace? Thanks.
    regards,
    Youli
    This question was solved.
    View Solution.

    Hello youlichika,
    Welcome to the HP Forums, I hope you enjoy your experience! To help you get the most out of the HP Forums I would like to direct your attention to the HP Forums Guide First Time Here? Learn How to Post and More.
    I understand that you are not able to power on your desktop, and I would be happy to assist you in this endeavor! 
    In following the document for Troubleshooting Power Supply Issues, were you able to follow steps 3-9? If so, what were the results?
    If you have come to the end of the document, and you still have to drain the power from the computer to power it on, you can find a replacement part (5188-2627) through one of the sites available by following this link.
    I hope this helps!
    Best Regards   
    MechPilot
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the right to say “Thanks” for helping!

  • Wait For A Button Press

    Hey, I am currently creating a game and need to know how to wait for a certain button to be pressed. A popup message comes up that tells the user to press a button, then I need to wait for the button to be pressed. Then once the button is pressed, I want another message to come up. The problem is, I have no idea how to wait for a button press after the first message comes up. Instead it just displays the first message, then the second directly after.
    Thanks

    So you have a button that is always present. Normally clicking the button does nothing. But sometimes a message shows up, in which case if the user clicks the button, something happens. Right?
    UI principles aside (it's bad form to display a button that does nothing), this is pretty simple.
    Create a field to track whether the button does anything. For example:
    private boolean buttonActive = false;In your action listener for that button, first check the value:
    public void actionPerformed(ActionEvent e) {
        if (buttonActive) {
            // do your thing
    }If the buttonActive is true, it does something, otherwise it does nothing.
    After you display the message, set buttonActive to true. When you want the button to become a brick again, set it to false.

  • How to do custom dialog so it displays the dialog and waits for user to end

    I have an application that I want to create my own dialog screens. For example, the user cliks on one frame, and I want to open a window for the user to enter data, after the user finishes, he presses OK and then the main app continues.
    On the class that I open the dialog, I open it with:
    NewOkCancelDialog.abrePopup();
    System.out.println("Program should wait for the dialog to close");And the 'NewOkCancelDialog' class is defined like:
    public class NewOkCancelDialog extends javax.swing.JDialog {
    The constructor is like:
    public NewOkCancelDialog(java.awt.Frame parent, boolean modal) {
    super(parent, true);
    initComponents();
    this.setLocation(400,400);
    This methods are when the user activates the button and the popup closes..
    private void cierraPopupOk(){
    resultados.setciudad1(this.fld_ciudad1.getText());
    if (resultados.getciudad1length() < 3) {
    System.out.println("Error en la entrada!");
    } else {
    doClose(RET_OK);
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    cierraPopupOk();
    private void doClose(int retStatus) {
    returnStatus = retStatus;
    this.estaAbierto = false;
    setVisible(false);
    dispose();
    I would like to have the application in the first lines, after calling
    NewOkCancelDialog.abrePopup();
    to wait until the method doClose() in NewOkCancelDialog class is finnished. But right now, after the ...abrePopup() is called, it continues.
    What am I doing wrong? or what am I not doing?

    Use the "code" tags not the "bold" tags when posting code.
    But right now, after the ...abrePopup() is called, it continues.Well your posted code doesn't show this method so we don't know what you are doing in this method.
    Why are you using a static method to show the dialog? Normally the code would be:
    JDialog dialog = new CustomDialog();
    dialog.setVisible( true );
    But you are correct with the basic idea in that you need to use a modal dialog.

  • [Solved] Keep the last button pressed with a custom style

    Hello,
    I have a VBox with 20 buttons and I have this style applied (menu.css) (only for VBox wrapper):
    .button:focused {
        -fx-background-color: #0768A9;
        -fx-text-fill: #FFFFFF;
    But when I pressed other button outside the VBox the style disappears, because the other button get the focus.
    I'm afraid I'm taking the wrong way.
    How I can do to keep the last button pressed with a custom style? (Only for buttons containing the VBox).
    Best regards

    I created a simple method to change background colors in buttons:
        private void setSelectedBtnStyle(Button bboat) {
      // Change style oldSelectedBoat
        selectedBoat.setStyle("-fx-background-color: white;-fx-text-fill: black;");
        // oldSelectedBoat var change to newSelectedBoat
        this.selectedBoat = bboat;
      // Change style newSelectedBoat
        selectedBoat.setStyle("-fx-background-color: #0768A9;-fx-text-fill: #FFFFFF;");;
    Surely not the best solution, but it works for me.
    Best regards.

  • Make jFrame wait for jDialog to finish

    I am making a project in Netbeans i have a main Frame and some Dialog windows that open up if you press some buttons.
    when one window opens i want the main Frame script to pause and wait for it to complete.
    i have tried 3 different ways:
    questionDialog.setVisible(true);
    while (questionDialog.isVisible()) {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
    } but that shows the frame of the dialog box but never loads the inside and the whole application freezes.
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            questionDialog.setVisible(true);
    while (questionDialog.isVisible()) {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
    }that loaded my Dialog box but the script never waits for it to close i assume it is because it waits until "later" to show the dialog box and in that time it skips the while loop.
    Thread t = new Thread(new Runnable() {
        public void run() {
            questionDialog.setVisible(true);
            while (questionDialog.isVisible()) {
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
    t.start();
    System.out.println("Dialog started");
    System.out.println(questionDialog.isVisible());
    try {
        t.join();
    } catch (Exception e) {
    }but that had the same result as the first code it waited but never showed the dialog.
    where am i going wrong how should i go about this?
    Scott.
    EDIT:
    by finish i mean become not Visible. so isVisible() will return false
    Edited by: ratcateme on Nov 20, 2008 3:02 PM

    You don't have to do anything to do that
    questionDialog.setVisible(true), this method will block the thread, it would't keep going until the questionDialog is unvisible, this is the mistake of the way 1 and way 3.
    and the way 2: the while block will be execute before the questionDialog.setVisible(true) is execute, so questionDialog.isVisible() will return false
    my en is very poor, good luck!

  • Is there any way to wait for a value without using JDialog or JOptionPane?

    I am implementing a dictionary program by detecting word in a JTextPane and asking a user to choose one of available meanings from JOptionPane or JDialog. The program runs under a while-loop until all dictionary words are detected or a user clicks cancel.
    However, I don't want to use JDialog or JOptionPane because it is sometimes annoying to have a popup window on every detected dictionary word.
    So, I use JList with Buttons on the same Frame as the JTextPane. However, now, the program does not stop when it detects a dictionary word. It just uses a default value of the JList for translating word to meaning.
    Is there any way I can simulate the JDialog or JOptionPane without using it?
    I mean I'd like to stopp the program temporary, wait for an answer from other components, and then continue to detect the next dictionary word.
    Thank you.

    I'm probably reading this all wrong, but instead of the while loop,
    the method just looked for a dictionary word from a particular caretPosition,
    so, to start, it would be findWord(0)
    when found, add whatever to wherever, note the caretPostion at the end of the 'found' word, and method returns.
    when the user selects whatever button, the button's actionListener also calls the method again, using the noted caretPosition
    findWord(42);
    so, it starts searching from 42 (instead of the start)
    basically it is event driven
    findWord sets the button/s
    click a button starts findWord

  • Wait for user to select the OK button

    For my application I cannot use a simple MessagePopup where the user must select the OK button to continue.
    I created a new panel with just a text message and an OK button to act like a MessagePopup.
    When I call InstallPopup and the Panel box pops up I want to wait until the user selects OK before continuing just like the MessagePopup.
    How can I accomplish this?
    Thanks!
    John W.
    Solved!
    Go to Solution.

    You can use GetUserEvent () function. In the scenario you have depicted you must have all controls in the popup panel set as "Normal" and only the OK button set as "Hot" (The default control mode). The callback the must handle the panel can be structured like this:
    int pnl, ctl, handle;
    // some code here
    // Code to handle the popup
    handle = LoadPanel (.....)
    InstallPopup (handle);
    GetUserEvent (1, &pnl, &ctl); // Wait for the user to press OK button
    DiscardPanel (handle);
    // The rest of the code here
    This help topic gives you additional informations on this subject.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • It is so nice spending 2 hours on a phone to be hung up upon waiting for a supervisor. After being told the day before I would get a call when the customer service representiave started her shift at 7pm to give me more answers. I do not like to be stuck w

    What a frustrating experience I have had trying to get away from This phone and Plan. I just want to down grade this phone. What difference does it make to you here? All VZW will do is re certify the phone and give it to someone else. I just would like to down grade to a cheaper phone and do away with android os. I still have the same issues with the phone as I did with my other one within a hour of re activating it. I should have no issues with the os it is flawed and should not happen. I am sorry to say but The blackberry OS is a lot more stable. There may not be as many apps but it is more productive and being able to multi task is a lot more needed on a phone. I was told yesterday I would get a call back today at 7pm when this tech support lady would start her shift to give me my options and she did not call. Making me call at 930pm today and after talking to someone I waited for 45 minuets to be hung up on. That is a real great way to treat a customer and make things better. I just want away from the Andriod OS. What difference does it make to you as a company to make a customer happy who was with you since 08 and having a second device added on to the account? What Poor way to treat someone to make them happy with all the profits you have and can't give anything back to a customer.

    What a frustrating experience I have had trying to get away from This phone and Plan. I just want to down grade this phone. What difference does it make to you here? All VZW will do is re certify the phone and give it to someone else. I just would like to down grade to a cheaper phone and do away with android os. I still have the same issues with the phone as I did with my other one within a hour of re activating it. I should have no issues with the os it is flawed and should not happen. I am sorry to say but The blackberry OS is a lot more stable. There may not be as many apps but it is more productive and being able to multi task is a lot more needed on a phone. I was told yesterday I would get a call back today at 7pm when this tech support lady would start her shift to give me my options and she did not call. Making me call at 930pm today and after talking to someone I waited for 45 minuets to be hung up on. That is a real great way to treat a customer and make things better. I just want away from the Andriod OS. What difference does it make to you as a company to make a customer happy who was with you since 08 and having a second device added on to the account? What Poor way to treat someone to make them happy with all the profits you have and can't give anything back to a customer.

Maybe you are looking for