Create Swing Components in a loop and access them - java

I need to read a configuration file and put the data (it consists of key-value-pairs) into some textFields I have to create dynamically in a JFrame.
After that I want to modify the textFields and save the changes to the file again.
What I have so far:
FileConfiguration fileConfig = new PropertiesConfiguration(new File("xesfile.properties"));
Iterator<String> keys = fileConfig.getKeys();
while (keys.hasNext()) {
String singleKey = keys.next();
//for the case that a key has multiple values
if (fileConfig.getProperty(singleKey).getClass().equals(ArrayList.class)) {
ArrayList<String> blaArray = (ArrayList<String>) fileConfig.getProperty(singleKey);
for (int i = 0; i < blaArray.size(); i++) {
this.keyLabel = new JLabel(this.nameKeyLabel + this.count);
this.entityLabel = new JLabel(this.nameEntityLabel + this.count);
this.keyTextField = new JTextField();
this.keyTextField.setName(this.nameKeyTextField + this.count);
this.keyTextField.setText(singleKey);
this.entityTextField = new JTextField();
this.entityTextField.setName(this.nameEntityTextField + this.count);
this.entityTextField.setText(blaArray.get(i));
this.count++;
this.configFrame.add(this.keyLabel);
this.configFrame.add(this.keyTextField);
this.configFrame.add(this.entityLabel);
this.configFrame.add(this.entityTextField);
this.configFrame.revalidate();
this.configFrame.repaint();
this.configFrame.pack();
}
//for the case a key has a single value
} else {
this.keyLabel = new JLabel(this.nameKeyLabel + this.count);
this.entityLabel = new JLabel(this.nameEntityLabel + this.count);
this.keyTextField = new JTextField();
this.keyTextField.setName(this.nameKeyTextField + this.count);
this.keyTextField.setText(singleKey);
this.entityTextField = new JTextField();
this.entityTextField.setName(this.nameEntityTextField + this.count);
this.entityTextField.setText((String) fileConfig.getProperty(singleKey));
this.count++;
this.configFrame.add(this.keyLabel);
this.configFrame.add(this.keyTextField);
this.configFrame.add(this.entityLabel);
this.configFrame.add(this.entityTextField);
this.configFrame.revalidate();
this.configFrame.repaint();
this.configFrame.pack();
}
}
As you see the TextFields are created again and again in every pass of the while-loop. But I need to access the textFields I created in the first pass of the loop for the example.
Thought if I would access the TextFields with getName() they would be returned, but that's not the case.
Can anyone help me out?

Store your TextField in a Map with key as name and value as TextField object itself. You could later access it using:
TextField textField = map.get("myField");

This is so simple
// In loop
1) Create the component.
2) Add it to an Generic ArrayList
3) You can also attach an actionListener to the component in loop if you want.
// Out of loop
4) Iterate the ArrayList and access the desire component.

Related

Is there way to keep queue data in memory in java GUI program

I'm writing a program to simulate a waiting queue for campus students this program users a linked list to do the queue and I used a button click event to execute the code.
It works only once every time add it only holds one student I think it because the list gets cleared after the button click event. I just want know is there a way to keep the list active till I terminate the main program.
My Code Below:
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
Queue stdQue = new LinkedList(); <-- Create the queue
String stName = addStdName.getText();
int sId;
int stdQuality;
if(!stName.isEmpty()){
// Generate a random number as Id
RanNum tempId = new RanNum();
sId = tempId.genNum();
// Generate a random number as a quality number to be matched later with the apartment
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
The above code functions with out error I just want to find out to keep the queue live until the user terminate the main program.
I think this can be archived in a CLI program using a while loop but this is a GUI program I don;t know how to do that in a this format.
UPDATE
I made changes according to #learninloop when I do that I get an error "Cannot Find Symbol:method addStd1ActionPerformed(evt)". Also like to inform you that I'm using NetBeans 8.0.2 as my java IDE.
addStd1.setText("Add Student");
addStd1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {addStd1ActionPerformed(evt);}
And the changed main code is below:
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
}
UPDATE
I changed the code and put my linked list in to a class and moved it totally out of the button click event. So the new code as follows,
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
if (!stdQue.isEmpty()){
for(Object all : stdQue){
lstQue.setText(all.toString());
}
}
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue1.stdQue.add(sId);
stdQue1.stdQue.add(stdQuality);
stdQue1.stdQue.add(stName);
Object atTop = stdQue1.stdQue.element().toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
Now as you see in my class I want to display what ever in the queue in a text area named queLst as you can see I have used a for loop to do it but my issue is it's not displaying the list in the text area and the other thing when it's placed inside the button click event it works but adds what ever I enter at that point can some show me a way or give an idea to how to archive this.
UPDATE
I did some changes to the above code now it working but I don't if I'm doing this wrong one things is when I retrieve the inserted data from the queue it not what I expect to see and I think still my queue linked list is not getting populated.
Can some one please have a look at my code and tell me what I'm doing is write or wrong.
class stdQueCls{
Queue<stdDetailGroup> stdQue;
public stdQueCls(){
stdQue = new LinkedList<stdDetailGroup>();
//lstQue.setText(stdQue.toString());
}
}
class stdDetailGroup{
String stdId;
String stQuality;
String stdName;
public stdDetailGroup(String a, String b, String c){
stdId = a;
stQuality = b;
stdName = c;
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int stdQualityInt;
int sIdInt;
String sId;
String stdQuality;
RanNum tempId = new RanNum();
sIdInt = tempId.genNum();
sId = Integer.toString(sIdInt);
RanNum tempQuality = new RanNum();
stdQualityInt = tempQuality.genNum();
stdQuality = Integer.toString(stdQualityInt);
stdDetailGroup stdDetailsAdd = new stdDetailGroup(sId, stdQuality, stName);
stdQue1.stdQue.add(stdDetailsAdd);
Object atTop = stdQue1.stdQue.toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
private void shwQue1ActionPerformed(java.awt.event.ActionEvent evt) {
stdQueCls stdQue2 = new stdQueCls();
lstQue.setText(stdQue2.stdQue.toString());
}
As you are creating the linkedlist object stdQue inside the action performed event of button, the object is getting created and reinitialized every time the button is clicked. To make the data persistent, please take the object creation outside the button click event.
Assuming the class name as StudentManager, you can create the object inside the constructor:
class StudentManager {
Queue stdQue;
public StudentManager() {
stdQue = new LinkedList(); <-- Create the queue
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt)
{
.
.
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
.
.
}
}

Printing all content of a JList as output

I have a JList in my GUI, which uses an ArrayList as data:
ArrayList Cruise = new ArrayList();
Cruise.add("Scottish to Greek Waters");
Cruise.add("Greek to Scottish Waters");
JScrollPane scrollPane = new JScrollPane();
CruiseList = new JList(Cruise.toArray());
CruiseList.setPreferredSize(new Dimension(200, 200));
scrollPane.setViewportView(CruiseList);
CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CruiseList.setSelectedIndex(0);
CruiseList.setVisibleRowCount(6);
listPanel.add(scrollPane);
Frame1.setVisible(true);
I have a button - List all Cruises, which once clicked on should display this as output:
"Scottish to Greek Waters"
"Greek to Scottish Waters"
However, upon clicking the button, it only displays the selected list option as output.
This is what I have so far:
listallCruises.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String AllCruises = CruiseList.getSelectedValue().toString();
System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
}
});
How do I print out all element in the list upon clicking the button?
You are outputting just the selected value because that's the method you are calling, getSelectedValue().
To display ALL the values, you have to get the model and iterate through the values, like so:
int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);

Using a textbox for input for a JList

Okay I know this has got to be something very simple I am trying to do but I am pulling my hair out trying to figure it out. I have a GUI with three text boxes and one JList I am trying to add to the list. Here is my addButton code below:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement(firstText + " : " + lastText + " : " + emailText);
custList.setModel(model);
}
I can add text to my list but if I try to add a second line of text it just overwrites the first one. How can I just add to the list with out overwriting the other?
I can add text to my jlist box but if I try to add a second line of
text it just overwrites the first one.
Because, each time your are adding a text to JList you are creating new DefaultListModel and setting that model to the JList which removes the already added texts in JList. To overcome this problem create the object of DefaultListModel once outside the addButtonActionPerformed method.Also set the model for JList once. Your code should be something like this:
DefaultListModel<String> model = new DefaultListModel<>();
private void someMethod() //call this method in your constructor or method where you have initialized your GUI
{
custList.setModel(model);
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
model.addElement(firstText + " : " + lastText + " : " + emailText);
}
By default a JList will use a DefaultListModel.
Cast the JList model via list.getModel(), and just remove your setModel method call which resets the list data.

Adding multiple values form database into RichList Blackberry

I am using Blackberry Plug-in and i am using Rich Lists of blackberry.
I want to make lists appear the same number of times as there are entries in the database table.
I m using the below code but it shows only one name in list view.
I need to show all the entries in database into list view...Kindly help me..
I have already used list.add(); inside the for loop but it is showing Exception: java.lang.IllegalStateException: Field added to a manager while it is already parented.
public static void richlistshow(){
String name = null;
list = new RichList(mainManager, true, 2, 0);
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
for (int c = 0; c < target_list.size();c++){
City tar_city = new City();
tar_city = (City)target_list.elementAt(c);
name = tar_city.get_city_name().toString();
}
//adding lists to the screen
list.add(new Object[] {delete,name,"time-date"});
}
You didn't posted full codes you are working with. But following code may help you to get rid of IllegalStateException. You were adding same BitmapField instance for every list entries, which caused the exception.
public static void richlistshow() {
final Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
list = new RichList(mainManager, true, 2, 0);
for (int c = 0; c < target_list.size(); c++) {
// create a new BitmapField for every entry.
// An UI Field can't have more than one parent.
final BitmapField delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
City tar_city = (City) target_list.elementAt(c);
final String name = tar_city.get_city_name().toString();
// add to list
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
list.add(new Object[] { delete, name, "time-date" });
}
});
}
}

Arraylist retrieved from populated hashmap keeps returning an empty arraylist

I have a hashmap and I am inserting an arraylist as the value in a while loop. During an iteration, if the hashmap already contains a key, I want to retreive the arraylist already stored, append new data to it and put it back into the hashmap.
The issue I have now is when I check if a hashmap contains a value and it does, the arraylist being returned is of size 0 as though I never put in anything before.
final HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
String status = "";
String channel = "";
while (daily.next()) {
while (avrg.next())
if (avrg.getString(1).equals(daily.getString(1)) && avrg.getString(2).equals(daily.getString(2))) {
final Object pstmnt = null;
final Object pstmnt2 = null;
final float thresholdValue = calcThreshold(pstmnt, pstmnt2, daily.getString(1));
channel = daily.getString("client_name");
if (daily.getFloat(3) > avrg.getFloat(3) + thresholdValue * avrg.getFloat(3)) {
status = "HIGHER";
}
else if (daily.getFloat(3) < avrg.getFloat(3) - thresholdValue * avrg.getFloat(3)) {
status = "LOWER";
}
else {
status = "Normal";
}
final PrintStream out;
out.println(channel);
out.println(thresholdValue);
out.println(status);
if (map.containsKey(channel)) {
out.println("map contained key");
final ArrayList<String> temp = new ArrayList<String>();
temp.addAll(map.get(channel));
out.println("previous size: " + temp.size());
temp.add(daily.getString("event"));
temp.add(Float.toString(daily.getFloat(3)));
temp.add(Float.toString(avrg.getFloat(3)));
temp.add(Float.toString(thresholdValue * 100));
temp.add(status);
out.println("current size: " + temp.size());
map.put(channel, temp);
out.println("array added to map");
temp.clear();
System.out.println("done");
}
else {
final ArrayList<String> temp = new ArrayList<String>();
out.println("new key created");
temp.add(daily.getString("event"));
temp.add(Float.toString(daily.getFloat(3)));
temp.add(Float.toString(avrg.getFloat(3)));
temp.add(Float.toString(thresholdValue * 100));
temp.add(status);
System.out.println(temp.size());
map.put(channel, temp);
System.out.println("array added to map");
}
}
avrg.beforeFirst();
}
I am really not sure why this is happening. Any help would be appreciated!
The problem is right here:
map.put(channel, temp);
out.println("array added to map");
temp.clear();
temp.clear() clears the same list that you've just added to the map. Since temp is about to go out of scope, that statement serves no useful purpose and can be removed.
Let me start by saying that #aix has the correct answer, but you should rewrite you code to get rid of all the duplication. The if block starting from
if (map.containsKey(channel))
can be simplified to the following.
ArrayList<String> temp = map.get(channel);
if (temp == null) {
out.println("new key created");
ArrayList<String> temp = new ArrayList<String>();
map.put(channel, temp);
}
temp.add(daily.getString("event"));
temp.add(Float.toString(daily.getFloat(3)));
temp.add(Float.toString(avrg.getFloat(3)));
temp.add(Float.toString(thresholdValue * 100));
temp.add(status);
There is no need to create a new list and copy every time you add to it.

Categories