Get text element inside JList to a variable? - java

Despite a lot of research I can't find an answer or solve how to get the selected text element inside a JList to a variable. Therefore I would preciate some help. I have tried to select the index of the selected element and removed elements with this code and that works fine, but as I wrote I want the selected text to a variable after pressing a button. Thanks!
int index = list.getSelectedIndex();
model.removeElementAt(index);
Parts of my JList code:
model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 60));
Parts of my actionlistener code:
// Select customer
if(event.getSource() == buttonSelectCustomer){
int index = list.getSelectedIndex(); // Just for test
model.removeElementAt(index); // Just for test
int number = model.getSize(); // Just for test
//String selectedText = list.getSelectedValue(); // Not working!
}

Use the ListModel#getElementAt(int) method with the currently selected index. If you are certain your model only contains String instances, you can directly cast it to a String as well

You can't get the selected text because you try to get it after you have removed the selected element.
you can change your code:
if(event.getSource() == buttonSelectCustomer)
{
int index = list.getSelectedIndex(); // Just for test
model.removeElementAt(index); // Just for test
int number = model.getSize(); // Just for test
String selectedText = list.getSelectedValue(); // Not working!
}
to my code:
if(event.getSource() == buttonSelectCustomer)
{
String selectedText = (String)list.getSelectedValue(); // it works
int index = list.getSelectedIndex(); // Just for test
model.removeElementAt(index); // Just for test
int number = model.getSize(); // Just for test
}
then it works.

It's easy to retrieve the item of selected index.
Here is a simple code-snippet:
String[] string = new String[]{"Hello","Hi","Bye"};
JList list = new JList(string);
Now use the following code to get the selected item as a string:
String item = list.getSelectedIndex().toString();

Related

Add value to a selected jlist model

So I am trying to make a program that adds a subject to a jList from a textfield and after that, I want to add the grade for that subject from a textfield. Is it possible to store (in an array) that value to the item selected on the jList? so that I can access it for getting the average of all the grades of the subjects entered.
int x[] = jList1.getSelectedIndices();
for(int i = 0; i < jList1.getModel().getSize(); i++){
grade[x[i]] = Double.parseDouble(jTextField2.getText());
jList1.getSelectedValue();
}
You are supposed to manipulate data in the model that jList is based on.
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list = new JList(listModel);
https://docs.oracle.com/javase/tutorial/uiswing/components/list.html#creating
Jlist is a (view) component that displays a list of objects and allows the user to select one or more items. A separate model, ListModel, maintains the contents of the list.
https://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html
What is the exact problem with your implementation?
EDIT
Double grade = Double.parseDouble(jTextField2.getText());
for(int i = 0; i < jList1.getModel().getSize(); i++){
String before = jList1.getModel().getElementAt(i);
String after=before+"_"+String.valueOf(grade);
jList1.getModel().setElementAt(after,i);
}
howto change a value of jlist element in jpane dialog

4 JRadioButtons used in a ButtonGroup, selecting specific button with a numeric value

I have built a UI with 4 radio buttons, and then grouped them together in a ButtonGroup. I get the index of the button selected, and store it in a DB. But when the form is displayed back, i am required to show which button was initially selected. The following is the code i get to save the index value.
Enumeration<AbstractButton> elements = ProdType.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = (AbstractButton) elements.nextElement();
if (button.isSelected()) {
if (button.getText().equals("ZERO"))
strProdType = "0";
else if (button.getText().equals("ONE"))
strProdType = "1";
else if (button.getText().equals("TWO"))
strProdType = "2";
else if (button.getText().equals("THREE"))
strProdType = "3";
else if (button.getText().equals("FOUR"))
strProdType = "4";
}
}
I made few changes to the code shown above, and it now works perfect. I am storing it as String value, and then using the same string value converted to integer while displaying. Some trouble faced cos of RadioButtons and the ButtonGroup. But quite a learning.
Enumeration<AbstractButton> elements = MyType.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = elements.nextElement();
if (button.isSelected()) {
strMyTypeVal = Integer.toString(i);
}
i = i + 1;
}

Get multiple Objects from JList and add them to an Array?

I'm having trouble with this part of my assignment.
This panel also contains a JList object containing the following 10 Canadian universities: Toronto, York, Western, Brock, Guelph, Waterloo, McGill, Concordia, Laval and Macmaster. From that list the user will select 3 universities. A Button labeled "Submit" displayed at the bottom of the panel allows the user to enter the input data coming from textfields and JList object into an array with maximum 100 Student objects.
I have created a String Array for 10 universities.
String uniNames[] = {"Toronto", "York", "Western", "Brock",
"Guelph", "Waterloo", "McGill", "Concordia", "Laval", "Macmaster"};
That Array of Strings is added to a JList
JList<String> uniList = new JList<>(uniNames); //(2)
uniList.setVisibleRowCount(10);
uniList.setFixedCellHeight(34);
uniList.setFixedCellWidth(300);
uniList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Add to uniPanelList
uniPanelList.add(uniList);
//Add to uniPanel
uniPanel.add(label3, BorderLayout.NORTH);
uniPanel.add(uniPanelList, BorderLayout.CENTER);
I have created the Submit button, which takes input data
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent submit){
String name = "", mark = "";
int markNum;
if (submit.getSource()==submitButton){ //If submit is pressed
name = nameInput.getText();
mark = markInput.getText();
markNum = Integer.parseInt(mark); //Convert String to int
//copyList.setListData(colorList.getSelectedValues());
//String objs = uniList.getSelectedValuesList();
//Add information to Array, count++ to keep track
stuArray[count++] = new Student (name, markNum);
nameInput.setText(""); //Resets input area
markInput.setText(""); //Resets input area
//Set label under submit button
outputLabel.setText("Student " + count +
" out of 100 submitted.");
}
}
});
I'm having trouble with the part where the program has to select 3 from my JList, press Submit and it goes into the Array. I have tried getSelectedValuesList(), but it returns an error.
List cannot be converted to String
String objs = uniList.getSelectedValuesList();
I'm stuck trying to figure out where to go on from here. Any tips?
The toArray() function of java.util.List might be what you're looking for. According to the Javadoc:
Returns an array containing all of the elements in this list in proper
sequence.
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent submit) {
String[] selectedUniversities = uniList.getSelectedValuesList().toArray(new String[] {});
}
});
The error message states all you need:
List cannot be converted to String
do instead:
String objs = uniList.getSelectedValue().toString();

Java: Array list of objects & getting values/properties of automatically created checkboxes

I have a ArrayList of Strings that automatically generates a list of check-boxes (of varying count) in a popup window. I currently have two problems with the below code:
Object[] params doesn't work because it requires me to know the size of the ArrayList ar in advance, and I havent figured out to get an arraylist of objects to work with my code. How can I fix this? I tried creating an arraylist of objects, but I could only get it to display nonsensical text.
How can I get the values/text of each checkbox and it's respective isSelected() state?
Below is my code:
String message = "The selected servers will be shutdown.";
Object[] params = {message, null, null, null, null, null};
ArrayList<String> ar = GetSet.getStopCommand(); // Example array: ./Stopplm11.sh|./Stopplm12.sh|./Stopplm14.sh|./Stopplm15.sh
for(int i=0; i< ar.size(); i++){
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
params[i+1]= checkbox;
}
int n = JOptionPane.showConfirmDialog(btnShutdownServer, params, "Shutdown Servers", JOptionPane.OK_CANCEL_OPTION);
if (n == JOptionPane.OK_OPTION){
// DO STUFF
//boolean buttonIsSelected= checkbox.isSelected();
}else{
// user cancelled
}
An image, for those who like images:
You can make it an ArrayList of JCheckBox:
ArrayList<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
Then you can do:
for(int i = 0; i < ar.size(); i++)
{
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
// add the checkbox to the ArrayList
checkboxes.add(checkbox);
}
Finally, to check the state of all checkboxes in your if condition, you can simply do:
if (n == JOptionPane.OK_OPTION){
// DO STUFF
//boolean buttonIsSelected= checkbox.isSelected();
// loop through all checkboxes in the ArrayList
for (JCheckBox checkbox : checkboxes)
{
// current one is selected
boolean buttonIsSelected = checkbox.isSelected();
}
// rest of code in if condition
}
Instead of storing params inside of an array, store those parameters within an ArrayList, as such:
ArrayList<Object> params = new ArrayList<Object>();
params.add("The selected servers will be shutdown.");
for(int i = 0; i < ar.size(); i++)
{
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
params.add(checkbox);
}
Then, make params an array:
Object[] realParams = new Object(params.size());
realParams = params.toArray(realParams);
And then continue the rest of the code as you would.

JavaFX TableView how to get cell's data?

I'm using that method to get whole object.
tableView.getSelectionModel().getSelectedItem()
How can I get data from single cell?
I mean like get S20BJ9DZ300266 as String?
Assuming you know something is selected, you can do
TablePosition pos = table.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
// Item here is the table view type:
Item item = table.getItems().get(row);
TableColumn col = pos.getTableColumn();
// this gives the value in the selected cell:
String data = (String) col.getCellObservableValue(item).getValue();
Assuming you haven't selected any row but know where and what you want....
// Item here is the table view type:
Unpaid item = userTable.getItems().get(0);
TableColumn col = userTable.getColumns().get(3);
// this gives the value in the selected cell:
String data = (String) col.getCellObservableValue(item).getValue();
JOptionPane.showMessageDialog(null, data);
table.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
selected.setText("");
return;
}
System.out.println(newValue.getId());
});
NB: "getId" is your "get" Column and "table" is the name of your tabelview
I solved it. I get the string, for example, "[1, proveedor1, calzado1, Rojo, 39, 600, 2, 1200]", and get the frist cell (id) whit substring. saludos
TablePosition pos = (TablePosition) tableVenta.getSelectionModel().getSelectedCells().get(0);
int index = pos.getRow();
String selected = tableVenta.getItems().get(index).toString();
selected = selected.substring(1, selected.indexOf(","));
System.out.println(selected);
If you are using scene builder, add a method to On Edit Commit for the particular column and add the logic in the controller class. Use event.getNewValue() to get the new value entered by the user. Eg.
#FXML
private void UpdateName(TableColumn.CellEditEvent<ModelClass, String> event) {
ModelClass mc = Table.getSelectionModel().getSelectedItem();
mc.setName(event.getNewValue());
System.err.println("new value "+event.getNewValue());
}
Use this when you allow editable columns
you can use this code i think it's working
String a=personTable.getColumns().get(0).getCellObservableValue(0).getValue().toString();
System.out.println("value"+a);

Categories

Resources