Add value to a selected jlist model - java

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

Related

Java how to calculate average of an arrayList that some elements removed randomly?

I have an arrayList<Integer> and arrayList<JLabel>. Integer holds the moneys as integers and JLabel holds the same values as strings. I want to remove randomly elements from both labels. For example if 20TL(tl is currency) removed in JLabel i want to remove it in integer arrayList too. It's simple. But then i want to calculate average of remains money in ArrayList. Here is my another arrayList to shuffle 0 to 23 numbers. Therefore i remove the same element both IntList and JLabel list.
ArrayList<Integer> Numbers = new ArrayList<Integer>();
for(int n = 0; n<24; n++){
Numbers.add(n);
}
Collections.shuffle(Numbers);
Then here is my both lists.
ArrayList<Integer> Money = new ArrayList<Integer>();
Money.add(1); Money.add(5); Money.add(10); Money.add(25); Money.add(50); Money.add(100); Money.add(500); Money.add(1000); Money.add(2000);
Money.add(5000); Money.add(10000); Money.add(20000); Money.add(25000); Money.add(30000); Money.add(40000); Money.add(50000); Money.add(100000); Money.add(200000);
Money.add(300000); Money.add(400000); Money.add(500000); Money.add(750000); Money.add(1000000); Money.add(2000000);
String[] para =new String[] {"1 TL","5 TL","10 TL","25 TL", "50 TL","100 TL","500 TL",//create an array for moneys
"1.000 TL","2.000 TL","5.000 TL","10.000 TL","20.000 TL","25.000 TL",
"30.000 TL","40.000 TL","50.000 TL","100.000 TL",
"200.000 TL","300.000 TL","400.000 TL","500.000 TL","750.000 TL"
,"1.000.000 TL","2.000.000 TL"};
ArrayList <JLabel> myLabel = new ArrayList<JLabel>();
for(int i=0; i < 12 ; i++){
JLabel holder = new JLabel();
holder.setText(para[i]);
myLabel.add(holder);
p2.add(holder);//add the label to the panel
}
for(int j=12; j<para.length; j++){
JLabel holder2 = new JLabel();
holder2.setText(para[j]);
myLabel.add(holder2);
p3.add(holder2);
}
here is my removing style.this in actionListener method
private int asd = 0;
///// some code
myLabel.get(Numbers.get(asd)).setVisible(false);
Money.remove(Numbers.get(asd));
When i try to remove money in intarraylist the calculation method does not work properly. Because for example if the Numbers array's first element is 5 then the 50 will be removed. And arrayList will be shrinked. After that when Numbers.get(asd) is equal to 23, there will not 23th element in int arraylist. Because its shrinked and has no such 23th element. I hope i can tell my problem well.
Ps: I've tried to use array instead of arraylist. But i can't calculate the average of lefts. Because array doesn't shrink when some element be removed.
I would make a lot of changes to that code. For one, I would try to create one collection of values, so that I don't have to fiddle with making changes to parallel collections, since I know that this would reduce the chance of errors. For something like this, I'd use a JList<Integer> and populate its model, a DefaultListModel<Integer> with integers. I can then easily display this as a Turkish Lira using a NumberFormat currency instance that is set to the Turkish Locale. For example if I create my model like so:
// constants used to populate my model
private static final Integer[] VALUES = { 1, 5, 10, 25, 50, 100, 500, 1000, 2000, 5000, 10000,
20000, 25000, 30000, 40000, 50000, 100000, 200000, 300000, 400000, 500000, 750000,
1000000, 2000000 };
// locale for Turkey used to get its currency
private Locale trLocale = new Locale("tr", "TR");
// currency number formatter for Turkish Lira
private NumberFormat tlFormat = NumberFormat.getCurrencyInstance(trLocale);
// my JList's model
private DefaultListModel<Integer> listModel = new DefaultListModel<>();
// create the JList with its model
private JList<Integer> jList = new JList<>(listModel);
// elsewhere in my constructor
// populate my list model with the array values
for (Integer value : VALUES) {
listModel.addElement(value);
}
// set my JList's renderer to render the numbers as Turkish Lira
jList.setCellRenderer(new MyCellRenderer());
// add my list to a JScrollPane and set how many rows are visible
jList.setVisibleRowCount(10);
JScrollPane scrollPane = new JScrollPane(jList);
The JList's cell renderer will change the value that it holds, here an Integer, to a String representation as Turkish Lira:
private class MyCellRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
String textValue = tlFormat.format(value); // format the Integer to its currency String
// pass it into the super's renderer
return super.getListCellRendererComponent(list, textValue, index, isSelected, cellHasFocus);
}
}
Then if later I can remove selected values from the list in a button's ActionListener and have it call a method that calculates the average of all items held in the list:
#Override
public void actionPerformed(ActionEvent e) {
List<Integer> selectedValues = jList.getSelectedValuesList();
for (Integer selectedValue : selectedValues) {
listModel.removeElement(selectedValue);
}
// method elsewhere that iterates through the listModel, calculates an average
// and displays it
calculateAndDisplayAverage();
}
It could look like so:
I would recommend a Map: i.e. HashMap<Integer, JLabel> money . Which would guarantee that your two data-sets are in sync.
For the average, Java 8 streams are really handy:
Collection<Integer> amounts = money.keySet();
double average = (double) amounts.stream().mapToInt(i -> i).sum() / amounts.size()

JLabels with JTextFields in LinkedHashMap

I have a program that at one part demands a user to determine the amount of days per week in 40 weeks (def = 5).
The user firstly fills in the amount of days the 40 weeks will have, to then set the days per week.
Now, I have both JLabel (KEY) and JTextfield (VALUE) stored in a LinkedHashMap,
LinkedHashMap<JLabel, JTextField> weeksMap = new LinkedHashMap<JLabel,JTextField>();
for (int i=1; i<=40; i++) {
JLabel weekL = new JLabel("Week "+i);
JTextField weekF = new JTextField(10);
weekF.setText("5");
//SetWeekAction sWA = new SetWeekAction(mainPane, weekL, weekF);
//weekF.addActionListener(sWA);
weeksMap.put((weekL), weekF);
}
and they will be added to the panel after user sets the total amount of days in the certain year.
EDIT - NOTE: the reason for having these two in a HashMap is I cannot create elements on lick, otherwise I could create infinite labels and text fields and I do not wish to work with buttonpressed=true or such. I need both text fields and labels 'prepared' before the 'click' happens.
for (Map.Entry<JLabel, JTextField> entry : weeksMap.entrySet()) {
index++;
weeksPane.add(entry.getKey());
weeksPane.add(entry.getValue());
}
The GUI view
How do I get the text field of for example 'Week 23'? The for loop goes through the List and adds the Objects correctly, but I have no reference to that certain object anymore.
You can use one ArrayList for storing text field and label text
ArrayList<JTextField> weeks = new ArrayList<JTextField>();
for (int i=1; i<=40; i++) {
JTextField weekF = new JTextField(10);
weekF.setName("Week "+i);
weekF.setText("5");
JLabel weekL = new JLabel(weekF.getName());
weekL.setLabelFor(weekF);
weeks.put(weekF);
}
On update event you can invalidate and redraw weeks panel
I can think of one simple solution of making two separate LinkedHashMap one as LinkedHashMap < integer, JLabel> and another as LinkedHashMap
Now in your loop you can add value in both the LinkedHashMap using the int value from loop as key for JLabel and JTextField while storing them in your both LinkedHashMap.
Since both JLabel and JTextField are now attached with the integer value according to the loop number in which they were created you can access them using those integer value.
Hope this can solve your problem.

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.

Get text element inside JList to a variable?

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

how to create TextFields dynamically in j2me?

we are developing Mobile application in j2me.In my application, we are using TextField and some other controls in Form.Here, my problem is i want to dynamically create TextField based on User's Credentials.For Example, If Manager is entered,then i want to create certain TextField(based on Manager Selection) for getting input from the Manager.Otherwise,i just want to create TextField that are less than the Manager TextField.
How to Create TextFields Dynamically...
For example like this...
int userSelection=10;
for(int i=0;i<userSelection;i++)
TextField text=new TextField("Some Name",null);
here, our problem is,
I want to create TextField With Different Name...
Please guide me to get out of this issue...
Create the TextField array and refer from array index.
TextField[] textFields = new TextField[10];
for (int i = 0; i < textFields.length; i++) {
textFields[0] = new TextField(label, text, maxSize, constraint);
}
after you use correct parameters to construct TextField, code might look like
import javax.microedition.lcdui.TextField;
import java.util.Vector;
// ...
Vector newTextFields(int userSelection) {
// neither List nor generics in midp sorry
final int MAX_SIZE = 42;
final Vector list = new Vector();
for(int i=0; i < userSelection; i++) {
list.addElement(new TextField("Name #" + i, null,
MAX_SIZE, TextField.ANY);
}
return list;
}
// ...

Categories

Resources