JOptionPane title bar icon - java

I'd like to replace the icon in a JOptionPane title bar (as it currently shows the default Java coffee logo).
I tried the following:
JOptionPane.showMessageDialog(null, "Some Text", "Login",
JOptionPane.INFORMATION_MESSAGE, ImageCacheProvider
.instance.getImageIcon("img/an image.png"));
It replaces the icon in the window but not the one in the title bar:
Is there any approach to change the icon in the title bar or alternatively to hide the default Java icon without having to implement a JDialog class?
Thanks a bunch!
Thomas

Use it like this:
Icon icon = new ImageIcon("d:/temp/CheckBox.gif");
JOptionPane jp = new JOptionPane("Session Expired - Please Re Login"),
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
icon);
JDialog dialog = jp.createDialog(null, "Session Expired - Please Re Login");
((Frame)dialog.getParent()).setIconImage(((ImageIcon)icon).getImage());
dialog.setResizable(true);
dialog.setVisible(true);

This worked well for me:
private static final Image myImage = ...;
/*
* Copied from javax.swing.JOptionPane.showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)
*/
#SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException {
JOptionPane pane = new JOptionPane(message, messageType, optionType, icon, options, initialValue);
pane.setInitialValue(initialValue);
JDialog dialog = pane.createDialog(parentComponent, title);
// Added this line
dialog.setIconImage(myImage);
pane.selectInitialValue();
dialog.show();
dialog.dispose();
Object selectedValue = pane.getValue();
if (selectedValue == null)
return JOptionPane.CLOSED_OPTION;
if (options == null) {
if (selectedValue instanceof Integer)
return ((Integer) selectedValue).intValue();
return JOptionPane.CLOSED_OPTION;
}
for (int counter = 0, maxCounter = options.length; counter < maxCounter; counter++) {
if (options[counter].equals(selectedValue))
return counter;
}
return JOptionPane.CLOSED_OPTION;
}

Related

JOptionPane Dialog Determine if Close Button was Clicked

I want to create a dialog with a checkbox and a combobox. This is what I have:
JCheckBox checkBox = new JCheckBox("My checkbox");
JLabel modeLabel = new JLabel("Select mode:");
String[] modes = {"A", "B", "C"};
JComboBox<String> modesComboBox = new JComboBox<>(modes);
JPanel modePanel = new JPanel(new FlowLayout());
modePanel.add(modeLabel);
modePanel.add(modesComboBox);
JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
dialogPanel.add(checkBox);
dialogPanel.add(modePanel);
JOptionPane.showMessageDialog(null, dialogPanel);
How do I determine whether the Close (i.e., "X") button or the OK button was clicked? I need to know which one of these two buttons caused the dialog to close.
Use JOptionPane.showConfirmDialog(Component,Object) (or overloaded equivalents) to get an int returned that reports yes, no or cancelled.
Calling showConfirmDialog..
Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option.
Parameters:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
message - the Object to display
Returns:
an integer indicating the option selected by the user
Edit
On closer inspection, it becomes apparent this task needs both a confirmation dialog and an option dialog. Here is a complete example that reports the results of the user choices to the console.
import javax.swing.*;
public class OptionSelection {
public OptionSelection() {
int result;
String[] modes = {"A", "B", "C"};
result = JOptionPane.showOptionDialog(
null,
"Modes",
"Select mode",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
modes,
"B"
);
if (result == JOptionPane.CLOSED_OPTION) {
System.out.println("User canceled mode selection");
} else {
System.out.println("Result: " + modes[result]);
}
result = JOptionPane.showConfirmDialog(null,
"Are you now, or have you ever?",
"Declaration",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
System.out.println("User says YES!");
} else if (result == JOptionPane.NO_OPTION) {
System.out.println("User says NO!");
} else {
System.out.println("User canceled");
}
}
public static void main(String[] args) {
Runnable r = () -> new OptionSelection();
SwingUtilities.invokeLater(r);
}
}

Show JOptionPane (with dropdown menu) on the top of other windows

I am working on a program that shows the following menu (menu_image) when it starts. I have a little problem: I'd want to show it on the top of the other windows, but I am not able to achieve this.
class Menu {
public String showMenu(){
Object[] options = {"option1", "option2", "option3"};
Object selectionObject = JOptionPane.showInputDialog(null, "Choose", "Menu", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
String selectionString = selectionObject.toString();
return selectionString;
}
}
Can someone help me, please? Thank you in advance
Based on Berger's suggestion, I solved my problem in the following way...
class Menu {
public String showMenu(){
//i solved my problem adding the following 2 lines of code...
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
Object[] options = {"option1", "option2", "option3"};
//...and passing `frame` instead of `null` as first parameter
Object selectionObject = JOptionPane.showInputDialog(frame, "Choose", "Menu", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
String selectionString = selectionObject.toString();
return selectionString;
}
}

Can't display intiali value in JoptionPane within JDialog

This is probably a dumb question, but I can't figure out how to fix it. I want all my JoptionPanes to be resizable, so I am imbedding them in JDialog. I will have to convert all my showXxxDialog calls eventually, so I decided to start with showInputDialog. Everything works (the Dialog looks nice, and is resizable), except that it won't display the initial value in the JOptionPane display, even though it is correct in the JOptionPane constructor. Here is my code (messageType is PLAIN_MESSAGE, but QUESTION_MESSAGE does the same):
public class MyOptionPane {
static Object showInputDialog(Object f, Object message, String title, int messageType,
Icon ico, Object[] options, Object initValue) {
JOptionPane pane = new JOptionPane(message, messageType, JOptionPane.OK_CANCEL_OPTION,
ico, options, initValue);
JDialog dialog = pane.createDialog((Component) f, title);
if (!dialog.isResizable()) {
dialog.setResizable(true);
}
pane.setWantsInput(true);
dialog.pack();
dialog.setVisible(true);
return pane.getInputValue();
}
}
Help would be much appreciated!
I have good and bad news, a fix to your problem is to include the line: pane.setInitialSelectionValue(initValue);. Great right? Well the bad news is that I cannot explain why it doesn't auto insert the initValue via the constructor. Hopefully someone else can build off of this and explain to us both.
import javax.swing.*;
import java.awt.*;
public class MyOptionPane {
static Object showInputDialog(Object f, Object message, String title, int messageType,
Icon ico, Object[] options, Object initValue) {
JOptionPane pane = new JOptionPane(message, messageType, JOptionPane.OK_CANCEL_OPTION,
ico, options, initValue);
JDialog dialog = pane.createDialog((Component) f, title);
if (!dialog.isResizable()) {
dialog.setResizable(true);
}
pane.setInitialSelectionValue(pane.getInitialValue()); // set it
pane.setWantsInput(true);
dialog.pack();
dialog.setVisible(true);
return pane.getInputValue();
}
}

How JOptionPane's showInputDialog Works?

I was wondering how inputdialog returns value especially when there are also ok and cancel buttons.
Could somebody explain how does it manage to return value?
UPDATE:
Let me put it this way.
I want to create a dialog with 6 buttons and each button returns different value.
And i want it get that value like this:
String value = MyDialog.getValue(); // like showInputDialog
the problem is how do i return value on button press?
Now that I have a clearer understanding of your goal, I think instead of trying to emulate JOptionPane, it would be easier to just give each button a different actionCommand:
private JDialog dialog;
private String inputValue;
String showPromptDialog(Frame parent) {
dialog = new JDialog(parent, true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// [add components to dialog here]
firstButton.setAction(new ButtonAction("Button 1", "first"));
secondButton.setAction(new ButtonAction("Button 2", "second"));
thirdButton.setAction(new ButtonAction("Button 3", "third"));
fourthButton.setAction(new ButtonAction("Button 4", "fourth"));
fifthButton.setAction(new ButtonAction("Button 5", "fifth"));
sixthButton.setAction(new ButtonAction("Button 6", "sixth"));
dialog.pack();
dialog.setLocationRelativeTo(parent);
inputValue = null;
dialog.setVisible(true);
return inputValue;
}
private class ButtonAction
extends AbstractAction {
private static final long serialVersionUID = 1;
ButtonAction(String text,
String actionCommand) {
super(text);
putValue(ACTION_COMMAND_KEY, actionCommand);
}
public void actionPerformed(ActionEvent event) {
inputValue = event.getActionCommand();
dialog.dispose();
}
}
From the Java tutorials
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
You might like to familiarise yourself with the section on "Getting the User's Input from a Dialog"
You should also familiarise yourself with the Java Docs on the same subject

How to tame the X on the JOptionPane Dialog boxes?

Also, right now whenever I click the 'X" button on top right, the dialog boxes behaves as if I clicked OK (on messages) or YES (on questions). When the user clicks the X, I want DO_Nothing.
In the code below, when i click on the X on the dialog box, it pops out the 'eat!'. Apparently, the X is acting as 'YES' Option, which it should not.
int c =JOptionPane.showConfirmDialog(null, "Are you hungry?", "1", JOptionPane.YES_NO_OPTION);
if(c==JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else {JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);}
Changed to show how to ignore the cancel button on Dialog box per OP clarification of question:
JOptionPane pane = new JOptionPane("Are you hungry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
JDialog dialog = pane.createDialog("Title");
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
}
});
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();
dialog.setVisible(true);
int c = ((Integer)pane.getValue()).intValue();
if(c == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else if (c == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);
}
You can't do what you want through the usual JOptionPane.show* methods.
You have to do something like this:
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType)
{
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
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 line that actually disables the close button is:
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

Categories

Resources