Showing an Integer tableview in javaFx as a string - java

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.

Related

Accessing string template rule names from ANTLR base listener

Working on a pretty printer. Based on my understanding of ANTLR and StringTemplate so far, if I want to match all my grammar rules to templates and apply the template each time the grammar rule is invoked, I can create my templates with names matching my grammar rules.
[Side question: Is this how I should approach it? It seems like ANTLR should being doing the work of matching the parsed text to the output templates. My job will be to make sure the parser rules and templates are complete/correct.]
I think ANTLR 3 allowed directly setting templates inside of the ANTLR grammar, but ANTLR 4 seems to have moved away from that.
Based on the above assumptions, it looks like the MyGrammarBaseListener class that ANTLR generates is going to be doing all the work.
I've been able to collect the names of the rules invoked while parsing the text input by converting this example to ANTLR 4. I ended up with this for my enterEveryRule():
#Override public void enterEveryRule(ParserRuleContext ctx) {
if (builder.length() > 0) {
builder.append(' ');
}
if (ctx.getChildCount() > 0) {
builder.append('(');
}
int ruleIndex = ctx.getRuleIndex();
String ruleName;
if (ruleIndex >= 0 && ruleIndex < ruleNames.length) {
ruleName = ruleNames[ruleIndex];
System.out.println(ruleName); // this part works as intended
}
else {
ruleName = Integer.toString(ruleIndex);
}
builder.append(ruleName);
// CONFUSION HERE:
// get template names (looking through the API to figure out how to do this)
Set<String> templates = (MyTemplates.stg).getTemplateNames()
// or String[] for return value? Java stuff
// for each ruleName in ruleNames
// if (ruleName == templateName)
// run template using rule children as parameters
// write pretty-printed version to file
}
The linked example applies the changes to create the text output in exitEveryRule() so I'm not sure where to actually implement my template-matching algorithm. I'll experiment with both enter and exit to see what works best.
My main question is: How do I access the template names in MyTemplates.stg? What do I have to import, etc.?
(I'll probably be back to ask about matching up rule children to template parameters in a different question...)
Following demonstrates a simple way of dynamically accessing and rendering named StringTemplates. Intent is to build varMap values in the listener (or visitor) in its corresponding context, keyed by parameter name, and call the context dependent named template to incrementally render the content of the template.
public class Render {
private static final String templateDir = "some/path/to/templates";
private STGroupFile blocksGroup;
private STGroupFile stmtGroup;
public Render() {
blocksGroup = new STGroupFile(Strings.concatAsClassPath(templateDir, "Blocks.stg"));
stmtGroup = new STGroupFile(Strings.concatAsClassPath(templateDir, "Statements.stg"));
}
public String gen(GenType type, String name) {
return gen(type, name, null);
}
/**
* type is an enum, identifying the group template
* name is the template name within the group
* varMap contains the named values to be passed to the template
*/
public String gen(GenType type, String name, Map<String, Object> varMap) {
Log.debug(this, name);
STGroupFile stf = null;
switch (type) {
case BLOCK:
stf = blocksGroup;
break;
case STMT:
stf = stmtGroup;
break;
}
ST st = stf.getInstanceOf(name);
if (varMap != null) {
for (String varName : varMap.keySet()) {
try {
st.add(varName, varMap.get(varName));
} catch (NullPointerException e) {
Log.error(this, "Error adding attribute: " + name + ":" + varName + " [" + e.getMessage() + "]");
}
}
}
return st.render();
}
}

How to fix error using equalsIgnorecase in java netbeans?

I am building java project in inventory management. following is the code i used for inserting color in database using equalsIgnorecase but it continuous showing Already exist. Please some one fix my code.
thanks
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtNewColor.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fields should not be empty");
}
else
{
try {
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(cl));
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
if (color==0)
{
String strdata="Insert into color_details (Color)values(?)";
ps=DbConnection.cn.prepareStatement(strdata);
ps.setString(1, txtNewColor.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Color Added Successfully");
cleartext();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
refreshTable();
}
Try change if(cl.equalsIgnoreCase(cl)); to if(c.equalsIgnoreCase(cl))
Had not spotted the semi-colon at the end of your if statement
You are comparing the same String again. So It always results in a true, also the ; will skip even if they match. Remove it.
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(c))
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
You used same two strings to compare. so change c.equalsIgnoreCase(c1). Also make sure you have removed trailing spaces when getting input from text fields. it may makes your comparison fail.
String c = txtNewColor.getText().trim();
Remove the semi colon after if clause
if(cl.equalsIgnoreCase(cl)); ---> if(cl.equalsIgnoreCase(cl))

Using Jackcess to retrieve numeric values stored in a text field gives ClassCastException

I am working with Jackcess to read and categorize an access database. It's simply meant to open the database, loop through each line, and print out individual row data to the console which meet certain conditions. It works fine, except for when I try to read numeric values. My code is below. (This code is built into a Swing GUI and gets executed when a jbutton is pressed.)
if (inv == null) { // Check to see if inventory file has been set. If not, then set it to the default reference path.
inv = rPath;
}
if (inventoryFile.exists()) { // Check to see if the reference path exists.
List<String> testTypes = jList1.getSelectedValuesList();
List<String> evalTypes = jList3.getSelectedValuesList();
List<String> grainTypes = jList2.getSelectedValuesList();
StringBuilder sb = new StringBuilder();
for (int i=0; i<=evalTypes.size()-1; i++) {
if (i<evalTypes.size()-1) {
sb.append(evalTypes.get(i)).append(" ");
}
else {
sb.append(evalTypes.get(i));
}
}
String evalType = sb.toString();
try (Database db = DatabaseBuilder.open(new File(inv));) {
Table sampleList = db.getTable("NTEP SAMPLES LIST");
Cursor cursor = CursorBuilder.createCursor(sampleList);
for (int i=0; i<=testTypes.size()-1; i++) {
if ("Sample Volume".equals(testTypes.get(i))) {
if (grainTypes.size() == 1 && "HRW".equals(grainTypes.get(0))) {
switch (evalType) {
case "GMM":
for (Row row : sampleList){
if (null != row.getString("CURRENTGAC")) {}
if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}
}
break;
case "NIRT":
// some conditional code
break;
case "TW":
// some more code
break;
}
}
else {
JOptionPane.showMessageDialog(null, "Only HRW samples can be used for the selected test(s).", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
}
catch (IOException ex) {
Logger.getLogger(SampleFilterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
When the code is run I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
The following condition looks to be what is throwing the error.
row.getDouble("CURRENTGAC")>=12.00
It appears that when the data is read from the database, the program is reading everything as a string, even though some fields are numeric. I was attempting to cast this field as a double, but java doesn't seem to like that. I have tried using the Double.parseDouble() and Double.valueOf() commands to try converting the value (as mentioned here) but without success.
My question is, how can I convert these fields to numeric values? Is trying to type cast the way to go, or is there a different method I'm not aware of? You will also notice in the code that I created a cursor, but am not using it. The original plan was to use it for navigating through the database, but I found some example code from the jackcess webpage and decided to use that instead. Not sure if that was the right move or not, but it seemed like a simpler solution. Any help is much appreciated. Thanks.
EDIT:
To ensure the program was reading a string value from my database, I input the following code
row.get("CURRENTGAC").getClass().getName()
The output was java.lang.String, so this confirms that it is a string. As was suggested, I changed the following code
case "GMM":
for (Row row : sampleList){
if (null != row.get("CURRENTGAC"))
//System.out.println(row.get("CURRENTGAC").getClass().getName());
System.out.println(String.format("|%s|", row.getString("CURRENTGAC")));
/*if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00 && row.getDouble("CURRENTGAC")<=14.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}*/
}
break;
The ouput to the console from these changes is below
|9.85|
|11.76|
|9.57|
|12.98|
|10.43|
|13.08|
|10.53|
|11.46|
...
This output, although looks numeric, is still of the string type. So when I tried to run it with my conditional statement (which is commented out in the updated sample code) I still get the same java.lang.ClassCastException error that I was getting before.
Jackcess does not return all values as strings. It will retrieve the fields (columns) of a table as the appropriate Java type for that Access field type. For example, with a test table named "Table1" ...
ID DoubleField TextField
-- ----------- ---------
1 1.23 4.56
... the following Java code ...
Table t = db.getTable("Table1");
for (Row r : t) {
Object o;
Double d;
String fieldName;
fieldName = "DoubleField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %f",
o));
System.out.println();
fieldName = "TextField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %s",
o));
try {
d = r.getDouble(fieldName);
} catch (Exception x) {
System.out.println(String.format(
"r.getDouble(\"%s\") failed - %s: %s",
fieldName,
x.getClass().getName(),
x.getMessage()));
}
try {
d = Double.parseDouble(r.getString(fieldName));
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) succeeded. Value: %f",
fieldName,
d));
} catch (Exception x) {
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) failed: %s",
fieldName,
x.getClass().getName()));
}
System.out.println();
}
... produces:
DoubleField comes back as: java.lang.Double
Value: 1.230000
TextField comes back as: java.lang.String
Value: 4.56
r.getDouble("TextField") failed - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
Double.parseDouble(r.getString("TextField")) succeeded. Value: 4.560000
If you are unable to get Double.parseDouble() to parse the string values from your database then either
they contain "funny characters" that are not apparent from the samples you posted, or
you're doing it wrong.
Additional information re: your sample file
Jackcess is returning CURRENTGAC as String because it is a Text field in the table:
The following Java code ...
Table t = db.getTable("NTEP SAMPLES LIST");
int countNotNull = 0;
int countAtLeast12 = 0;
for (Row r : t) {
String s = r.getString("CURRENTGAC");
if (s != null) {
countNotNull++;
Double d = Double.parseDouble(s);
if (d >= 12.00) {
countAtLeast12++;
}
}
}
System.out.println(String.format(
"Scan complete. Found %d non-null CURRENTGAC values, %d of which were >= 12.00.",
countNotNull,
countAtLeast12));
... produces ...
Scan complete. Found 100 non-null CURRENTGAC values, 62 of which were >= 12.00.

Selenium WebDriver with Java - how to add "else" condition

I have code:
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
for(WebElement position_list : some_list.getOptions()) {
if(position_list.getText().equalsIgnoreCase(v_value)) {
some_list.selectByVisibleText(position_list.getText());
break;
}
}
}
How can I add condition: if selenium doesn't find position_list.getText().equalsIgnoreCase(v_value) then system throw new RuntimeExpression?
Use iterator instead of foreach, it provides a hasNext() method with which you can check if you are currently dealing with the last element of your list.
Iterator<WebElement> iterator = some_list.getOptions().iterator();
and then instead of your foreach:
while(iterator.hasNext()) {
WebElement current = iterator.next();
if(current.getText().equalsIgnoreCase(v_value)) {
current.selectByVisibleText(position_list.getText());
break;
}
if(!iterator.hasNext()){
throw new RuntimeException();
}
}
Just a suggestion from what I see in your code.
When you use some_list.selectByVisibleText(position_list.getText()); the selectByVisibleText(..) method is already setup to iterate over all available options and select the one that matches the text parameter you pass in. Putting the call inside a loop checking for the option to be available is not ideal if you are looking to throw an exception.
Also, let's say you have the following code -
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
some_list.selectByVisibleText(position_list.getText());
....
}
In this case selectByVisibleText would throw a NoSuchElementException("Cannot locate element with text: " + text); in case the option is not available for selection. You should be able to catch that and throw a runtime exception.
I guess a simple answer to your question is a try catch
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
for(WebElement position_list : some_list.getOptions()) {
try{
if(position_list.getText().equalsIgnoreCase(v_value)) {
some_list.selectByVisibleText(position_list.getText());
break;
}
}
catch(RuntimeExpression ex)
{
...
}
}
}

When I set a variable to JTextArea it has not value

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..

Categories