how to get a component by name in java [duplicate] - java

This question already has answers here:
Get a Swing component by name
(8 answers)
Closed 6 years ago.
here is the edited code with specified method.
String value = obj.validateTextFields(txtFields);
public String validateTextFields(JTextField[] txtField){
String res = "";
for(JTextField txtFields : txtField) {
if(txtFields.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtFields.getName() +" is empty!");
res +=txtFields.getName()+",";
}
}
return res;
value is the names of text fields so how to get the text field by this name.

If you want to associate an object with a String for easy retrieval, one simple way is to use a Map<String, JTextField> with a concrete implementation as a HashMap<String, JTextField>.
Then in your initialization code, you place the components in the map with their associated String using the Map's put(...) method, and later when you want to retrieve it, use the Map's get(...) method.

Related

How can I rewrite null checks with optional in a better way [duplicate]

This question already has an answer here:
Java 8 avoiding null pointer checks using Optional
(1 answer)
Closed 1 year ago.
I am having a small snippet of code. I would like to write it in a better way with fewer nested checks. How can I achieve it?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
Is there any concise way I can rewrite the above piece of code using Java 8?
You can make itemResponse.getItem() class to return Optional<Item> and use the chained map method which will executed only if Optional has value, and if map method return non null value then only final ifPresent(Consumer consumer) is executed
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);

Java strange issue changing string [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've tried searching for this, but then I'm not sure when how to describe it.
I have a method that formats some data from a hashmap to go into a mySQL table:
private String valuesList() {
String valuesList = "";
HashMap<String,String> data = getData();
for(Map.Entry<String, String> entry : data.entrySet()) {
String value=entry.getValue();
valuesList+="'"+value+"',";
}
valuesList = valuesList.substring(0, valuesList.length() - 1);
return valuesList;
}
Most of the time that works fine, but in some cases one of the values has an apostrophe in, which leads to an output like this:
'4577314','18-02-2017','null','4566974','null','Overseas Domestic Workers' Rights Bill','1124','null'
Note the 'Overseas Domestic Workers' Rights Bill' bit at the end. I thought that would be easy to fix by changing
valuesList+="'"+entry.getValue()+"',";
to
valuesList+="'"+entry.getValue().replace("'","")+"',";
but the method now throws a null pointer exception at that line. In fact any kind of change to that string such as .trim() does the same, throwing a null.
I'm completely stumped now
You can escape quotes from value like this
value = value.replaceAll("'","''");

Don't get compilation error when using three dots notation for parameters [duplicate]

This question already has answers here:
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 6 years ago.
I want to generate CSV files. I have a generateCSV method which takes a filename as parameters and a bunch of entries
private static void generateCSV(String pFilename, String... pColumns) {
try(FileWriter fileWriter = new FileWriter(pFilename,true)) {
for(String column : pColumns) {
fileWriter.append(column);
fileWriter.append(";");
}
fileWriter.append("\n");
fileWriter.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
When calling the method with generateCSV("myfile.csv") without the entries i don't get any compilation error. I thought that this notation implies passing 1-N parameters from this object type. No ?
It is fine to only pass a single parameter to this method: pColumns will then be a zero-length array.
If you want to require that at least one column name is passed, add an additional parameter:
private static void generateCSV(
String pFilename, String firstColumn, String... otherColumns) {
You then need to handle the first column specially:
fileWriter.append(firstColumn);
fileWriter.append(";");
for(String column : otherColumns) {
fileWriter.append(column);
fileWriter.append(";");
}
which is slightly less convenient than being able to treat them as a single array; but you just need to weigh that against the benefits of compile-time enforcement of having at least one column.

To use a string value as a variable name [duplicate]

This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 6 years ago.
Is it possible to use String as a variable name.. like in this example -
String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");
if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
What you can do is by associating (mapping) those values to the Music object. Here is example:
Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));
if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
You can't do this in Java, but you can almost do it using a map.
Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);
if(map.get(musicPlaying).stillPlaying) {
// happy listening
}
No, this is not supported in Java.
stillPlaying doesn't exist as a method (or variable) on String.
As the comment suggests below, it probably is doable through some reflection, however to quote another comment...
You can do all kinds of stupid tricks with reflection. But you're
basically breaking the "warranty void if removed" sticker on the class
the instant you do it.
No. But you might want to look into using a Map instead.
I used a switch case.
Switch (string)
{
case "string1":
string1();
break;
case "string2":
string2();
break;
}

How to find an object in arraylist by one of it's element and print it? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am developing a console application where I can register items. Each item has 3 properties serial number, model, year.
I have 3 classes Laptop, Laptops(arraylist) and Office to run the application.
So far I have managed to find the object itself by index number, but i need to list all objects with the property typed in.
This is how I ask user to choose the option
Laptops inHouse = new Laptops();
model = Console.askModel("Enter Model : ");
inHouse.findModel(model);
break;
That is the find method in Laptops class
public void findModel(String aModel)
{
int arraySize = laptops.size();
for(int i=0; i<arraySize; i++) {
if (laptops.get(i).getModel() == aModel) {
System.out.println(laptops.get(i));
}
}
}
this is the askModel method in Console class.
public static String askModel(String aModel)
{
System.out.println(aModel);
String model = askString("Enter the model: ");
return model;
}
Additionally, I am quite new to java, I understand the concept but still struggling on many thing so If I forgot to post a code which is needed to solve the problem I am sorry in advnace.
findModel is fine except for your String comparison which checks for object equality instead of String equality, change the comparison to:
if (laptops.get(i).getModel().equals(aModel))
For non-primitives, equality tests using == check if the object is literally identical (that it's the same instance), whereas String.equals will compare the actual String value.
You might want a HashMap instead of an ArrayList:
import java.util.HashMap
public class Laptops{
Map<String, Laptop> laptops = new HashMap<String, Laptop>();
//alternatively if java 7, do "= new HashMap<>();" instead
public Laptop findModel(Laptop aModel){
Laptop theModel = laptops.get(aModel);
return theModel;
}
To put the models in, you'll use the put method of HashMap:
public void addAModel(String modelName, Laptop aModel){
laptops.put(modelName, aModel);
}
This way if you know a model's name (a String), it will return you the Laptop object you're after.

Categories