Display selected Item in JComboBox when item is clicked - java

I currently have 2 JComboBoxes. When an item in the first JComboBox is selected, relevant items are displayed in JComboBox2. However when I try to select the items in the second JComboBox it keeps returning to default. However it is registering the value of the item that is selected, just not displaying the selected item in the JComboBox.
Here is a snippet of my code:
mainComboBox = new JComboBox( treeItems);
mainComboBox.addActionListener( this );
getContentPane().add( mainComboBox, BorderLayout.WEST );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.addActionListener(this);
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
getContentPane().add( subComboBox, BorderLayout.EAST );
String [] chromalveolataItems = chromalveolataTreeSet.toArray(new String[chromalveolataTreeSet.size()]);
subItems.put(treeItems[1], chromalveolataItems);
String [] mycetozoaItems = mycetozoaTreeSet.toArray(new String[mycetozoaTreeSet.size()]);
subItems.put(treeItems[2], mycetozoaItems);
String [] metazoaItems = metazoaTreeSet.toArray(new String[metazoaTreeSet.size()]);
subItems.put(treeItems[3], metazoaItems);
String [] viridiplantaeItems = viridiplantaeTreeSet.toArray(new String[viridiplantaeTreeSet.size()]);
subItems.put(treeItems[4], viridiplantaeItems);
String [] virusesItems = virusesTreeSet.toArray(new String[virusesTreeSet.size()]);
subItems.put(treeItems[5], virusesItems);
.
#Override
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
String organismComboItem = (String)subComboBox.getSelectedItem();
if(treeArray.contains(organismComboItem)){
//System.out.println(treeArray.indexOf(organismComboItem));
String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
System.out.println(selectedId);
}
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
There is probably a relatively simple solution to this however I am new to Java so please forgive me.
Any help whatsoever would be much appreciated! :)

Looks to me like you based your code on the example found in this posting: Binding comboboxes in swing (or one like it).
When you use examples don't add extra code.
subComboBox.addActionListener(this);
The example does not do this. By adding the same listener to the subComboBox you are telling it to reset itself every time you select an item from it. Only the mainComboBox needs the ActionListener.

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.

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

My program has a Country and State combobox, and from the state combobox it only gets the first value no matter what you choose [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So i created a program for an assignment i have, which creates a sequential file with data about students. I made a country and state combobox, depending on the country comes the corresponding states, but in the sequential file (which is a .dat file) no matter what state i choose, in the sequential file, the state is always the first one.For example if choose Australia and Tasmania state , the state in the sequential file will be New South Wales. Here is my code thanks in advance
public assignment1st()
{
super("create student file");
try{
output=new DataOutputStream(new FileOutputStream("studentRec.dat"));
}
catch ( IOException e ) {
System.err.println( "File won't open properly/n" +
e.toString( ) );
System.exit( 1 );
}
initialize();
//*******HERE STARTS THE COUNTRY/STATE COMBOBOX BUILD**************************************
String[] countries = {"-CHOOSE","Australia","Belgium","Brazil","Canada","Georgia","Greece",
"India","Lithuania","Macedonia"};
comboBox_1 = new JComboBox<Object>(countries);
comboBox_1.addActionListener(this);
comboBox_1.setBounds(278, 142, 92, 20);
frame.getContentPane().add(comboBox_1);
// Create sub combo box with multiple models
//State Combobox
comboBox_2 = new JComboBox<String>();
comboBox_2.addItem("-CHOOSE-");
comboBox_2.setBounds(452, 142, 109, 20);
frame.getContentPane().add(comboBox_2);
comboBox_2.setPrototypeDisplayValue("XXXXXXXXXX");
String[] Australia = { "New South Wales", "Tasmania", "Queensland" ,"Victoria"};
states.put(countries[1], Australia);
String[] Belgium = { "Louxembourg", "Hainaut", "Flemish" };
states.put(countries[2], Belgium);
String[] Brazil = { "Amazonas", "Mato Grosso" };
states.put(countries[3], Brazil);
String[] Canada = { "Vancouver", "Quebec" };
states.put(countries[4], Canada);
String[] Georgia = {"Tbilisi", "S.Ossetia" };
states.put(countries[5], Georgia);
String[] Greece = { "Pelloponisos", "Chalchidikis", "Thesprotias" };
states.put(countries[6], Greece);
String[] India = { "Jalpur", "Kolkata", "New Delhi" };
states.put(countries[7], India);
String[] Lithuania = { "Akmene", "Kretinga", "Varena" };
states.put(countries[8],Lithuania);
String[] Macedonia = { "Bitola", "Struga", "Veles" };
states.put(countries[9], Macedonia);
}
code which imports data
if ( studentID > 0 ) {
//PLACE FOR COMBOBOXEZ
String sex=(String) comboBox.getSelectedItem();
output.writeUTF(sex);
String country=(String) comboBox_1.getSelectedItem();
output.writeUTF(country);
String state=(String) comboBox_2.getSelectedItem();
output.writeUTF(state);
String month=(String) comboBox_3.getSelectedItem();
output.writeUTF(month);
String day=(String) comboBox_4.getSelectedItem();
output.writeUTF(day);
String year=(String) comboBox_5.getSelectedItem();
output.writeUTF(year);
output.writeInt(maths);
output.writeInt(buisness);
output.writeInt(programming);
output.writeInt(accounting);
output.writeInt(art);
output.writeInt(music);
and finally the actionperformed for the country state comboboxes
public void actionPerformed( ActionEvent e ) {
//*************FOR STATE AND COUNTRY COMBOBOXEZ*********************
String country = (String)comboBox_1.getSelectedItem();
Object o = states.get( country );
if (o == null)
{
comboBox_2.setModel( new DefaultComboBoxModel<String>() );
}
else
{
comboBox_2.setModel( new DefaultComboBoxModel<String>( (String[])o ) );
}
//**********DONE WITH THE STATE AND COUNTRY COMBOBOXEZ**********
This is because your this part of code :
if (o == null)
{
comboBoxstate.setModel( new DefaultComboBoxModel<String>() );
}
else
{
comboBoxstate.setModel( new DefaultComboBoxModel<String>( (String[])o ) );
}
Is before this:
if (e.getSource()==btnEnter){
addRecord( ) ;
}
As such, your combo box gets rearranged first, and then the record is added.
If you put the second part before the first one, it works perfectly. That's it.
But, I would suggest you to check which component caused the action, and then do what you want to do, else actions on some components can cause operations which you expected some other component to perform. If you want that, you can experiment with e.getActionCommand()

How to get the text content on the swt table with arbitrary controls

I have different controls placed on a table using TableEditor.
...
TableItem [] items = table.getItems ();
for (int i=0; i<items.length; i++) {
TableEditor editor = new TableEditor (table);
final Text text1 = new Text (table, SWT.NONE);
text1.setText(listSimOnlyComponents.get(i).getName());
text1.setEditable(false);
editor.grabHorizontal = true;
editor.setEditor(text1, items[i], 0);
editor = new TableEditor (table);
final CCombo combo1 = new CCombo (table, SWT.NONE);
combo1.setText("");
Set<String> comps = mapComponentToPort.keySet();
for(String comp:comps)
combo1.add(comp);
editor.grabHorizontal = true;
editor.setEditor(combo1, items[i], 1);
} //end of for
...
When I try to get the text on the table using getItem(i).getText, I get empty string
...
TableItem [] items = table.getItems ();
for(int i=0; i<items.length; i++) {
TableItem item = items[i];
String col0text = items[i].getText(0); //this text is empty
String col1text = items[i].getText(1); //this text is empty
}
...
Why does getText returns empty strings even when I have text appearing on the table?
Instead of using the text property, you might consider using the data property instead.
Benefits:
you can attach the data (e.g. a control or complex data structure) directly to the table item.
the only thing your table item creation need to know from your table cell editor is the object reference to be stored in the data property.
you don't need that event handling stuff (just read the controls data when you really need it).
Create:
TableItem item = new TableItem(table, SWT.None);
TableEditor editor = new TableEditor(table);
Button checkbox = new Button(table, SWT.CHECK);
checkbox.pack();
editor.setEditor(checkbox,item,0);
item.setData("cb",checkbox); // using key enables you to add more pieces of complex data
Read:
for (TableItem item : table) {
Button checkbox = (Button) item.getData("cb");
if (checkbox.getSelection()) { /* ... do whatever you want */ }
}
When the table shows up, the checkbox is visible and can be clicked. Using the setText method fails in case of transparent background controls -> you will see the text of the table items cell below
your control (I tried this).
Anyway it would be much easier if it would be possible to extend the table item class to hide even the data key. But as usual, subclassing is denied.
in the event listeners for the controls I added
item.setText call
...
combo1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
String sel = combo2.getText();
item.setText(ComponentPortToConnectCol, sel);
}});
...
This gives me the desired result. Thanks OTisler for the clue
How are you setting up your table? I copied your code to debug it and set up the table as shown below (first for loop)
I tried but couldn't reproduce the problem you're seeing. It might be the way you are adding things to the table.
TableEditor Examples
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
for (int i = 0; i < 3; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "" + i, "" + i, "" + i });
}
TableItem [] items = table.getItems();
for (int i=0; i<items.length; i++) {
TableEditor editor = new TableEditor (table);
final Text text1 = new Text (table, SWT.NONE);
text1.setText("TEST");
text1.setEditable(false);
editor.grabHorizontal = true;
editor.setEditor(text1, items[i], 0);
editor = new TableEditor (table);
final CCombo combo1 = new CCombo (table, SWT.NONE);
combo1.setText("");
String[] comps = {"A","B","C"};
for(String comp:comps)
combo1.add(comp);
editor.grabHorizontal = true;
editor.setEditor(combo1, items[i], 1);
} //end of for
TableItem [] items2 = table.getItems ();
for(int i=0; i<items2.length; i++) {
TableItem item = items2[i];
String col0text = items2[i].getText(0); //returns '0' first for loop
}

Categories

Resources