overriding JComboBox getSelectedItem is not working - java

I m trying to override my JComboBox getSelectedItem method using this static method :
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
// query to select ID and TITLE from profiles table
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
ArrayList visualItems = new ArrayList(); // the Items of my combobox [item1,item2]
ArrayList idItems = new ArrayList(); // the corresponding IDs for each item [id1,id2]
while (myJComboResultSet.next()) {
visualItems.add(myJComboResultSet.getObject("TITRE")); // filling items set
idItems.add(myJComboResultSet.getObject("ID")); // filling IDs set
}
System.out.println("IDItems=" + idItems); // checking that my Items are filled
System.out.println("visualItems=" + visualItems); // checking that my IDs are filled
// creating a combobox of previous items
jComboBox = new JComboBox(visualItems.toArray()) {
ArrayList values = idItems;
// overriding the getSelectedItem to return the corresponding selected item's ID
#Override
public Object getSelectedItem() {
Object get = values.get(super.getSelectedIndex());
System.out.println("get = " + get);
return get;
}
};
}
I m calling this method from another frame :
JComboBoxTools.setupID_TITLE_ComboBox(J_Users_Profile,"profiles");
But when executed it don't work.
the output :
visualItems=[Admin,Teacher,Student]
IDItems=[0,3,5]
the selected item return value is : Teacher
Don't know what to do I want it to return 3 wich is the ID of teacher.
the full project is under : this link
thank you.

I get my desired values using a mapComboBoxModel
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
HashMap myMap = new HashMap();
while (myJComboResultSet.next()) {
myMap.put(myJComboResultSet.getObject("TITRE"), myJComboResultSet.getObject("ID"));
}
jComboBox.setModel(new MapComboBoxModel(myMap) {
#Override
public Object getValue(Object selectedItem) {
return map_data.get(selectedItem); //To change body of generated methods, choose Tools | Templates.
}
});
}
I overrided getValue to return the ID .
if (myComponent instanceof JComboBox) {
JComboBox jComboBox = (JComboBox) myComponent;
MapComboBoxModel model = (MapComboBoxModel) jComboBox.getModel();
values+=""+model.getValue(model.getSelectedItem())+",";
}

Related

How would I unit test jdbcTemplate.query that have overrides?

I have a class that uses multiple get methods the returns
public int getCurrNum(String Name) {
// query clearances table to return an int that represents the clearance level
String sql = "SELECT number FROM clearances WHERE '" + Name + "' = name;";
//String.format("SELECT number FROM clearances WHERE '%s' = name;",clearanceName);
return jdbcTemplate.queryForObject(sql, Integer.class);
}
which I understand I can use Mockito with a statement like Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))).thenReturn(1);
But that is not really testing values that are being passed in because I am just telling it to return a value I want. I want to make sure all these methods return what the parameters are specially passing in. We have a user token with user details being sent in. We also have more JdbcTemplates such as
public List<String> getCurr(String currCountry) {
// query alliances table to return a list of alliance tags that countain the
// user's country tag
String sql = "SELECT * FROM user WHERE '" + currCountry + "' = ANY(access_tags) ;";
return jdbcTemplate.query(sql, new RowMapper<String>() {
#Override
public String mapRow(ResultSet rs, int rownumber) throws SQLException {
return rs.getString(1);
}
});
Then the last methods combines everything and has this return statement that uses all these setters from another class.
// return list of appropriately filtered missions
return jdbcTemplate.query(sql, new RowMapper<Mission>() {
#Override
public OtherClass mapRow(ResultSet rs, int rownumber) throws SQLException {
OtherClass m = new OtherClass();
m.setNumber(rs.getInt(1));
m.setName(rs.getString(2));
m.setLastCheckinDate(rs.getString(3));
m.setLocation(rs.getString(4));
m.setCurrLocation(rs.getString(5));
m.setFinalLocation(rs.getString(6));
m.setTags(rs.getString(7));
return m;
}
});
}
But I am not sure how to test these statements. Without using the Mockito.when commands, they always turn out null. We have this information in a database .xml file for the column and rows so it knows what information to grab to fill in the lists. Do I need to mock a mock db or something to test this?

Printing out ObservableList<ObsevableList<String>>items from a tableview one item at a time

I have Board model that I map to a tableView. I can printout the entire selection, but I am trying to print out each line in the selection with special formatting.
Here is the model
public class Board (String pieceno, String avge, String lpte, String lptloc, String grade) {
String PcNo;
String AvgE;
String LptE;
String LptLoc;
String Grade;
public Board( {
this.PcNo = pieceno;
this.AvgE = avge;
this.LptE = lpte;
this.LptLoc = lptloc;
this.Grade = grade;
}
public String getPcNo() {
return PcNo;
}
public void setPcNo(String pcno) {
PcNo = pcno;
}
pubic String getAvgE() {
return AvgE;
}
public void setAvgE(String avge) {
AvgE = avge;
}
public String getLptE() {
return LptE;
}
public void setLptE(String lpte) {
LptE = lpte;
}
public String getLptLoc() {
return LptLoc;
}
public void setLptLoc(String lptloc) {
LptLoc = lptloc;
}
public String getGrade() {
return Grade;
}
public void setGrade(String gr) {
Grade = gr;
}
#Override
public String toString() {
return getPcNo() + "," + getAvgE() + "," + getLptE()
+ "," + getLptLoc() + "," + getGrade() + "\n";
}
}
Now here is the code for tableView and selection of multiple rows.
TableView tableView = new TableView();
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
TableColumn pcNoCol = new TableColumn();
pcNoCol.setText("pcNo");
pcNoCol.setCellValueFactory(new PropertyValueFactory("pcNo"));
tableView.getColumns().add(pcNoCol);
TableColumn avgECol = new TableColumn();
avgECol.setText("avgE");
avgECol.setCellValueFactory(new PropertyValueFactory("avgE"));
tableView.getColumns().add(avgECol);
TableColumn lptECol = new TableColumn();
lptECol.setText("lptE");
lptECol.setCellValueFactory(new PropertyValueFactory("lptE"));
tableView.getColumns().add(lptECol);
TableColumn lptLocCol = new TableColumn();
lptLocCol.setText("lptLoc");
lptLocCol.setCellValueFactory(new PropertyValueFactory("lptLoc"));
tableView.getColumns().add(lptLocCol);
TableColumn gradeCol = new TableColumn();
gradeCol.setText("grade");
gradeCol.setCellValueFactory(new PropertyValueFactory("grade"));
tableView.getColumns().add(gradeCol);
//Bindings.
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
tableView.itemsProperty().bind(service.valueProperty());
Now the mouse event that grabs the rows and prints out selecteditems is
tableView.setOnMousePressed((MouseEvent event) -> {
ObservableList<ObservableList<String>>selectedItems = tableView.getSelectionModel().getSelectedItems();
//selectedItems.forEach(selecteditem -> System.out.println(selecteditem));
System.out.println(selectedItems);
});
The code works, but Instead of println(selectedItems) I wish to print out each individual selected item, I try the line that is commented out above the foreach line. but I get the following error.
Executing /home/jimbo/NetBeanProjects/AccountFXFrontEnd/dist/run12421/AccountFXFrontEnd.jar usring platform /usr/java/jdk1.8.0_91/jre/bin/java
Exception in thread"JavaFX Application Thread" java.lang.ClassCastException: accountfxfrontend model Board cannot be cast to javafx.collections.ObservableList
at java.lang.Iterable.forEach Iterable.java.75
Can someone tell me what I need to do in order to print out each item rather than the collection? Thanks.
I should be obvious that I am new to javafx and collections I appreciate the help ..
jimbo
You should really start using type parameters, like TableView<Board>. It will help to avoid such mistakes. So, this:
tableView.getSelectionModel().getSelectedItems();
returns ObservableList<Board>, not ObservableList<ObservableList<String>>. Hence the exception when using forEach, as it tries to cast Board to ObservableList. You don't get it with System.out.println(selectedItems), because in this case there is no type casting, println just operates with Object. By the way, if you use:
ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems();
it will work with forEach as well, because, again, it will be operating with Object.

glazedlists with ID in java

I am using glazedlists for JComboBox in java to make a JComboBox searchable and sortable. But there is situation I can't get to solve it.
I have a JComboBox attached with glazedlists. glazedlists takes String array to fill this combobox and make it searchable like this
String[] Values = {"ABC", "DEF", "GHI", "JKL", "MNO"};
JComboBox cmb = new JComboBox();
AutoCompleteSupport.install(cmb , GlazedLists.eventListOf(Values));
This works good but the problem is that I want to add ID along with value coming from Database and for that I am implementing my own custom ListCellRenderer like this
class MyListRenderer extends JLabel implements ListCellRenderer
{
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Object[] itemData = (Object[])value;
setText((String)itemData[1]);
return this;
}
}
cmb.setRenderer(new MyListRenderer());
And to add value in JComboBox, I have to
while(rs.next()){
int id=rs.getInt("company_id");
String category=rs.getString("company_name");
Object[] itemData = new Object[] {id, category};
cmb.addItem(itemData);
}
Now how can I implement my JComboBox with glazedlists while setting my own custom renderer?
Didn't have any success with your way, but I found a solution in an earlier project. You can set the model of the JComboBox instead by doing something like this:
//load the list of objects to use
ContainerClass[] allOptions = ContainerClass.getAll();
//create an EventList with this list and set is as the combobox model
final EventList<ContainerClass> eventList = GlazedLists.eventList(Arrays.asList(allOptions));
comboBox.setModel(new DefaultComboBoxModel<ContainerClass>(allOptions));
//finally initialize the combobox by SwingUtilities if done on a non-UI thread
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AutoCompleteSupport<ContainerClass> install =
AutoCompleteSupport.install(comboBox, eventList);
install.setFilterMode(TextMatcherEditor.CONTAINS);
install.setHidesPopupOnFocusLost(true);
install.setSelectsTextOnFocusGain(false);
install.setCorrectsCase(false);
}
});
And with a ContainerClass like:
class ContainerClass{
int id;
String company;
//helper method to get all the objects needed
static ContainerClass[] getAll(){
ContainerClass test = new ContainerClass();
test.id = 2;
test.company = "abc";
return new ContainerClass[]{test,test,test};
}
#Override
//this String is what actually will be displayed in the combobox
public String toString(){return "(" + id + ") " + company;}
}
And I'm assuming that your JComboBox has the following type:
JComboBox<ContainerClass> comboBox;
(I had to obfuscate the names of all variables, so there might be errors in the code. Let me know and I will correct them)
So to recap. GlazedLists uses the model to get the names, which again asks the ContainerClass for it's toString() method which will return the name to display in the JComboBox.
As a note, when you call comboBox.getSelectedItem() it will return an object of type ContainerClass, or null if it isn't a valid selection.
UPDATE
If you want to be able to control the order as well as the name, you would need to implement your own model for the ComboBox. Found this that seems to explain it well:
class MyComboBoxModel extends AbstractListModel implements ComboBoxModel {
String[] ComputerComps = { "Monitor", "Key Board", "Mouse", "Joy Stick",
"Modem", "CD ROM", "RAM Chip", "Diskette" };
String selection = null;
public Object getElementAt(int index) {
return ComputerComps[index];
}
public int getSize() {
return ComputerComps.length;
}
public void setSelectedItem(Object anItem) {
selection = (String) anItem; // to select and register an
} // item from the pull-down list
// Methods implemented from the interface ComboBoxModel
public Object getSelectedItem() {
return selection; // to add the selection to the combo box
}
}

displaying value, but selecting an id from drop down list

The user types 2 letters in the autocomplete text box
Those 2 letters get saved and used in a web service method in order to
retrieve all users who start with those 2 letters
XML result get returned, and get parsed, and we retrieve the user name+ the id and
save each one in different ArrayList
the result from the first name arraylist get puts in an a dropdown list (the autocomplete one)
The user select an item from the drop list items
--
I need to display the name in the drop down list, however, when the user chooses a name, that user ID should be selected and saved as a String in order to be used for another query.
Question is: How to display the name but select the ID for that name
AutoCompleteTextView assigneeInput;
assigneeInput=(AutoCompleteTextView)
findViewById(id.editassignee);
assigneeInput.addTextChangedListener(new
TextWatcher() {
#Override
public void onTextChanged (CharSequence s,int start, int before, int count){
getContactsForAssignee();
}
#Override
public void beforeTextChanged (CharSequence s,int start, int count, int after){
}
#Override
public void afterTextChanged (Editable s){
}
}
);
//Textwatcher for assignee input -end
}
//Method to get Contacts for the assignee autocomplete - Start
public void getContactsForAssignee() {
//webservice call method
}
//Method to get Contacts for the assignee autocomplete - End
public void receiveResults10(String result10) {
try {
//Dom parsing set up
List<String> valSetOne = new ArrayList<String>();
List<String> valSetTwo = new ArrayList<String>();
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < nodesUDSObjectList.getLength(); i++) {
Element elementUDSObject = (Element) nodesUDSObjectList.item(i);
NodeList nodesAttributeList = elementUDSObject.getElementsByTagName("Attribute");
HashMap<String, String> mapp = new HashMap<String, String>();
for (int iA = 0; iA < nodesAttributeList.getLength(); iA++) {
Element elementAttribute = (Element) nodesAttributeList.item(iA);
//You have attribute(iA)
NodeList AttrNameElementList = (NodeList) elementAttribute.getElementsByTagName("AttrName");
String nameValue = getCharacterDataFromElement((Element) (AttrNameElementList.item(0)));
System.out.println("name" + nameValue);
NodeList AttrValueElementList = (NodeList) elementAttribute.getElementsByTagName("AttrValue");
String valueValue = getCharacterDataFromElement((Element) (AttrValueElementList.item(0)));
if (nameValue.equals("name")) {
valSetOne.add(valueValue);
mapp.put(COMBO_NAME, valueValue);
}
if (nameValue.equals("id")) {
valSetTwo.add(valueValue);
mapp.put(PERSISTENT_ID, valueValue);
}
}
menuItems.add(mapp);
}
AutoCompleteTextView editAssignee;
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, valSetOne);
editAssignee = (AutoCompleteTextView) findViewById(R.id.editassignee);
editAssignee.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
}
//Beginning of method to actually save the ticket executed on click of the "save" button
public void SaveThisIncident(View v) {
AutoCompleteTextView editAssigneeInput = (AutoCompleteTextView) findViewById(R.id.editassignee); //receiving the users input for assignee
String thisIsAssignee = editAssigneeInput.getText().toString();
}
You need to set itemclicklistner for your AutoCompleteTextView editAssignee & use BaseAdapter instead of ArrayAdapter.
Pass ArrayList of your custom object which contain both id & string value to baseadapter.
Custom object can be
public class item{
String id;
String value;
}
Now onClickItem you can get both id & value from your Arraylist

Java Combobox, Managing 2 fields from database

I want to get a result set with 2 fields from my DB.
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
And then I want to show the field called "name_prov" in the comboBox (As the item). But I also want to have my "id_prov" which is the ID (PRIMARY KEY) as the value for this item. This serves for the purpose of relating the name (of the providers in this case) with its ID just by using the combobox.
This is the code of the JComboBox event FocusGained that Im currently using.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
CBProvedores.addItem(rs.getString("name_prov"));
//Here should be the Value related to the item I am creating
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
Is there anyway I can accomplish this?
First create a POJO, which will hold both your name and id.
public class ComboItem {
private String id;
private String name;
public ComboItem(String id, String name) {
this.id = id;
this.name = name;
}
// Add the getter and setter as you want.
// This will be used internally by JComboBox as the label to be displayed.
#Override
public String toString() {
return name;
}
}
Then use this POJO objects to be put into your JComboBox.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
String id = rs.getString("id_prov"); // Get the Id
String name = rs.getString("name_prov"); // Get the Name
ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
CBProv.addItem(comboItem); // Put it into the ComboBox
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
And then finally to get the value selected, you can do this:-
CBProv.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
// comboItem.getId(), comboItem.getName() - Use as you wish.
}
});
Hi there i am Also still a newbie to java and javafx. This is what i did in javafx and it worked for me Hope you can work around it in java.
private void fillProviders()
{
List<String> providerList = new ArrayList<String>();
try
{
String Sql = "select * from prov ";
pat= conn.prepareStatement(Sql);
rs=pat.executeQuery();
while (rs.next())
{
providerList.add(rs.getString("id_prov")+" "+ rs.getString("name_prov"));
}
ObservableList<String> provider = FXCollections.observableArrayList(providerList);
bankName.setItems(provider);
}
catch( Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Hope it works for you. Note that my my combobox Name is bankName

Categories

Resources