Force JOptionPane to Stay Open - java

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));
}

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.

Having a String or int with a binding to a Property

I need to make a programm in JavaFX where I need to manage a movie library. I have a tableview that is filled by an observable list. Then I made bindings between the Properties and the Textboxes or Labels next to the tableview. Now the problem is, I have also pictures that are related to the movies, like cinema posters. and at the moment I just use a hardcoded one:
imgPoster = new Image(getClass().getResourceAsStream("../resources/images/posters/" + 5 + ".jpg"));
In the datafile there is one column with the ID of the movie and the same number is also the picture for it. So I need to replace that "5" in the sample code with a binding or so that it actively changes the picture as soon as I click on a row in the tableview.
How do I do that?
edit:
After the first comment i did that:
imgOscars = new Image(getClass().getResourceAsStream("../resources/images/oscar/Oscar-logo.png"));
oscars = new ImageView(imgOscars);
oscars.setPreserveRatio(true);
oscars.setFitHeight(45);
but question stays
Either add a listener to the selected item property in the table (I am just guessing at the model you are using for the table):
TableView<Movie> table = ... ;
table.getSelectionModel().selectedItemProperty().addListener((obs, oldSelectedMovie, newSelectedMovie) -> {
if (newSelectedMovie == null) {
oscars.setImage(null);
} else {
// get image from new selection
Image image = new Image(getClass().getResourceAsStream("../resources/images/oscar/"+newSelectedMoviegetId()+".png"));
oscars.setImage(image);
}
});
or use a binding:
oscars.imageProperty().bind(Bindings.createObjectBinding(() -> {
if (table.getSelectionModel().getSelectedItem() == null) {
return null ;
} else {
Movie selected = table.getSelectionModel().getSelectedItem();
return new Image(getClass().getResourceAsStream("../resources/images/oscar/"+selected.getId()+".png")); ;
},
table.getSelectionModel().selectedItemProperty());

Swing check boxes

When the code below is run and the Beta check box is selected, then the Alpha check box, the text reads "Selected check boxes: Alpha, Beta" not "Selected check boxes: Beta, Alpha". Why do they appear in the opposite order to how they were selected?
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CBDemo implements ItemListener {
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(280, 120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected = new JLabel("");
jlabChanged = new JLabel("");
// Make check boxes.
jcbAlpha = new JCheckBox("Alpha");
jcbBeta = new JCheckBox("Beta");
jcbGamma = new JCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes.
public void itemStateChanged(ItemEvent ie) {
String str = "";
// Obtain a reference to the check box that
// caused the event.
JCheckBox cb = (JCheckBox) ie.getItem();
// Report what check box changed.
if(cb.isSelected())
jlabChanged.setText(cb.getText() + " was just selected.");
else
jlabChanged.setText(cb.getText() + " was just cleared.");
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
jlabSelected.setText("Selected check boxes: " + str);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CBDemo();
}
});
}
}
When any check box is clicked itemStateChanged() is called, the order of the string is driven by the order of your str+= statements in the code, not the temporal order of the clicks.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
To achieve the desired behaviour
store the selection events in some kind of ordered structure, e.g. a List that itemStateChanged updates and then displays.
Use different ItemListener instances for each checkbox, or use the ItemEvent parameter to determine where the event came from to update the structure accordingly
Try changing the 3 ifs to a single:
if (cb.isSelected()) {
selectionOrder.add(cb.getText()); // will return Alpha, Beta depending which is selected
}
jlabSelected.setText("Selected check boxes: " + selectionOrder);
Where selectionOrder is a field at the top of your CBDemo class
private List<String> selectionOrder = new ArrayList<String>();
This will obviously keep growing the list indefinitely, but fine for a demo.
Since Your order of Appending value to String is
Alpha --then-->Beta--then-->Gamma
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
So No Matter in which order you select the checkbox .
To achieve your desired output Use
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
jcbAlpha.setSelected(false);// So when Next Time you click on other checkbox this condtion does not append result to Str
}
if(jcbBeta.isSelected()) {
str += "Beta ";
jcbBeta.setSelected(false);
}
if(jcbGamma.isSelected()) {
str += "Gamma";
jcbGamma.setSelected(false);
}

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

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.

Using JComboBox as a search box

Im using a JComboBox to search a query from a sql database. Here is my code.
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.removeAllItems();
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
sr.setSelectedItem(null);
sr.setPopupVisible(true);
System.out.println(sch);
}
sr = JComboBox
But when i type a letter in combobox, it adds all the items in database. I came to know that System.out.println(sch); always gives an empty string. And as soon as i type a letter, the text field of combo box becomes empty(i cant type a word with two letters). How to fix this? Thank you.
The reasons for your problems are the following:
sch is always empty is because you are calling sr.removeAllItems(); before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();. This means that the contents of the JComboBox is cleared (along with the selection) before you get what is selected.
Solution: Call sr.removeAllItems();AFTER you have got the selected item.
The combo box becomes empty because you call sr.setSelectedItem(null); at the end after you have repopulated it.
Solution: If you want the entered text then sr.getEditor().setItem(scr);
Only and idea but try to enclose the contents of the method in an if statement and check if the Enter key is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.
Use an ActionListener instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent when the editing is done.
When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.
Got the solution. This code works fine.
private void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
sr.removeAllItems();
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
sr.setSelectedItem(null);
sr.setPopupVisible(true);
((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
}
Thanks to Skepi,Kleopatra, Guillaume Polet

Categories

Resources