can't get the buttons in the OptionDialog to appear on a new line.
They all appear in one row, but I'd like to have them on separate lines.
I also tried setting up a frame to add to the OptionDialog (to set the max width), but it didn't work out for me either.
Any ideas/help/suggestions appreciated.
Object[] options = { "Button1", "Button2", "Button3", "Button4",
"Button5 On a newLine\n\n", "Button 6", "Button 7" };
int x = JOptionPane.showOptionDialog(null, "Choose a button..", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
Consider this alternative.
import javax.swing.*;
class Options {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5",
"Option 6",
"Option 7",
"None of the above"
};
JComboBox optionList = new JComboBox(options);
optionList.setSelectedIndex(7);
JOptionPane.showMessageDialog(null, optionList, "Title",
JOptionPane.QUESTION_MESSAGE);
}
});
}
}
You can't do that using the Option Dialog from JOptionPane, but you still can create your own dialog window by extending JDialog, and this way you will be able to use the layout you want for your components.
Create your own OptionPane class if you want to break buttons in multiple lines.
You'll be breaking a bunch of UI standards in doing so, though.
The same kind of answer as above, but more concrete:
Object[] options = outputcdirs;
JComboBox optionList = new JComboBox(outputcdirs);
optionList.setSelectedIndex(0);
JPanel jpan = new JPanel ();
jpan.add(new JLabel("Select dirs:"));
jpan.add(optionList);
int n = JOptionPane.showOptionDialog(this, jpan, "text...",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null);
if (n != -1)
n = optionList.getSelectedIndex();
if (n == -1)
throw new Exception("No selection: ...");
String value = outputcdirs[n];
Related
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.
I want to make an options window where a JOptionPane is opened, the user goes through it, and it sets options. I have a problem on lines 10-14 of the following code, though.
if (key == KeyEvent.VK_ENTER) {
Object[] possibleValues = { "Trails (Broken)", "Invicibility" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if (possibleValues[0] != null) {
Object[] options = {"True", "False"};
JOptionPane.showOptionDialog(null,
"Press True To Make It True And False For False",
(String) possibleValues[0], JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (options[0] != null) {
Options.OP_TRAILS = true;
} else if(options[1] != null) {
Options.OP_TRAILS = false;
}
}
}
I think you need to have a read of the JOptionPane JavaDocs and How to Make Dialogs in order to understand what is been returned to you
JOptionPane is providing you withing information about what the user selected. For example...
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
selectedValue is going to either be null (for nothing was selected) or one of the values from the possibleValues array.
JOptionPane.showOptionDialog will return:
an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog
Something like this...
Object[] possibleValues = {"Trails (Broken)", "Invicibility"};
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
System.out.println(selectedValue);
if (possibleValues[0].equals(selectedValue)) {
// Trails (Broken) was selected
Object[] options = {"True", "False"};
int result = JOptionPane.showOptionDialog(null, "Press True To Make It True And False For False", (String) possibleValues[0], JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
switch (result) {
case 0:
Options.OP_TRAILS = false;
break;
case 1:
Options.OP_TRAILS = false;
break;
}
} else if (possibleValues[1].equals(selectedValue)) {
// Invicibility was selected
}
might be more appropriate
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.
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));
}
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.