JDialog Ok/Cancel button events
Dear Java gurus,
I have something that's been bugging me for days. Now, maybe it's really obvious but my cold has bunged up my head too much to think clearly. Anyway, I thought I'd pass it this way for expert opinion..
I have a class that extends JDialog, with various textboxes, comboboxes etc. It also has the usual OK + Cancel buttons. The only thing left to implement is something like this:
MyCustomDialog d = new MyCustomDialog();
int returnVal = d.showDialog();
This is similar to most of the dialogs provided with Swing, where the return value is a static field something along the lines of 0 == OK button pressed, 1 == Cancel.
This allows me to only start "getting" the values from the dialog only if the user selects ok. The problem is, I can't see how to accomplish this. I've been looking at the source for JFileChooser and JColorChooser, but they are more complicated than I can follow. (I am relatively novice when it comes to Swing) I promise, I have been looking on the net for examples, but I've had no luck. Maybe because any searching for JDialog tends to bring back simple examples of the supplied Swing dialogs.
So, any suggestions?
TIA
arooaroo wrote: Shame, because I thought you were on to something.
I was. Trust me.
Look at the signature for JOptionPane.showConfirmDialog(). This is the simplest version, but the others look like this and then some:
static int showConfirmDialog(Component parentComponent, Object message)
Note that the message parameter is of type object. This means you can theoretically pass any type of object. A component is an object. Therefore, you can pass a JPanel as the message parameter.
Look at this quote from the JOptionPane description in the API:
message
A descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant. However, the type of this parameter is actually Object. Its interpretation depends on its type:
Object[]
An array of objects is interpreted as a series of messages (one per object) arranged in a vertical stack. The interpretation is recursive -- each object in the array is interpreted according to its type.
Component
The Component is displayed in the dialog.
Icon
The Icon is wrapped in a JLabel and displayed in the dialog.
others
The object is converted to a String by calling its toString method. The result is wrapped in a JLabel and displayed.
I was going to suggest the modal option on JDialog, but for some reason I thought it wouldn't work. I still think using JOptionPane would be easier; that's what it was designed for.
Dusty
Similar Messages
-
InputListofValue PopUp window CANCEL button event capture ?
HI All ,
Jdeveloper version 11.X.6.
i have explained the outline of issue below:
User enter some data on InpuLIstOfValue text field and click on the maginfied Glass, the pop opens and selects some data and click 'OK' ,it will display appropriately on below fields.
but if user enters the wrong data on InpuLIstOfValue text field and clicks on maginfier Glass,no results found on the popup window, so upon click of "CANCEL" button on popup window ,
is there any way to remove the old data on InpuLIstOfValue Filed ?
Basicaly i am looking for the capturing the CANCEL button event on the popUpwindow ,based on event status .
PLase let us know if any hints ?
ThanksStep by step:
1. Create the converter class:
package view.converters;
import java.util.Collection;
import java.util.Collections;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import org.apache.myfaces.trinidad.convert.ClientConverter;
import org.apache.commons.lang.StringUtils;
public class LOVConverter implements Converter, ClientConverter {
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
if (StringUtils.isBlank(value)) {
// cancel event was triggered, so do something
return value; // if value is not an instance of String you need to convert it to its primary type (Number, Date, String, etc)
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value)
if (value == null || /* value is empty in its primary type */) {
// cancel event was triggered, so do something
return value.toString();
public String getClientLibrarySource(FacesContext facesContext)
return null;
public Collection<String> getClientImportNames()
return Collections.emptySet();
public String getClientScript(FacesContext facesContext, UIComponent uiComponent)
return null;
public String getClientConversion(FacesContext facesContext, UIComponent uiComponent)
return null;
}2. Declare the converter in faces-config.xml:
<converter>
<converter-id>LOVConverter</converter-id>
<converter-class>view.converters.LOVConverter</converter-class>
</converter>3. Your inputListOfValues should look like this (see the property converter="LOVConverter"):
<af:inputListOfValues popupTitle="Search"
value="#{row.bindings.DepartmentId.inputValue}"
model="#{row.bindings.DepartmentId.listOfValuesModel}"
required="#{bindings.EmployeesView1.hints.DepartmentId.mandatory}"
columns="#{bindings.EmployeesView1.hints.DepartmentId.displayWidth}"
shortDesc="#{bindings.EmployeesView1.hints.DepartmentId.tooltip}"
converter="LOVConverter"
id="ilov1">After that, when the user clicks the Cancel button, both methods (getAsObject and getAsString) should be invoked, and then you would be able to reset the component value (using uiComponent parameter).
AP -
Multithreaded Swing and a "Cancel Button"
I have a Swing-based app that runs some lengthy JDBC queries. Currently when the user hits the "Run Query" button a small dialog pops up to say that the process is running, please wait, etc. I'd like to add a working Cancel button to that dialog that will allow the user to stop that query before it finnishes.
From what I've been able to learn so far it seems I should use one of the SwingUtilities methods such as invokeAndWait or invokeLater. I'm not sure which one would be more appropriate for my situation though.
I'm also having trouble thinking of an elegant way (or not-so elegant if that's the only way) to have the cancel button event communicate with the DB Query thread to let it know that the process should be stopped. Detailed explanations or examples would be welcome.
MikeYou will not need to use the SwingUtilities methods. Those are when you want to update the GUI from a different thread. In your case, you want to update a class running in a non-gui thread from the GUI thread. Not a problem.
You will want to create a Runnable class that runs your query. Run that class on another thread when the query is executed. There will need to be some public 'cancel' method in that class that can be called when you want that object to cancel whatever operation it is doing. Simply call that 'cancel' method from your dialog button's action when the user hits the cancel button.
Now, how your query class handles the cancel method is the main problem. The api way of doing this would be to call the Statement.cancel() method on the statement object that is performing the query. But how (or if) that method works depends on the jdbc driver & database, hopefully yours supports it. :-) -
Capturing the Cancel button with Before Print event handler
I put together a script that is triggered by a beforePrint event handler. Everything works fine but I can't figure out how and where to capture the user clicking on the Cancel button in the Print dialog?
Any ideas? Thanks, DanAlen,
My bet is you are using JDeveloper 11.1.1.5. This is a known ADF bug 12551764 in this release, not related to JHeadstart.
Here are the details:
http://adfbugs.blogspot.com/2011/05/jdeveloper-11115-serius-bug.html
I just checked the bug database, it is fixed in patch 12399372. You can go to metalink to download the patch.
Steven Davelaar,
JHeadstart Team. -
Hello.
I have the following code:-
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ok)
theType = type.getSelection().getActionCommand();
// use the entered data
theBid = Integer.parseInt(bid.getText());
theName = name.getText();
else if (e.getSource() == cancel) {
// data entry cancelled
dispose();
}my problem is the cancel button doesn't actually cancel although does close the window it still submits the data.
how can i get it to destroy all data and then close the window?
many thanks in advance.
dave.Hello,
those bits of code still don't seem to work. it ends up setting 'null' for strings and 0 for ints still when i press cancel.
here is more code to show where the data is actually used:-
GUINew.java (part of previous code):-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUINew extends JDialog implements ActionListener
private JButton ok;
private JButton cancel;
private ButtonGroup type;
private JTextField bid;
private JTextField name;
int theBid;
String theName;
String theType;
public GUINew(String sTitle, JFrame owner) {
super (owner, sTitle, true);
setLooknFeel();
bid = new JTextField(4);
name = new JTextField(14);
ok = new JButton("Hire Boat!");
ok.addActionListener(this);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
type = new ButtonGroup();
// create each radio button, specifying its label
JRadioButton pedal = new JRadioButton("Pedal boat");
JRadioButton rowing = new JRadioButton("Rowing boat");
// set a String to associate with each button
// will use this when the radio button is selected
pedal.setActionCommand("Pedal boat");
rowing.setActionCommand("Rowing boat");
type.add(pedal);
type.add(rowing);
JPanel top = new JPanel();
top.add(pedal);
top.add(rowing);
getContentPane().add("North", top);
JPanel center = new JPanel();
center.add(new JLabel("Enter Boat ID:"));
center.add(bid);
center.add(new JLabel("Enter Name/Colour:"));
center.add(name);
getContentPane().add("Center", center);
JPanel bottom = new JPanel();
bottom.add(ok);
bottom.add(cancel);
getContentPane().add("South", bottom);
pack();
public int getBid() { return theBid; }
public String getName() { return theName; }
public String getType() { return theType; }
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ok)
theType = type.getSelection().getActionCommand();
// use the entered data
theBid = Integer.parseInt(bid.getText());
theName = name.getText();
else if (e.getSource() == cancel) {
this.dispose();//will release memory
this.setVisible(false);//will hide the window
dispose();
// windows look and feel settings
private void setLooknFeel() {
String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
try {
UIManager.setLookAndFeel(lookAndFeel);
catch (Exception e) {
e.printStackTrace();
}Main.java - where the data is used:-
else if (e.getSource() == mtOne) { // add new boat
GUINew newb = new GUINew("Add a new boat", this);
newb.setVisible(true);
if(newb.getType() == "Rowing Boat") {
octagon.addBoat(new RowingBoat(newb.getName(), newb.getBid()), newb.getBid(), textarea, title);
else {
octagon.addBoat(new PedalBoat(newb.getName(), newb.getBid()), newb.getBid(), textarea, title);
}at the moment when i click cancel it submits getName as Null and getBid and 0.
Thanks
Dave. -
How to stop the Flex application when user clicks on Cancel button from JS-confirm message?
Hi All,
I use the next code when a user clicks on a link:
private function clickHandler():void
ExternalInterface.call('confirm', 'Of course you want to go to the Adobe forums!');
navigateToURL(new URLRequest('http://forums.adobe.com'), '_self');
This will show up the javascript confimation box. But when the cancel-button is clicked, the user goes straightly to http://forums.adobe.com...
How to stop Flex performing the next code when a user clicks on the Cancel button?
Or, how to catch which button is clicked by a user in Flex?
Thanks!I agree with Mr. Hall that using mx.controls.Alert in Flex may be a better route.
Show the Alert like this:
// show an alert with a question and yes and no choices
Alert.show( "Would you like to go to the Adobe Forums?", "Question",
Alert.YES | Alert.NO, this, closeHandler, null, Alert.YES );
Then handle the response in the closeHandler() function:
protected function closeHandler( closeEvent:CloseEvent ):void
if( event.detail == Alert.YES )
navigateToURL( new URLRequest('http://forums.adobe.com'), '_self' );
else if( event.detail == Alert.NO )
// they chose no
The following documentation on Alerts may be helpful:
http://www.flexafterdark.com/docs/ActionScript-Alert
Let me know if that helps...
Ben Edwards -
How to handle the "cancel" button and "close" icon of a popup ?
Hi,
I have a popup with "cancel button" and "close icon"(on the top right corner of the popup), I want the same operations to be performed on clicking of any of these two components.
Is there a way to handle such situation ?
I read about 2 cases to look into this but they didn't work too well for me.
1. I read about the "popcancellistener" but that listener is called whenever the popup closes, so suppose I have an "ok button" on the popup to create a record, after the record is created, the popup closes and goes into the "popcancellistener", now the question is "how do we know if it came there because of the 'ok button' or 'some other event'".
2. I even checked the "DialogListener", now I'm able to distinguish between the 'OK' and 'CANCEL' button in the dialoglistener using the "Dialog.Outcome.ok/cancel", but when a user clicks on the close icon, we do not enter the "DialogListener" at all, so in this case "how do we handle the close icon click event"
Do let me know if you need any more information from my side.
Thanks for the help in advance.The following mechanism responds to any of the following events: <Esc> key, Close icon ('x'), Cancel button
JavaScript part:
function popupClosedListener(event){
var source = event.getSource();
var popupId = source.getClientId();
var params = {};
params['popupId'] = popupId;
var type = "serverPopupClosed";
var immediate = true;
AdfCustomEvent.queue(source, type, params, immediate);
}JSF part:
<af:popup ....>
<af:clientListener method="popupClosedListener"
type="popupClosed"/>
<af:serverListener type="serverPopupClosed"
method="#{myBean.serverPopupClosedMetod}"/>
</af:popup>Finally, Java part:
public void serverPopupClosedMetod(ClientEvent event){
} -
How to enable the "Cancel button" so you can stop a report while loading ...
I have seen that some reports have a Cancel button located just below "the loading ..".
How can I enable that button in MS Reporting service 2005?The following mechanism responds to any of the following events: <Esc> key, Close icon ('x'), Cancel button
JavaScript part:
function popupClosedListener(event){
var source = event.getSource();
var popupId = source.getClientId();
var params = {};
params['popupId'] = popupId;
var type = "serverPopupClosed";
var immediate = true;
AdfCustomEvent.queue(source, type, params, immediate);
}JSF part:
<af:popup ....>
<af:clientListener method="popupClosedListener"
type="popupClosed"/>
<af:serverListener type="serverPopupClosed"
method="#{myBean.serverPopupClosedMetod}"/>
</af:popup>Finally, Java part:
public void serverPopupClosedMetod(ClientEvent event){
} -
How to disable the cancel button in the ProgressMonitor
hi,
I need to know, is there any way to disable/remove the (cancel)button in the ProgressMonitor?
One more problem is,
Once i click the cancel button, isCanceled() return true, how to make it false again so that the process continue....
It is very urgently.....
please help me out.
Thanks in advance.
Regards,
Deepa RaghuramanI don't think that's a good solution, because Cancel button itself is not disabled, so user is tempted to click it and nothing happens.
A better but dangerous solution is this:
progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,
"Running a Long Task",
"", 0, 100);
progressMonitor.setMillisToDecideToPopup(0);
progressMonitor.setMillisToPopup(0);
progressMonitor.setProgress(0);
JDialog dialog = (JDialog)progressMonitor.getAccessibleContext().getAccessibleParent();
JOptionPane pane = (JOptionPane)dialog.getContentPane().getComponent(0);
pane.setOptions(new Object[]{});Refer to the same question here [http://stackoverflow.com/questions/512151/how-do-i-disable-the-cancel-button-when-using-javax-swing-progressmonitor] . -
Hello,
The popup 'X' has nested view 'Y' and Ok, Cancel buttons. Nested View 'Y' has a start point, a Data service, a table with single column 'Z' and a out-port (configured to event Select), from the out-port, close pop-up endpoint is connected which is mapped to store the value of column 'Z'. The value of column Z, should be send out only on the click of OK button of the pop-up and not when Cancel is clicked, is there a way to validate that? At this moment, it is sent regardless of which button is clicked.
Thanks much,
DharmiHi Kobi,
I understood what you said but how do you do "that can be set to TRUE in the popup OK button." ?? The popup at [design time|http://img145.imageshack.us/img145/8789/popupdesigntimeks2.jpg] and [layout|http://img371.imageshack.us/img371/750/popuplayoutgs4.jpg].
If it is a normal form which has button you can store anything with that to data store, here how would I link that "OK" (close window) action of popup?
Best regards,
Dharmi -
Reg: save exit and cancel buttons
Hi,
In normal report programs when we enable the back , exit and cancel buttons they work fine without writing any code.but its not in the case of Module pool why?
In thr normal reports where does the code come from?
regards
prasanthHi....
Module pool programs is nothing but screen flow + reports...
Here we designing the screens....
So we hav to to give every functionality.. for all buttons and menu items of the appeared screen...
Where as in reports...,
We are just using the standard screen (sellection screen and list output screen ) s mostly...,
Here also some times we hav to go for created screens.. nothing but.... interactive reports...,
There we need to give again all those functionalities...
And..,
To see the BACK button logic and other logics in the reports...,
Ex: PAI event of SAPLWBABAP program...,
You can find that name with...
By giving /H and enter before ur action...
Thanks,
Naveen.I -
Mapping enter and esc to ok and cancel buttons
Hi,
Does java's fine API offer any method of mapping Enter and ESC to OK and Cancel buttons in a customized JDialog?
The current way I'm doing it is through a brute force of adding a KeyListener to every component in the dialog box (in an automated way), is there another way?
Any suggestions would be appreciated.Uh oh, should I be scared because he knows more about
Swing than just about anyone?
Yes. Because if you really get stuck then he won't help you and then you are doomed.
If anybody was rude it was him, and if anybody is an
idiot it's you. See how easy it is to make claims
without providing any reasons or rationale?Reasons and rationale have been provided but I guess you didn't grasp them the first go around so here goes.
1) You were impatient
You waited 30 minutes before whining and bumping. That is impatient. Nobody is being paid to deliver answers to you.
2) You posted in the wrong forum.
This is not the Swing forum is it? No it is not.
3) You should learn to search
If you had searched for even up to 15 minutes (and you wouldn't have needed this long) then you would have had your answer in half the time. Searching saves YOU time.
4) You were rude
When the facts (and please note the use of the word "fact" not personal opinion) above were pointed out to you then you were rude.
Finally the "you are an idiot" problem. I will give you this is the most subjective of the lot although given that you cannot dispute ANY of the above facts (although you seem to be trying and that's helping to make the case that you're quite the idiot) that's really not saying much.
However, it seems to me that if Person A wants the assistance of Person B (who is a valuable resource of information for person A and others) it does not seem wise for Person A to be rude to person B. So in the case of Person A who is rude to Person B who they are relying on as a free resource we can make the assertion that Person A is an idiot.
In case you couldn't follow that you are Person A. -
im trying to program a game that works with JOptionPane, and ive come to this weird problem:
this works fine but throws a null pointer exeption when i press the cancel button:
if (e.getSource() == easy) {
do {
word = JOptionPane.showInputDialog (x.create(1));
result = "" + ((x.right(word)) ? "YOU GUESSED!" : "YOU MISSED!");
JOptionPane.showMessageDialog (null, result);
while (palabra != null);
but when i try to catch the exeption:
if (e.getSource() == easy) {
try {
do
word = JOptionPane.showInputDialog (x.create(1));
result = "" + ((x.right(word)) ? "YOU GUESSED!" : "YOU MISSED!");
JOptionPane.showMessageDialog (null, result);
while (word != null);
catch (NullPointerException no){}
The weird thing happens:
the first time i press cancel it works fine but if i press easy again and then cancel it just reloads the input dialog and if i press cancel again it works, but if i do easy again, this time i have to press cancel 4 times for it to work, and if i press easy again i need 8 cancel, then 16 and so on....
i have no idea why this happens....
can anybody give me some help?
thank you./* the error takes place when presing the cancel button
to make this work press "press me first" and then activate me will show the
window, presing cancel and then again activate me makes everithing worse */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class sample {
static JButton neu = new JButton("Press Me!");
JButton act = new JButton("Activate Me!");
String word,result;
public Component createComponents() {
neu.setMnemonic('i');
neu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
act.addActionListener(this);
if (e.getSource() == act) {
do
word = JOptionPane.showInputDialog ("press cancel");
result = "" + ((word.equals("cancel")) ? "yes!" : "cancel!!!");
JOptionPane.showMessageDialog (null, result);
while (word != null);
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(0, 10));
pane.add(act);
return pane;
public static void addComponentsToPane(Container newbie) {
newbie.setLayout(new GridLayout(5,5,5,5));
newbie.add(neu);
private static void createAndShowGUI() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) { }
JFrame frame = new JFrame("LETTERAMA");
sample app = new sample();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true);
//ps. sorry for the horrible grids, i was kind of in a hurry -
Choose From List Cancel Button Throws Exception
Hi all,
When I click the "Cancel" Button on my CFL, I get an error....
EXCEPTION: Matrix__EBS_FRM_CRDCLM__64.OnAfterChooseFromList raised
No matching records found (ODBC -2028)
Any ideas???Hi
in your choose from list event add this condition
If Not pval.SelectedObjects Is Nothing Then
'write your code in this if condition
end if
hope it will help u.
Regards,
Mithun. -
Customize CANCEL button on ESS WD-ABAP
Hi,
Currently clicking the EXIT or CANCEL button on all ESS applications is opening a new window. We want the user to go back to initial screen while staying on the same window within the portal. Could anyone pls advise how to do this? I dont want to use the Workprotect mode as it is user specific.
Please advise.
Thanks.
Aditya.Hi Aditya,
Currently all the ESS/ MSS applications are FPM based web dynpro applications . So if you need to to modify any of the functionality, even button actions, you need to modify the FPM based web dynpro code. Most of the buttons(like review/ Exit, etc) have the standard FPM based events triggered when ever they are clicked.
One has to dig into the code and understand the flow of control in FPM. You can try to find out which event is being triggered when user clicks on the exit button, and modify code accordingly.
Thanks,
Sonali.
Maybe you are looking for
-
Dealing with dead cd/dvd drive
So my cd/dvd drive seems to be completely dead. I purchased a Sony dvd rewritable drive (DRX-830UL-T). But, duh, the included software I need to install to get it going (apparently Toast 6 Lite) is on CD, and of course, my drive doesn't recognize any
-
How to get the session variable value in JSF
Hi This is Subbus, I'm new for JSF framewrok, i was set the session scope for my LoginBean in faces-config.xml file.. <managed-bean-name>login</managed-bean-name> <managed-bean-class>LoginBean</managed-bean-class> <managed-bean-scope>session</managed
-
How do I turn this off? I can't download anything until I put in the card's information. But the card doesn't work anymore, it ran out of money. It keeps saying that my last perchase was unseccessful or something. I just want this to stop so I can up
-
Trouble with amazon and screen locking the app with voiceover
Hey, This is really bugging me, when I want to listen to a book in my amazon kindle app. I can't seem to screen lock my ipod touch, so that I can put it in a pocket or something instead of carrying it around, does anyone know how to screen lock or sc
-
Says I've installed Flash player successfully, why can't I play a video on FB?
Says I've installed Flash Play successfully, why can't I play a video on FB?