how to change the default text of buttons in JOptionPane.showInputDialog - java

I want to set the text of OK and CANCEL buttons in JOptionPane.showInputDialog
to my own strings.
There is a way to change the buttons' text in JOptionPane.showOptionDialog, but I couldn't find a way to change it in showInputDialog.

if you don't want it for just a single inputDialog, add these lines prior to creating dialog
UIManager.put("OptionPane.cancelButtonText", "nope");
UIManager.put("OptionPane.okButtonText", "yup");
where 'yup' and 'nope' is the text you want displayed

The code below should make a dialog appear and you can specify the button text in the Object[].
Object[] choices = {"One", "Two"};
Object defaultChoice = choices[0];
JOptionPane.showOptionDialog(this,
"Select one of the values",
"Title message",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
choices,
defaultChoice);
Also, make sure to look through the Java tutorials on the Oracle site. I found the solution at this link in the tutorials http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#create

If you want the JOptionPane.showInputDialog with custom button texts, you could extend JOptionPane:
public class JEnhancedOptionPane extends JOptionPane {
public static String showInputDialog(final Object message, final Object[] options)
throws HeadlessException {
final JOptionPane pane = new JOptionPane(message, QUESTION_MESSAGE,
OK_CANCEL_OPTION, null,
options, null);
pane.setWantsInput(true);
pane.setComponentOrientation((getRootFrame()).getComponentOrientation());
pane.setMessageType(QUESTION_MESSAGE);
pane.selectInitialValue();
final String title = UIManager.getString("OptionPane.inputDialogTitle", null);
final JDialog dialog = pane.createDialog(null, title);
dialog.setVisible(true);
dialog.dispose();
final Object value = pane.getInputValue();
return (value == UNINITIALIZED_VALUE) ? null : (String) value;
}
}
You could call it like this:
JEnhancedOptionPane.showInputDialog("Number:", new Object[]{"Yes", "No"});

Please see How to Make Dialogs: Customizing Button Text.

Related

how to combine joptionpane with combobox

i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.
i've tried change but the red code always show
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String wel = sdf.format(cal1.getDate());
String NamaFile = "/report/harianMasuk.jasper";
HashMap hash = new HashMap();
String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
try {
hash.put("til", wel);
hash.put("rul", tak);
runReportDefault(NamaFile, hash);
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
Read the section from the Swing tutorial on Getting User Input From a Dialog.
It demonstrates how to display a combo box in a JOptionPane.
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:
String selectedItem = "";
int selectedItemIndex = -1;
/* Ensure dialog never hides behind anything (use if
the keyword 'this' can not be used or there is no
object to reference as parent for the dialog). */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------
int btns = JOptionPane.OK_CANCEL_OPTION;
String dialogMessage = "<html>Select the desired item from the Drop-Down "
+ "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
"Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);
// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
if (res == 2) {
selectedItem = "Selection Option Was Canceled!";
break;
}
selectedItemIndex = cb.getSelectedIndex();
if (res == JOptionPane.OK_OPTION) {
if (selectedItemIndex == -1) {
JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
+ "select something or select <font color=red><b>Cancel</b></font>.",
"Invalid Selection...", JOptionPane.WARNING_MESSAGE);
}
else {
selectedItem = cb.getSelectedItem().toString();
}
}
iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
+ "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
+ "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();
With the above code, the Input dialog that will be displayed would look something like this:
It is up to you to find the means to fill the comboBoxItems String Array used within the code above.

get values of Jtextfields when click OK in Dialog

My need is to display a tab in a JDialog (confirmDialog or inputDialog). The tab contains 2 JTextField per row. The display works fine :
but I don't know how to get the values of the JTextFields.
Here is the display code :
int size = model.getCheckedApplications().size();
// une ligne par application sélectionnée
layout = new GridLayout(size + 1, 3, 5, 5);
myPanel = new JPanel(layout);
myPanel.add(new JLabel("Application"));
myPanel.add(new JLabel("Version cadre"));
myPanel.add(new JLabel("Nouvelles natures"));
for (Application app : model.getCheckedApplications()) {
myPanel.add(new JLabel(app.getCode88()));
JTextField versionActuelleField = new JTextField(30);
versionActuelleField.setName("versionActuelle"
+ app.getCode88());
versionActuelleField.setText(app
.getVersionCadreActuelle());
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
myPanel.add(versionActuelleField);
myPanel.add(nouvellesNaturesField);
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then I don't know how to get the values when the user clicks on the OK Button :
if (result == 0) { // The user clicks on the ok button
You need to add them to some list that you store, so you can get at them again. Since you are adding them in reference to an application, I would suggest a Map
private Map<Application, JTextField> nouvellesNaturesFields = new ArrayListMultimap<Application, JTextField>(); //Or Hashmap, if the key is unique
private Map<Application, JTextField> versionActuelleFields = new ArrayListMultiMap<Application, JTextField>();
public List<JTextField> getNouvellesNaturesFields() {
return nouvellesNaturesFields ;
}
public List<JTextField> getVersionActuelleFields () {
return versionActuelleFields ;
}
//class code
for (Application app : model.getCheckedApplications()) {
//Other code
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
nouvellesNaturesFields.put(app, nouvellesNaturesField);
//Other code and same for your new nature fields
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then when the user clicks the confirm button, using the property accessor getNouvellesNaturesFields()or getVersionActuelleFields() you can iterate all the fields created, like so:
for (Map.Entry<Application, JTextField> entry: myMap.entries()) {
//Do something here
}
Or you could also get them via:
for (Application app : model.getCheckedApplications()) {
List<JTextField> data = myMap.get(app);
for(JTextField field : data) {
field.getText();
}
}
Since the key value probably won't be unique, I used an ArrayListMultiMap, but if it would be unique, then a HashMap should suffice
You assign the Jtextfield value to a string using the getText() method e.g below
String texfield = JTextField.getText();
Subsequently you use the String textfield wherever you want. And to get the right jtextfield you have to get text from the textfield you want for example you have four Jtexfield. Assuming they are JTextField1, JTextField2, JTextField3 and JTextField4. To get the value of JTextField3 you have
String texfield = JTextField3.getText();
The values should be in the JTextFields you created:
versionActuelleField
nouvellesNaturesField
Also, you might want to look at ParamDialog, which I implemented to be a generic solution to this question.
EDIT
Yes I see now that you are creating these JTextFields in a loop. So you need to create a Collection, I'd suggest a Map<String, JTextField> where you could map all of your application names to the matching JTextField, as well as iterate over the collection to get all application names / JTextFields.

How to rename the Text OK and cancel of the org.eclipse.jface.dialogs.MessageDialog

I'm using the Message Dialog of org.eclipse.jface.dialogs and i need to rename the 'Ok' and 'Cancel' text in the buttons displayed. How to go about ?
MessageDialog requestRestartDialog = new MessageDialog(window.getShell(), "Title", null,
"Message to be displayed", MessageDialog.CONFIRM, new String[] { "String 1", "String 2" }, 0);
int index = requestRestartDialog.open();
index will return the array index of the label specified.

Force JOptionPane to Stay Open

My application is constructed as follows:
Main window allows user to select CSV file to be parsed
JOptionPane appears after a CSV file is selected and the JOptionPane contains a drop-down menu with various choices; each of which generates a separate window
Currently, the JOptionPane closes after a selection is made from the menu and the "OK" button is clicked
I am looking for a way to force the JOptionPane to remain open so that the user can select something different if they want. I would like the JOptionPane to be closed only by clicking the "X" in the upper right corner. I am also open to other possibilities to achieve a similar result if using a JOptionPane isn't the best way to go on this.
Here is the relevant block of code I'm working on:
try
{
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
// Reads the complete file into list of tokens.
List<String[]> rowsAsTokens = null;
try
{
rowsAsTokens = reader.readAll();
}
catch (IOException e1)
{
e1.printStackTrace();
}
String[] menuChoices = { "option 1", "option 2", "option 3" };
String graphSelection = (String) JOptionPane.showInputDialog(null,
"Choose from the following options...", "Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
menuChoices, // Array of menuChoices
menuChoices[0]); // Initial choice
String menuSelection = graphSelection;
// Condition if first item in drop-down is selected
if (menuSelection == menuChoices[0] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option1();
}
if (menuSelection == menuChoices[1] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option2();
}
if (menuSelection == menuChoices[2] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option3();
}
else if (graphSelection == null)
{
log.append("Cancelled." + newline);
}
}
I would like for the window with the choices to remain open even after
the user has selected an option so that they can select another option
if they wish. How do I get the JOptionPane to remain open instead of
its default behavior where it closes once a drop-down value is
selected?
this is basic property, by default JOptionPane is disposed, this isn't possible without dirty hacks, don't do that
use JDialog (could, may be undecorated) with proper value for ModalityType
you can to use some of variations for Java & Ribbon
you can to put desired choices to the JComboBox or JMenu with JMenuItems (very nice of ways) to the JLayer or GlassPane
I think that this is standard job for JMenu or JToolBar
In either of these option panes, I can change my choice as many times as I like before closing it. The 3rd option pane will show (default to) the value selected earlier in the 1st - the current value.
import java.awt.*;
import javax.swing.*;
class Options {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"None of the above"
};
JComboBox optionControl = new JComboBox(options);
optionControl.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
System.out.println(optionControl.getSelectedItem());
String graphSelection = (String) JOptionPane.showInputDialog(
null,
"Choose from the following options...",
"Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
options, // Array of menuChoices
options[3]); // Initial choice
System.out.println(graphSelection);
// show the combo with current value!
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I think Michael guessed right with a JList. Here is a comparison between list & combo.
Note that both JList & JComboBox can use a renderer as seen in the combo. The important difference is that a list is an embedded component that supports multiple selection.
The following solution won't give you a drop-down menu but it will allow you to select multiple values.
You can use a JList to store your choices and to use JOptionPane.showInputMessage like this:
JList listOfChoices = new JList(new String[] {"First", "Second", "Third"});
JOptionPane.showInputDialog(null, listOfChoices, "Select Multiple Values...", JOptionPane.QUESTION_MESSAGE);
Using the method getSelectedIndices() on listOfChoices after the JOptionPane.showInputDialog() will return an array of integers that contains the indexes that were selected from the JList and you can use a ListModel to get their values:
int[] ans = listOfChoices.getSelectedIndices();
ListModel listOfChoicesModel = listOfChoices.getModel();
for (int i : ans) {
System.out.println(listOfChoicesModel.getElementAt(i));
}

Configure width, wrap & font of pop-up

I'm Java beginner. I'm using the below code to show a pop-up whenever required in my application.
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType)
{
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
//pane.setFont(new java.awt.Font("SansSerif", 0, 12));//Not working to change the font of pop-up text and button texts
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
//dialog.setFont(new java.awt.Font("SansSerif", 0, 12)); //Not working to change the font of pop-up text and button texts
dialog.setLocationRelativeTo(parentComponent);
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true) ;
dialog.dispose();
Object o = pane.getValue();
if (o instanceof Integer) {
return (Integer)o;
}
return JOptionPane.CLOSED_OPTION;
}
The pop up is being shown properly, but have following problems:
How to change the font to the pop up text/message and text of button (yes/no)?
How to restrict the pop up width to its parents width?
How to wrap the pop up text (like wrapping the text in text area)?
Update: (Answer for 1)
Get the components from JOptionPane and set the fonts as below:
private static final String key = "OptionPane.messageFont";
//Question: QUESTION_MESSAGE
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType){
UIManager.put(key, new java.awt.Font("SansSerif", 0, 12));
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
JPanel buttonPanel = (JPanel)pane.getComponent(1);
Object buttonOk[] = buttonPanel.getComponents();
for (int i = 0; i < buttonOk.length; i++) {
JButton button = (JButton)buttonOk[i];
button.setFont(new java.awt.Font("SansSerif", 0, 12));
button.validate();
}
pane.setFont(new java.awt.Font("SansSerif", 0, 12));
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
dialog.setFont(new java.awt.Font("SansSerif", 0, 12));
dialog.setLocationRelativeTo(parentComponent);
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true) ;
dialog.dispose();
Object o = pane.getValue();
if (o instanceof Integer) {
return (Integer)o;
}
return JOptionPane.CLOSED_OPTION;
}
Update 2 (Answer for 3rd question):
Use the below function which automatically wraps the text. This function inturn calls showConfirmDialog(parentComponent, message, title, optionType); The code for showConfirmDialog(...) is already given in the question.
/**
* Question/Confirmation Message Dialog Multiline.
* It DONOT require linebreak ("\n") for multiline messages. It will automatically wrap the text to new lines.
* Note: last when used was not properly working. Please verify it.
*/
public static int showConfirmDialogMultiLine(Component parentComponent,
Object message, String title, int optionType){
JTextArea textArea = new JTextArea((String)message);
textArea.setColumns(50);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
textArea.setBackground(parentComponent.getBackground());
textArea.setFont(Usability.getFont("DialogBoxes.DialogTextFont")); //$NON-NLS-1$
textArea.setEditable(false);
message = textArea;
int retVal = showConfirmDialog(parentComponent,
message,
title,
optionType);
return retVal;
}
Do anybody know answers for 2nd question?
You can use the UIManager to change the OptionPane.messageFont, as suggested below.
private static final String key = "OptionPane.messageFont";
...
private int showConfirmDialog(...) {
UIManager.put(key, UIManager.getFont(key).deriveFont(Font.ITALIC, 20));
JOptionPane pane = new JOptionPane(...);
...
}
Addendum: Where do I get different keys?
UIManager Defaults is an excellent resource for this, as it can examine the default properties of installed Look & Feel implementations.

Categories

Resources