JAVA: conditioning String to comboBox items, it is possible? - java

I am trying to make an if conditional statement that will compare my textfield FillUnitTextTag to jcombobox cmbBox_PurchsUnit's items so that, no redundant items will be added to the combobox.
my FillUnitTextTag textfield is the field were I can add item(s) to the comboBox cmbBox_PurchsUnit but it also keeps the existing one(intentional).
How may I get rid of it?
here's my actual code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(FillUnitTextTag.getText().equals(cmbBox_PurchsUnit.getSelectedIndex())){
JOptionPane.showMessageDialog(null, "Item is already in the combobox");
} else {
int p = JOptionPane.showConfirmDialog(null, FillUnitTextTag.getText()+" will be added to units.\n"
+ "Do want to continue?","", JOptionPane.YES_NO_OPTION);
if(p==0){
cmbBox_PurchsUnit.addItem(FillUnitTextTag.getText());
cmbBox_PurchsUnit.setSelectedItem(FillUnitTextTag.getText());
UnitPopUp.dispose();
}
}
}
Thanks in advance!

Get the JComboBox's model via its getModel() method,
then loop through the model using a for loop comparing Strings in the model vs the String to add.
The model has a getSize() method that tells you how many times to loop
And it has a getElementAt(int index) method that allows you to get each item in the model for comparison.
In pseudocode (since again, you're better off writing your own code):
set a boolean variable, okToAdd to true
Get your combo box's model by calling getModel() on it.
create a for loop that loops from 0 to the size of the model, which you get by calling getSize()
in the loop get each item from the model via getElementAt(int index)
compare the item to the String of interest via the equals(...) method
If they match then change okToAdd to false
end of for loop.
If okToAdd is true, add String to the combo box's model

How about:
ComboBoxModel cmbBoxmodel = cmbBox_PurchsUnit.getModel();
cmbBoxmodel.getSize();
for(int dis=0;dis<=cmbBoxmodel.getSize();dis++){
cmbBoxmodel.getElementAt(dis);
}

Related

Get the value of a specific cell of JTable with mouse clicking

I have a JTable and Given such codes:
jTable.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
System.out.println(jTable.getRowCount());
System.out.println(jTable.getModel().getValueAt(jTable.getRowCount(), 0));
}
});
If I click on a certain row, like in the picture above, I clicked the second row, how can I get that row's content?(How to get the Canada)?
Personally, I use the Mouse Clicked event. You could try something like this inside your event method:
private void myTableMouseClicked(java.awt.event.MouseEvent evt) {
int row = this.myTable.getSelectedRow();
int column = this.myTable.getSelectedColumn();
this.myTable.getValueAt(selectedRow, selectedColumn);
}
Be aware that the getValueAt method returns an Object. You probably will need to cast the Object returned into the object it is supposed to be. And also you could have a global variable that's going to have the value returned by getValueAt for using it as you need.
I hope it helps.

How to remove an item from a jlist

I have a Jlist which is populated with books, however, what I would like to do is that once one of the books is selected I press a button called return book that should make the book removed from the list.
I have a members class that has a return book method as follows
public void returnBook(Book aBook)
{
currentLoans.remove(aBook);
aBook.setBorrower(null);
}
On my main application I have the following code under the return book button
private void theButtonActionPerformed(java.awt.event.ActionEvent evt) {
//!!!Return book
DefaultListModel model = (DefaultListModel) BooksOnLoan.getModel();
Book selectedBook;
selectedBook = (Book)BooksOnLoan.getModel();
model.remove(selectedBook);
}
As you can see I am quite not sure how to remove the item from the list once the button is clicked.
The method "remove" from DefaultListModel works with index, so you first need to get the index of the element that you want to remove and provide that to the remove method. You can use methods on your list for that: getSelectedIndex method for single selection mode (you will get -1 if there is no selection), or getSelectedIndices for multiselect.
If in any case your list stays the same after this, you need to refresh GUI after the model has been changed. Although I am almost certain that you need not do that, but keep this principle in mind for future.

JComboBox display blank area when getItemCount()>0

I use JcomboBox as a suggestion box that when user type in, it check for matches and display suggestion.
Here is how I create the JComboBox:
Vector<String> popUpVector = new Vector<String>();
JComboBox jcb = new JComboBox(popUpVector);
every time Key Listener catch event, I do this
popUpVector.clear();
jcb.hidhPopUp();
for(String s : database){
popUpVector.add(s);
}
jcb.showPopUp();
It works as long as I don't select item from the dropdown.
However, once I select item from the dropdown, the dropDown will display blank afterward, I check the popUpVector, it is not empty though, I think it has something to do with the selection, so I unhook it from actionListener, it didn't helps.
Can anyone help me with this, thanks a lot!
Passing a Vector to the JComboBox constructor will according to the source indeed use that vector to back the underlying model:
public JComboBox(Vector<?> items) {
super();
setModel(new DefaultComboBoxModel(items));
init();
}
and
public DefaultComboBoxModel(Vector<?> v) {
objects = v;
if ( getSize() > 0 ) {
selectedObject = getElementAt( 0 );
}
}
Meaning that if you change the contents of the vector, you also change the contents of your model. However, making changes to the model requires to fire the correct events to inform the view about the changes. And since vector does not fire any events, the DefaultComboBoxModel has no way of knowing that the contents of the vector has been changed.
So imo the DefaultComboBoxModel constructor simply should have taken the elements from the vector and store those iso storing the vector directly.
Now to solve your problem: instead of storing your values in a Vector, use a DefaultComboBoxModel and use the available API on that model to make the changes. Using the API will make sure the model fires the correct changes. See for example the implementation of the addElement method:
public void addElement(Object anObject) {
objects.addElement(anObject);
fireIntervalAdded(this,objects.size()-1, objects.size()-1);
if ( objects.size() == 1 && selectedObject == null && anObject != null ) {
setSelectedItem( anObject );
}
}
your issue is
popUpVector.clear();
correct way to clear the Vector is only
popUpVector = new Vector<String>();
better could be to add / remove / modify the JComboBoxes Items in ComboBoxModel

Java: Iterate JMenuItem from ArrayList with HashMaps

I have a JFrame with a menubar, in which i'd like some dynamic menus, as in, depending on the size of the ArrayList with HashLists. The problem here is that i then got a dynamic amount of JMenuItems, so i need a way to get as much variables as HashLists. In this case i made the name of the variable static, but obviously that's not working on the ActionListener, since all MenuItems will have the same ActionListener.
I'm wondering how to solve this, and how to get a menu with a dynamic amount of menuitems which all have unique actionlisteners.
private ArrayList<HashMap> menuLijst;
.
for (HashMap h : menuLijst) {
String vraag = (String) h.get("vraag");
JMenuItem qMenu = new JMenuItem(vraag);
informatie.add(qMenu);
qMenu.addActionListener(this);
}
Thanks in advance.
Depending on what you want to do in your ActionListener, you can either use this, as you do right now and in the actionPerformed you can then use ((JMenutItem)event.getSource()) to see which menu item has been clicked. Alternatively, you could register as many ActionListeners as there are menus, like this:
for (final HashMap h : menuLijst) {
final String vraag = (String) h.get("vraag");
final JMenuItem qMenu = new JMenuItem(vraag);
informatie.add(qMenu);
qMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// here event.getSource() is the same as qMenu
System.out.println("Menu "+qMenu+" with label "+vraag+" has been pressed");
System.out.println("HashMap is "+h);
}
});
}
But to me (and also seeing your previous questions), it seems that you are abusing the usage of HashMap instead of using appropriate new objects. I don't know what else is in your HashMap, let's say that you have 3 keys: "vraag", "answer", "grade", you could create the following class:
public class MyClass {
private String vraag;
private String answer;
private int grade;
// And getters and setters here.
}
And have a List<MyClass> instead of List<HashMap>.
I don't see why you want to use a HashMap for your Strings. If you save an ArrayList of Strings, and loop over them to add them all to the menu, you can add actionListeners to all of them, just as you are doing now.
In your ActionListener, check which button is clicked by looping through the ArrayList, and comparing to the name of the clicked button.

problem when implementing a selection listener in a JTable

I am developing a JTable with different rows. I would like to associate an event to the selection of a row in this table. I have used the following selection class to provide behaviour to the table selection:
public class TableSelectionListener implements ListSelectionListener{
public Integer item;
public TableSelectionListener(Integer item){
this.dialog = item;
}
public void valueChanged(ListSelectionEvent e) {
System.out.println("The row clicked is "+item);
}
}
When I create an instance of this table, sai tabletest, I have added the following piece of code:
tabletest.getSelectionModel().addListSelectionListener(new TableSelectionListener(tabletest.getSelectedRow());
The problem is that when I click on one row once, instead of retrieving the related message once, I retrieve the same message several times, suggesting that the actions repeated several times. For example:
The row clicked is 0
The row clicked is 0
The row clicked is 0
The row clicked is 0
Does anyone know where the problem may be?
Well, that's just normal.
Your selection listener is created with the value of tabletest.getSelectedRow() at its creation table (which is zero). And, as you never change the value of item in your listener, this listener fcan only display 0as a result.
If I were you, I wouold replace the valueChanged() method by something like (although it's untested and I remember strange things happens sometimes when mixing view and model row values) this :
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) // added as sometimes, multiple events are fired while selection changes
System.out.println("The row clicked is "+e.getFirstIndex());
}
Firstly, it's perfectly normal to get multiple ListSelectionEvents, while the selection is being changed. You can use the getValueIsAdjusting method to determine when selection has ended (it will return false).
Secondly, there's no need to construct your TableSelectionListener with a row number. When your valueChanged method is called, you can get the index of the first/last selected row (remember it's possibly to select multiple rows in the table, unless you disable that) using e.getFirstIndex() and e.getLastIndex() respectively.
An easier way of doing it, is as follows:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("e...."+table.getSelectedRow());
}
});

Categories

Resources