Modifying an item in an arraylist coding issue - java

I am trying to change values of items in my arraylist. I can't seem to get this working. I am at a loss as to how to really ask this question. The code is quite extensive (or at least it is in my book) so I can't really show all of it. However if I know the current index, how can I make it change the ItemName?
currentIndex.setItemName(newItemName);
CurrentIndex is an int that tells me which index I am at, ItemName is a string that is in my arraylist. Should I be getting the ItemName prior to trying to set it? Something like this
InventoryItem.getItemName();
currentIndex.setItemName(newItemName);
This also does not work.
Edit: I was asked to show more code. Here is the panel that pops up in my action listener
modifyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JTextField xField = new JTextField(15);
JTextField yField = new JTextField(15);
JTextField zField = new JTextField(15);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Item Name:"));
myPanel.add(xField);
myPanel.add(Box.createVerticalStrut(15)); // a spacer
myPanel.add(new JLabel("Number in inventory:"));
myPanel.add(yField);
myPanel.add(Box.createVerticalStrut(15)); // a spacer
myPanel.add(new JLabel("Unit Price:"));
myPanel.add(zField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter data into all boxes", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newAmount = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
inventory.get(currentIndex).setItemName(newItemName);
inventory.get(currentIndex).setInStock(newAmount);
inventory.get(currentIndex).setUnitPrice(newPrice);
}
}
}
);

I'm not sure what your ArrayList is name so I'll just call it arrayList.
Try
arrayList.get(currentIndex).setItemName(newItemName);
arrayList.get(currentIndex) calls the element from your list at the current index
That allows you to use .setItemName(newItemName) to change the name of the object.

ìnt doesn't have a method setItemName (or any method at all, since it's a primitive, not an object).
Try yourArrayList.get(currentIndex).setItemName(newItemName);
It calls setItemName on the desired element of the list.
EDIT: to fix your new problem, replace String newItemName = String.valueOf(xField); with
String newItemName = xField.getText();
I believe this is what you want to do.

list.set(index, newItemName)
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#set(int, E)

Check out this code that accomplishes what I think you are trying to do.
public class Test {
public static void main(String args[]){
ArrayList<Employee> myArrayList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setName("Juan");
myArrayList.add(e1);
myArrayList.get(0).setName("Jhon");
System.out.println(myArrayList.get(0).getName());
}
}
class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Related

How to call the JTable function again

I'm trying to make a GUI interface using java swing that is able to add users to a text file that I treat as a database. The GUI interface has a JTable which pulls the existing items in the text file and displays it initially. Once I go to add a new item, it gets updated on the text file but not on the JTable. This is mainly because I only call the JTable once the way I set up my code. I'm wondering how I can call the JTable multiple times or make a button for it to call a refresh of the table and display the newly added items alongside the old items.
I want it to be able to either call the refresh of the table in the updateList function or once the viewButton is pressed which triggers an else if statement which can do that in the actionPerformed function.
Here is my code:
class UserManager extends JFrame implements ActionListener {
private JTextField firstNameField, lastNameField, salaryField;
private JButton addButton, removeButton, viewButton, sortButton, getButton;
private JList<Employee> userList;
private ArrayList<Employee> users;
public UserManager() {
setTitle("Employee Manager");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
firstNameField = new JTextField(20);
lastNameField = new JTextField(20);
salaryField = new JTextField(20);
addButton = new JButton("Add");
addButton.addActionListener(this);
removeButton = new JButton("Remove");
removeButton.addActionListener(this);
viewButton = new JButton("Refresh List"); // POTENTIAL BUTTON TO REFRESH JTABLE?
viewButton.addActionListener(this);
sortButton = new JButton("Sort List");
sortButton.addActionListener(this);
// Pulling data from text file database
ArrayList<ArrayList<String>> databaseData = ReadFile();
users = new ArrayList<Employee>();
// Adding existing databaseData to users
for (int i = 0; i < databaseData.size(); i++) {
Employee user = new Employee(databaseData.get(i).get(0), databaseData.get(i).get(1), Integer.valueOf(databaseData.get(i).get(2)));
users.add(user);
}
userList = new JList<Employee>(users.toArray(new Employee[0]));
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel firstNamePanel = new JPanel();
firstNamePanel.add(new JLabel("First Name:"));
firstNamePanel.add(firstNameField);
JPanel lastNamePanel = new JPanel();
lastNamePanel.add(new JLabel("Last Name:"));
lastNamePanel.add(lastNameField);
JPanel salaryPanel = new JPanel();
salaryPanel.add(new JLabel("Salary:"));
salaryPanel.add(salaryField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
buttonPanel.add(viewButton);
buttonPanel.add(sortButton);
// Converting 2D arraylist to normal 2D array for JTable
String[][] data = databaseData.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);
// Initializing column names of JTable
String[] columnNames = { "FName", "LName", "Salary" };
// Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
JTable j = new JTable(data, columnNames);
j.setBounds(1000, 1000, 900, 900);
// adding it to JScrollPane
JScrollPane table = new JScrollPane(j);
JPanel mainPanel = new JPanel(new GridLayout(5, 3));
mainPanel.add(firstNamePanel);
mainPanel.add(lastNamePanel);
mainPanel.add(salaryPanel);
mainPanel.add(buttonPanel);
mainPanel.add(table);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
// "Add" button is clicked
if (e.getSource() == addButton) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
int salary = 0;
try {
salary = Integer.parseInt(salaryField.getText());
}
catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Please enter a valid salary", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Error check to see if full name and age is entered
if (!firstName.equals("") && !lastName.equals("")) {
Employee user = new Employee(firstName, lastName, salary);
users.add(user);
updateList();
firstNameField.setText("");
lastNameField.setText("");
salaryField.setText("");
}
else {
JOptionPane.showMessageDialog(this, "Please enter a valid full name", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// POTENTIAL BUTTON THAT REFRESHES JTABLE?
else if (e.getSource() == viewButton) {
}
}
// Updates the list after a CRUD operation is called
private void updateList() {
userList.setListData(users.toArray(new Employee[0]));
try {
FileWriter fw = new FileWriter("db.txt", false);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter pw = new PrintWriter(bw);
// Loop through each student and write to the text file
for (int i = 0; i < users.size(); i++) {
fw.write(toString(users.get(i).getFirstName(), users.get(i).getLastName(), users.get(i).getSalary()));
}
fw.close();
// CALL A REFRESH FOR THE TABLE HERE??
}
catch (IOException io) {
}
}
// Combing multiple string and ints into a string
public String toString(String firstName, String lastName, int salary) {
return firstName + ", " + lastName + ", " + salary + "\n";
}
// Reading database
public static ArrayList<ArrayList<String>> ReadFile() {
try {
// Choose grades.txt file to look at
File myObj = new File("db.txt");
// Create scanner object
Scanner myReader = new Scanner(myObj);
// Create 2d list array to hold all the single list arrays of single information
ArrayList<ArrayList<String>> combinedArr = new ArrayList<ArrayList<String>>();
// While the file reader is still reading lines in the text
while (myReader.hasNextLine()) {
// Read strings of text in txt file
String data = myReader.nextLine();
// Get first and last name from a string
ArrayList<String> temp = GetName(data);
// Add the person and their salary to the combined array that holds everyones
combinedArr.add(temp);
}
// Close file once there are no more lines to read
myReader.close();
return combinedArr;
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Return invalid list string with nothing if error
ArrayList<ArrayList<String>> Invalid = new ArrayList<ArrayList<String>>();
return Invalid;
}
// Parses name in db
public static ArrayList<String> GetName(String data) {
String first = "";
String last = "";
String sal = "";
// System.out.println(data[0])
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == ',') {
// Start from 2 indexes after the first occurance of the comma
for (int j = i+2; j < data.length(); j++) {
if (data.charAt(j) == ',') {
for (int n = j+2; n < data.length(); n++) {
sal += data.charAt(n);
}
break;
}
last += data.charAt(j);
}
break;
}
first += data.charAt(i);
}
// Initializing package array to send all values
ArrayList<String> arr = new ArrayList<String>();
arr.add(first);
arr.add(last);
arr.add(sal);
return arr;
}
public static void main(String[] args) {
UserManager frame = new UserManager();
frame.setVisible(true);
}
}
class Employee {
// Initalizing variables
private String firstName;
private String lastName;
private int salary;
// Assigning variables
public Employee(String firstName, String lastName, int salary) {
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
// return first name
public String getFirstName() {
return firstName;
}
// return last name
public String getLastName() {
return lastName;
}
// return salary
public int getSalary() {
return salary;
}
}
Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
You don't refresh the table. The data for all Swing components is contained in a "model". You change the data in the model. When changes to the model are made the table is repainted to reflect the change.
So you could either:
create a new DefaultTableModel (which is unnecessary)
update the existing DefaultTableModel, by using the addRow(...) method to update the model every time you write a new item to your file.
Instead of using code like:
JTable j = new JTable(data, columnNames);
You can use:
model = new DefaultTableModel(data, columnNames)
table = new JTable(model)
Now you can access the DefaultTableModel any time you need to by creating an instance variable in your class or by using the table.getModel() method.
Usually lists and tables are updated through their models. They represent the information shown to the user. You can try this.
Create in your class a new field. Use this field when initializing the table in your constructor.
private JTable userTable;
In your update function, try this:
DefaultTableModel model = new DefaultTableModel();
users = // fetch here for your users
for (int i = 0, i < user.length, i++)
model.addRow(users[i]);
}
// finally set new model in your table
userTable.setModel(model);
userTable.doLayout();

Remove label before I click in java

ı have problem about delete a empty string values like we can see in picture,
in the first time if here is empty he give a error but after that even we write some strings in that blank,its still giving the same error how can ı delete this label before the sending again How can ı fix that problem ı tried some codes but nothing worked well please help about that
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class ui {
public static void main(String[] args) {
uiVision();
}
public static void uiVision() {
ImageIcon eyes = new ImageIcon("a.png");
Globals.jf.setTitle("Deneme Uygulamasi");
Globals.jf.setLocation(100,200);
JLabel label1,label2,label3;
Globals.jf.getContentPane().setLayout(new FlowLayout());
JTextField isim = new JTextField(20);
JTextField soyisim = new JTextField(20);
JTextField pasaport = new JTextField(20);
JTextField mail = new JTextField(20);
JPasswordField passwordField = new JPasswordField(10);
JPasswordField passwordField2 = new JPasswordField(10);
JButton buton1 = new JButton("Send");
JButton buton2 = new JButton(eyes);
JButton buton3 = new JButton(eyes);
JButton buton4 = new JButton("!");
label1 = new JLabel("Name:");// -8
label2 = new JLabel("Surname:");// -9
label3 = new JLabel("Passaport-ID:");//+ 10
JLabel label4 = new JLabel("Mail:");// +10
JLabel label5 = new JLabel("Password:");//+10
JLabel label6 = new JLabel("Re-Password:");// +20
buton1.setBounds(170,400,150,30);
buton2.setBounds(320,190,50,30);
buton3.setBounds(320,230,50,30);
buton4.setBounds(370,230,50,30);
isim.setBounds(170,30,150,30);
soyisim.setBounds(170,70,150,30);
pasaport.setBounds(170,110,150,30);
mail.setBounds(170,150,150,30);
passwordField.setBounds(170,190,150,30);
passwordField2.setBounds(170,230,150,30);
label1.setBounds(125,30,150,30);
label2.setBounds(106,70,150,30);
label3.setBounds(90,110,150,30);
label4.setBounds(132,150,150,30);
label5.setBounds(105,190,150,30);
label6.setBounds(91,230,150,30);
Globals.jf.add(buton1);Globals.jf.add(buton2);Globals.jf.add(buton3);
Globals.jf.add(label1);Globals.jf.add(label2);Globals.jf.add(label3);Globals.jf.add(label4); Globals.jf.add(label5);Globals.jf.add(label6);
Globals.jf.add(isim);Globals.jf.add(soyisim);Globals.jf.add(pasaport);Globals.jf.add(mail);Globals.jf.add(passwordField);Globals.jf.add(passwordField2);
Globals.jf.setSize(1000,500);
buton2.addActionListener(l -> {
if ( passwordField.getEchoChar() != '\u0000' ) {
passwordField.setEchoChar('\u0000');
} else {
passwordField.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}
});
buton3.addActionListener(l -> {
if ( passwordField2.getEchoChar() != '\u0000' ) {
passwordField2.setEchoChar('\u0000');
} else {
passwordField2.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}
});
buton1.addActionListener(e -> {
checkEmpty(isim.getText(),label1.getText(),label1);
checkEmpty(soyisim.getText(),label2.getText(),label2);
checkEmpty(pasaport.getText(),label3.getText(),label3);
checkEmpty(mail.getText(),label4.getText(),label4);
ExitWhenLoopEnd();
Globals.globalInt = 0;
System.out.println(passwordField.getPassword());
System.out.println(passwordField2.getPassword());
Globals.clickCount++;
});
Globals.jf.setLayout(null);
Globals.jf.setVisible(true);
Globals.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void checkEmpty(String value,String label,JLabel labelname) {
Integer syc = Integer.valueOf(0);
if(value != null && !value.trim().isEmpty()) {
if(Globals.globalInt != 4) {
Globals.globalInt++;
}
syc = 1;
}
else {
CreateEmptyMessageError(label,labelname,Globals.jf);
syc = -1;
}
System.out.println(syc);
}
public static void CreateEmptyMessageError(String labelError,JLabel label,JFrame jf) {
Globals.labelx = new JLabel(labelError.split(":")[0]+" is empty!");
Globals.labelx.setBounds(label.getBounds().x+250,label.getBounds().y,label.getWidth(),label.getHeight());
Globals.labelx.setForeground(Color.RED);
jf.add(Globals.labelx);
jf.revalidate();
jf.repaint();
}
public class Globals {
public static int globalInt = 0;
public static JLabel labelx = null;
public static JFrame jf = new JFrame();
public static int clickCount = 0;
public static int lastVal = 0;
public static int syc = 0;
}
public static void ExitWhenLoopEnd() {
if(Globals.globalInt == 4) {
System.exit(0);
}
}
}
Your problem is that you're creating a new JLabel and adding it to the GUI each time CreateEmptyMessageError(...) is called, and by doing this, you have no reference to this object, and no way to change its state.
The solution is to not do this, to instead create the error message label when you create the GUI itself, assign it to an instance field, and in that method above to not create a new JLabel object but rather to set the text of the existing object, one that shows a warning if the JTextField is empty, and one that sets the JLabel text to the empty String, "", if the JTextField has text.
Also,
As Progman has suggested in comments, avoid the use of static fields and methods unless the use suggests that these should be used, and this isn't the case here. Instead, use private instance fields and methods. This will make your code easier to mock/test/extend and re-use, this reduces potential for hard to identify bugs by reducing your code's cyclomatic complexity and coupling.
Avoid the use of null layouts and setBounds(...) and instead learn and use the layout managers.
Learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Give your fields names that describe what they represent, making your code self-commenting and easier to understand.

How to add continuously data from JTextField to JTable

I want to add continuously data from JTextFields to a Jtable.
When I click add button, the text from the JTextFields have to be inserted in the Jtable.
This code generates only one row when I click the add button.
I want the row to be added to the previous rows inserted.
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
Do I need to add an EventHandler to my table? Thank you. Please help me with my assignment.
Move this part:
DefaultTableModel model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
to your constructor and define model as an instance member. Don't create table model for each button click. Below part is enough for actionPerformed.
public void actionPerformed(ActionEvent arg0) {
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
Edit:
If you share your full code, I can tell you where to put the above parts. But for now, below example code can guide you.
public class TableClass {
DefaultTableModel model;
public TableClass() {
model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
JButton addButton = JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
})
}
}

How to call a variable from a keylistener to a different class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to build a payroll system and I'm having trouble using the variable in and action listener to my condition, somehow it cant see the variable I've declared in actionlistener, I've tried using calling it in a class but wasn't sure what I did wrong cause it didn't work. Thank you in advance!
Here is my code:
import java.io.File; import java.io.FileNotFoundException; import
java.util.ArrayList; import java.util.List; import
java.util.Scanner; import javax.swing.*; import java.awt.*; import
java.awt.event.*;
#SuppressWarnings("serial")
public class kapoy extends JFrame{
public static JTextField text1;
public static JTextField text2;
public JLabel label1;
public JLabel label2;
public JPanel panel1;
public JPanel panel2;
public JPanel panel3;
public JPanel panel4;
public kapoy() {
text1 = new JTextField();
text1.setPreferredSize(new Dimension(50,20));
text2 = new JTextField();
text2.setPreferredSize(new Dimension(50,20));
label1 = new
JLabel("Inpute Employee ID: ");
label2 = new JLabel("Input workedDays: ");
panel1 = new JPanel();
panel1.setLocation(0,0);
panel1.setSize(300,40);
panel1.setBackground(Color.blue);
panel1.add(label1);
panel1.add(text1);
add(panel1);
panel2 = new JPanel();
panel2.setLocation(0,40);
panel2.setSize(300,40);
panel2.setBackground(Color.red);
panel2.add(label2);
panel2.add(text2);
add(panel2);
panel3 = new JPanel();
panel3.setLocation(0,80);
panel3.setSize(400,200);
panel3.setBackground(Color.green);
add(panel3);
panel4 = new JPanel();
panel4.setLocation(300,0);
panel4.setSize(100,80);
panel4.setBackground(Color.yellow);
add(panel4);
setSize(410,300);
setLayout(null);
setTitle("Pay Roll by Migz"); }
public static void main(String[] args) {
kapoy cn = new kapoy(); cn.setVisible(true);
text1.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent e)
{
try {
/**Cant use this-->**/int x = Integer.parseInt(text1.getText());
} catch (NumberFormatException nfe) {
text1.setText("");
}
} });
try {
File f = new File("D:/Users/DAVID Family/Desktop/Employees.txt");
Scanner sc = new Scanner(f);
List<Employee> people = new ArrayList<Employee>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(" ");
int Id = Integer.parseInt(details[0]);
String name = details[1];
int rate = Integer.parseInt(details[2]);
Employee p = new Employee(Id, name, rate);
/**in here-->**/if (x == Id){
people.add(p);
}
}
for(Employee p: people){
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Employee{
private int Id;
private String name;
private int rate;
public Employee(int Id, String name, int rate){
this.Id = Id;
this.setName(name);
this.rate = rate;
}
public int getId() {
return Id; }
public void setId(int Id)
{
this.Id = Id; }
/public void setName(String
name) {
this.name = name; }
public String getName() {
return name; }
public int getrate() {
return rate; }
public void setrate(int rate) {
this.rate = rate; }
public String toString(){
return this.Id + " " + this.name + " " + this.rate; } }
The variable you have defined int x = Integer.parseInt(text1.getText()); is the local variable of method keyReleased as you have defined it inside the method, so the scope of this variable will always be within that method only.
It means you will only be able to use this variable inside method only, not outside it.
If you want to use it in your class, i.e. outside that method, then you should try with some instance variable.
Check this link
Don't use KeyListeners to modify the state of fields, this could cause concurrent modification exceptions, the underlying Document could be modified before your KeyListener is notified and doesn't take into account what would happen in the user pastes text into your field.
Instead, make use of DocumentFilter if you want to restrict what is entered into the field in real time and/or a DocumentListener if you want to be notified when changes occur to the field's Document
Take a look at Implementing a Document Filter, DocumentFilter Examples and Listening for Changes on a Document for more details
You also need to understand that you are operating within in a event driven environment. This means that user actions can occur at any time and in any order. The only thing you can do is wait until some event occurs and respond to.
This means that something like...
kapoy cn = new kapoy();
cn.setVisible(true);
int x = -1;
text1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
try {
x = Integer.parseInt(text1.getText());
} catch (NumberFormatException nfe) {
text1.setText("");
}
}
});
try {
File f = new File("D:/Users/DAVID Family/Desktop/Employees.txt");
Scanner sc = new Scanner(f);
List<Employee> people = new ArrayList<Employee>();
while (sc.hasNextLine()) {
//...
Employee p = new Employee(Id, name, rate);
if (x == Id) {
people.add(p);
}
}
//...
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Won't work, because by the time your code reaches if (x == Id) { x will still be -1, as the program won't have been able to respond to any key events...
You may, also, want to take a look at How to Use Text Fields and How to Write an Action Listeners

Change background of JLabel in runtime using reflection

I need to change background of JLabels dynamically.
I've 70 JLabels in a class. All JLabels represent some specific items. The items names are same as the variable of JLabel. The Sold Items names are saved in database. If I run a query that will return an array of the sold items. The sold items that are same as the JLabel should change the background. Rest will not change.
I've got the variables of all fields like this:
Field fld[] = BlueLine.class.getDeclaredFields();
for (int i = 0; i < fld.length; i++)
{
System.out.println("Variable Name is : " + fld[i].getName());
}
How can I cast my fld to a JLabel and change background of the JLabel when certain condition meets ? for example:
if(fld[i] == label5){
label5.setBackground.(Color.red);
} // or something like this. ?
Any outline will help.
Currently you're just looking at the fields themselves - you're interested in the values of those fields. For example:
Object value = fld[i].get(target); // Or null for static fields
if (value == label5) {
...
}
Here target is a reference to the object whose fields you want to get the values from. For static fields, just use null, as per the comment.
It's not at all clear that all of this is a good idea, however - problems which can be solved with reflection are often better solved in a different way. We don't really have enough context to advise you of specifics at the moment, but I would recommend that you at least try to think of cleaner designs.
Try it using Jcomponent.putClientProperty() and Jcomponent.getClientProperty().
Steps to follow:
First set the name of the JLabel same as its variable name
Put it as client property of JPanel where JLabel is added
Get it back using client property from JPanel using name of JLabel
Note: you can access it by using Field.getName() as defined in your question.
Sample code :
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.addContainerListener(new ContainerListener() {
#Override
public void componentRemoved(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " removed");
panel.putClientProperty(name, null);
}
}
#Override
public void componentAdded(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " added");
panel.putClientProperty(name, e.getChild());
}
}
});
MyLabels myLabels = new MyLabels();
panel.add(myLabels.getProduct1());
panel.add(myLabels.getProduct2());
panel.add(myLabels.getProduct3());
JButton btn = new JButton("Product1 and Product3 are sold");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] soldItems = new String[] { "Product1", "Product3" };
for (String soldItem : soldItems) {
Object obj = panel.getClientProperty(soldItem);
if (obj instanceof JLabel) {
((JLabel) obj).setForeground(Color.RED);
}
}
}
});
panel.add(btn);
frame.add(panel);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MyLabels.java:
class MyLabels {
private JLabel Product1;
private JLabel Product2;
private JLabel Product3;
public MyLabels() {
Product1 = new JLabel("Product1");
Product1.setName(Product1.getText());
Product2 = new JLabel("Product2");
Product2.setName(Product2.getText());
Product3 = new JLabel("Product3");
Product3.setName(Product3.getText());
}
public JLabel getProduct1() {
return Product1;
}
public void setProduct1(JLabel product1) {
Product1 = product1;
}
public JLabel getProduct2() {
return Product2;
}
public void setProduct2(JLabel product2) {
Product2 = product2;
}
public JLabel getProduct3() {
return Product3;
}
public void setProduct3(JLabel product3) {
Product3 = product3;
}
}

Categories