When I set a variable to JTextArea it has not value - java

I don't understand why a variable work in one part of code but in other part no. is the same variable, is referencied with the same value. this is my code
// Variables
String patologicos="";
String ginecologicos="";
String valuePanel="";
JTextArea ja;
here is built the constructor
public BaseHistorialPanelNoEditable(int typePanel){
// constructor
ja = new JTextArea();
ja.setPreferredSize(new Dimension(900, 280));
setBackground(Layout.pac_background);
ja.setEditable(false);
this.add(ja);
showInformation(typePanel);
}
Method to show some information
public void showInformation(int value){
// getting data from DB
getPatientData();
switch (value) {
case 1:
valuePanel = patologicos;
break;
case 2:
valuePanel = ginecologicos;
break;
default:
break;
}
// show message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
// set a value to text area
ja.setText(valuePanel);
}
Method to get information from database
public void getPatientData(){
Main.readdb.select(
"select * from clinic where no_paciente=" +
Paciente.getPac_no());
if (Main.readdb.getNext()) {
patologicos = Main.readdb.getString("historia_clinic");
ginecologicos = Main.readdb.getString("gineco");
}
this fragment of code show a message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
using the same variable it works.
why when I use the same variable one line after, it doesn't have any value?
ja.setText(valuePanel);
Thanks for your time.

Not sure but just an idea..
When you use setEditable(false).. It might be internal implementation that won't allow to set value..
try this:
ja.setEditable(true);
ja.setText(valuePanel);
ja.setEditable(false);
Hope this make sense..

Related

Showing an Integer tableview in javaFx as a string

I am trying to show a tableview where when the value in the table is a integer like 1 for example I want to display a String. So far I tried to get the cellValue like this:
public void changeView() {
if(intervall.getCellFactory().call(intervall).equals(1)) {
intervall.getCellFactory().call(intervall).setText("Täglich");
}
}
And I am calling the method in my initialize after setting the cellvalue.
public void initializeTable() {
try {
// Ablesen
Statement pStatement = connection.createStatement();
flightList = FXCollections.observableArrayList();
ResultSet myRs = pStatement
.executeQuery("select * from fluglinie where fluggesellschaft =\"" + fluggesellschaft + "\"");
while (myRs.next()) {
flightList.add(new flightRouteAddModel(myRs.getString("startFlughafen"),
myRs.getString("zielFlughafen"), myRs.getString("startDatum"), myRs.getString("flugzeug"),
myRs.getInt("intervall"), myRs.getInt("anzahlEconomy"), myRs.getInt("anzahlBusiness"),
myRs.getFloat("preisEconomy"), myRs.getFloat("preisBusines"), myRs.getFloat("distanz")));
}
} catch (Exception e) {
System.out.println(e);
}
startAirport.setCellValueFactory(new PropertyValueFactory<>("startAirport"));
targetAirport.setCellValueFactory(new PropertyValueFactory<>("targetAirport"));
flightDate.setCellValueFactory(new PropertyValueFactory<>("flightDate"));
airplane.setCellValueFactory(new PropertyValueFactory<>("airPlane"));
intervall.setCellValueFactory(new PropertyValueFactory<>("intervall"));
seatCountEco.setCellValueFactory(new PropertyValueFactory<>("countEconomy"));
seatCountBus.setCellValueFactory(new PropertyValueFactory<>("countBusiness"));
priceEco.setCellValueFactory(new PropertyValueFactory<>("priceEconomy"));
priceBus.setCellValueFactory(new PropertyValueFactory<>("priceBusiness"));
distance.setCellValueFactory(new PropertyValueFactory<>("distance"));
table.setItems(flightList);
changeView();
}
But it is not working can someone maybe take a look at this? I know changing the db would be maybe a better solution but I kinda wanted to try this workaround
The cellFactory returns TableCells. Calling this yourself does not result in a cell that is part of the TableView (or becomes part of it). Any TableCell with a properly impelemented equals method never yields true, if 1 (or any other Integer) is passed.
Assuming you always want to display Täglich instead of 1, the way to go about this is using a custom cellFactory for this column:
intervall.setCellFactory(col -> new TableCell<flightRouteAddModel, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
String text = "";
if (item != null) {
switch(item) {
case 1:
text = "Täglich";
break;
case 7:
text = "Wöchentlich";
break;
default:
text = String.format("Alle %d Tage", item);
break;
}
}
setText(text);
}
});
BTW: Please learn about the java naming conventions. This makes the code easier to read for other people and it should make this more readable even for yourself, since all java APIs (that I know of) use these conventions: Type names start with an uppercase letter.

I am unable to enter logic code to enter pin number in dynamic textfield.Using Selenium Webdriver Java

Trying to enter pin number in dynamic text field. Pin number text field changes every time the website is loaded. Need help to write logic for entering the pin number in 3 text field. There is 4 pin number but I get option to enter pin number in 3 text field.
Screenshot and code reference
As per your posted HTML. you can try with indexes if its same type of field.
Use below code:
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(1)")).sendKeys("your value"); // for first text box
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(2)")).sendKeys("your value"); // for Second text box
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(3)")).sendKeys("your value"); // for third text box
Please change the index in div[class='field-set'] input.input-pin:nth-child(index) as per textbox in page UI position.
UPDATE
If you are not sure which textbox have to accept value then use below logic
public static void main(String[] args) {
// first you need to store your testdata in a collection
Map<String,String> pinCodes = new HashMap<String, String>();
pinCodes.put("pin1", "2");
pinCodes.put("pin2", "3");
pinCodes.put("pin3", "3");
pinCodes.put("pin4", "4");
// you can remove the values as per you need suppose you only want `pin1` `pin2` then remove `pinCodes.put("pin3", "3");` and `pinCodes.put("pin4", "4");` from above code
enterPinCode(pincodes); //call method to enter the values in corresponding text-boxes
}
public void enterPinCode(Map<String,String> pinCodes) {
for (Entry<String, String> entry : pinCodes.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
switch (key) {
case "pin1" :
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(1)")).sendKeys(value);
break;
case "pin2" :
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(2)")).sendKeys(value);
break;
case "pin3" :
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(3)")).sendKeys(value);
break;
case "pin4" :
driver.findElement(By.cssSelector("div[class='field-set'] input.input-pin:nth-child(4)")).sendKeys(value);
break;
default :
System.out.println("pincode textbox key not found");
break;
}
}
}
OR if checkbox are dynamic on webpage then replace below code in switch statement :
switch (key) {
case "pin1" :
List<WebElement> box1 = driver.findElements(By.cssSelector("div[class='field-set'] input[placeholder='1st']"));
if(!box1.isEmpty()) {
box1.get(0).sendKeys(value);
}
break;
case "pin2" :
List<WebElement> box2 = driver.findElements(By.cssSelector("div[class='field-set'] input[placeholder='2nd']"));
if(!box2.isEmpty()) {
box2.get(0).sendKeys(value);
}
break;
case "pin3" :
List<WebElement> box3 = driver.findElements(By.cssSelector("div[class='field-set'] input[placeholder='3rd']"));
if(!box3.isEmpty()) {
box3.get(0).sendKeys(value);
}
break;
case "pin4" :
List<WebElement> box4 = driver.findElements(By.cssSelector("div[class='field-set'] input[placeholder='4th']"));
if(!box4.isEmpty()) {
box4.get(0).sendKeys(value);
}
break;
default :
System.out.println("pincode textbox key not found");
break;
}
This code will send the pin-code in corresponding pin-code textbox if available on webpage.

Issue with variable in a if/else loop in Java

import java.util.HashMap;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
String location = "memes more memes Virginia";
String test = createStateMap(location);
System.out.println(test);
}
public static String createStateMap(String loc) {
loc = loc.toUpperCase();
String secondLast; // Retrieves potential second to last value
String lastWord; // Retrieves last value
String state = "failed";
String trimmed = loc.trim(); // Take off spaces at the end of String
String o = trimmed.substring(0, trimmed.lastIndexOf(" ")); // Remove last Word in String EX. "SOUTH CAROLINA" = "SOUTH"
String otrim = o.trim(); // Take off spaces at the end of String
if (trimmed.contains("/")){
secondLast = otrim.substring(otrim.lastIndexOf("/")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf("/")+1);
} else {
secondLast = otrim.substring(otrim.lastIndexOf(" ")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf(" ")+1);
}
HashMap<String,String> names = new HashMap<String,String>();
names.put("ALABAMA", "AL");
names.put("ALASKA", "AK");
names.put("ARIZONA", "AZ");
names.put("ARKANSAS", "AR");
names.put("CALIFORNIA", "CA");
names.put("COLORADO", "CO");
names.put("CONNECTICUT", "CT");
names.put("DELAWARE", "DE");
names.put("FLORIDA", "FL");
names.put("GEORGIA", "GA");
names.put("HAWAII", "HI");
names.put("IDAHO", "ID");
names.put("ILLINOIS", "IL");
names.put("INDIANA", "IN");
names.put("IOWA", "IA");
names.put("KANSAS", "KS");
names.put("KENTUCKY", "KY");
names.put("LOUISIANA", "LA");
names.put("MAINE", "ME");
names.put("MARYLAND", "MD");
names.put("MASSACHUSETTS", "MA");
names.put("MICHIGAN", "MI");
names.put("MINNESOTA", "MN");
names.put("MISSISSIPPI", "MS");
names.put("MISSOURI", "MO");
names.put("MONTANA", "MT");
names.put("NEBRASKA", "NE");
names.put("NEVADA", "NV");
names.put("NEWHAMPSHIRE", "NH");
names.put("JERSEY", "NJ");
names.put("MEXICO", "NM");
names.put("YORK", "NY");
names.put("CAROLINA", "NC");
names.put("DAKOTA", "ND");
names.put("OHIO", "OH");
names.put("OKLAHOMA", "OK");
names.put("OREGON", "OR");
names.put("PENNSYLVANIA", "PA");
names.put("RHODEISLAND ", "RI");
names.put("CAROLINA", "SC");
names.put("DAKOTA", "SD");
names.put("TENNESSEE", "TN");
names.put("TEXAS", "TX");
names.put("UTAH", "UT");
names.put("VERMONT", "VT");
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
names.put("WISCONSIN", "WI");
names.put("WYOMING", "WY");
System.out.println(secondLast);
if (names.containsValue(lastWord)){
state = lastWord;
}
if (names.containsKey(lastWord)){
if (names.get(lastWord).equals("CAROLINA")){ // Differentiate NC and SC
if (secondLast.equals("North")){
state = "NC";
} else { state = "SC"; }
} if (names.get(lastWord).equals("DAKOTA")) { // Differentiate ND and SD
if (secondLast.equals("North")){
state = "ND";
} else { state = "SD"; }
} if (names.get(lastWord).equals("VIRGINIA")) { // Differentiate WV and VA
if (secondLast.equals("West")){
state = "WV";
} else { state = "VA"; }
} else { state = names.get(lastWord); }
}
return state;} }
I am currently having issues with my code that assigns a state's abbreviations to a variable depending on the String passed into the parameter of the createStateMap method. When the lastWord String is either Virginia, Dakota, or Carolina they will always be assigned WV, ND, or NC- even if the secondLast is not North or West.
Any help would be much appreciated, I have been stuck on this one for a while.
names.get(lastWord) already returns "SC" for key "CAROLINA", so your
names.get(lastWord).equals("CAROLINA")
condition will always return false.
It also makes no sense to put the same key twice in the Map, since the second value will overwrite the first value having the same key.
Why not put the full name of the state as key?
names.put("SOUTH CAROLINA", "SC");
names.put("NORTH CAROLINA", "NC");
In that case
state = names.get(fullStateName);
will always work and you can eliminate all of those conditions, as long as fullStateName contains the full name of the state (either a single word or two words).
If you don't know whether you should search for the last word or the last two words in the Map, you can search for the last two words, and if not found, search for the last word :
state = names.get(secondLast + " " + lastWord);
if (state == null) {
state = names.get(lastWord);
}
So, just as an fyi,
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
You're working with a HashMap here, so you can only have 1 value per key. This means the only value you'll get when you extract VIRGINIA is WV (the last one to be entered). Just put in the full state name, as Eran suggested. I mean, you're already putting in NEWHAMPSHIRE, which is technically two words, so I don't see why you don't want to do the same thing for the Carolinas, Dakotas, and Virginias.

Android: EditText returning same value as contents

The method below is responsible for inserting a new record to a database table and it is called when a button is pressed. However the String input that is assigned the value of the contents of the EditText never seems to be assigned to the new contents whenever a new value is typed in.
As a result inserting a new record only works once.
Any suggestions why this happens would be appreciated.
public void insertRecord(View additionBut) {
System.out.println("NOW INSIDE THE INSERT RECORD");
input = addTextInput.getText().toString();
addTextInput.getText().clear();
System.out.println(input);
if (purpose.equals("ViewNovel")) {
md.addPiece(input, "0");
} else if (purpose.equals("ViewPlay")) {
md.addPiece(input, "1");
} else {
// whatever else
}
displayList();
}
You can also clear your EditText in another way, Try following way,
public void insertRecord(View additionBut) {
System.out.println("NOW INSIDE THE INSERT RECORD");
input = addTextInput.getText().toString();
addTextInput.setText("") // Change here
System.out.println(input);
if (purpose.equals("ViewNovel")) {
md.addPiece(input, "0");
} else if (purpose.equals("ViewPlay")) {
md.addPiece(input, "1");
} else {
// whatever else
}
displayList();
}
Place
displayList();
addTextInput.getText().clear(); //after displayList();
May be the reference is same. Because of that when you try to clear the edit text the value in input getting reflected. If so, try creating new String object with the value in the edit text box.

Empty String validation for Multiple JTextfield

Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.
if (firstName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else {
//code to enter values into MySql database
the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.
Thanks
Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.
The collaborators:
InputVerifier which contains the validation logic. Here it's simply checking for empty text in the field in verify. Note that
verify must not have side-effects
shouldYieldFocus is overridden to not restrict focus traversal
it's the same instance for all text fields
a commit action that checks the validity of all children of its parent by explicitly invoking the inputVerifier (if any) and simply does nothing if any is invalid
a mechanism for a very simple though generally available error message taking the label of the input field
Some code snippets
// a reusable, shareable input verifier
InputVerifier iv = new InputVerifier() {
#Override
public boolean verify(JComponent input) {
if (!(input instanceof JTextField)) return true;
return isValidText((JTextField) input);
}
protected boolean isValidText(JTextField field) {
return field.getText() != null &&
!field.getText().trim().isEmpty();
}
/**
* Implemented to unconditionally return true: focus traversal
* should never be restricted.
*/
#Override
public boolean shouldYieldFocus(JComponent input) {
return true;
}
};
// using MigLayout for lazyness ;-)
final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
for (int i = 0; i < 5; i++) {
// instantiate the input fields with inputVerifier
JTextField field = new JTextField(20);
field.setInputVerifier(iv);
// set label per field
JLabel label = new JLabel("input " + i);
label.setLabelFor(field);
form.add(label);
form.add(field);
}
Action validateForm = new AbstractAction("Commit") {
#Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
if (!validateInputs(source.getParent())) {
// some input invalid, do nothing
return;
}
System.out.println("all valid - do stuff");
}
protected boolean validateInputs(Container form) {
for (int i = 0; i < form.getComponentCount(); i++) {
JComponent child = (JComponent) form.getComponent(i);
if (!isValid(child)) {
String text = getLabelText(child);
JOptionPane.showMessageDialog(form, "error at" + text);
child.requestFocusInWindow();
return false;
}
}
return true;
}
/**
* Returns the text of the label which is associated with
* child.
*/
protected String getLabelText(JComponent child) {
JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
return labelFor != null ? labelFor.getText() : "";
}
private boolean isValid(JComponent child) {
if (child.getInputVerifier() != null) {
return child.getInputVerifier().verify(child);
}
return true;
}
};
// just for fun: MigLayout handles sequence of buttons
// automagically as per OS guidelines
form.add(new JButton("Cancel"), "tag cancel, span, split 2");
form.add(new JButton(validateForm), "tag ok");
There are multiple ways to do this, one is
JTextField[] txtFieldA = new JTextField[13] ;
txtFieldFirstName.setName("First Name") ; //add name for all text fields
txtFieldA[0] = txtFieldFirstName ;
txtFieldA[1] = txtFieldLastName ;
....
// in action event
for(JTextField txtField : txtFieldA) {
if(txtField.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
//break it to avoid multiple popups
break;
}
}
Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.
Take an array of these three JTextField, I am giving an overview
JTextField[] fields = new JTextField[13]
field[0] = firstname;
field[1] = lastname; //then add remaining textfields
for(int i = 0; i < fields.size(); ++i) {
if(fields[i].getText().isEmpty())
JOptionPane.showMessageDialog(null, "No data entered");
}
Correct me if i'm wrong, I am not familiar with Swing or awt.HTH :)
Here is one way to do it:
public static boolean areAllNotEmpty(String... texts)
{
for(String s : texts) if(s == null || "".equals(s)) return false;
return true;
}
// ...
if(areAllNotEmpty(firstName, lastName, emailAddress, phone))
{
JOptionPane.showMessageDialog(null, "No data entered");
}

Categories