Cant get textbox values to multiply together into a third - java

Im currently working on a simple program to show the contents of a database. Im not sure how to get two of the textbox values to multiply together and put the result in the third. THis is the section of code:
private void GetProductTable() {
ResultSet rs = GetProducts();
try {
jTable2.setModel(buildTableModel(rs));
} catch (Exception ex) {
}
jTable2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JTable target;
target = (JTable) e.getSource();
int row;
row = target.getSelectedRow();
String[] result;
result = getRowAt(target, row);
ProductID.setText(result[0]);
ProductName.setText(result[1]);
ProductSupplierID.setText(result[2]);
ProductCataID.setText(result[3]);
ProductInStock.setText(result[4]);
ProductOnOrder.setText(result[5]);
ProductReorderLvl.setText(result[6]);
ProductDiscon.setText(result[7]);
ProductUnitPrice.setText(result[8]);
ProductUnitPrice1.setText();
}
});
}
I need result[5] to multiply by result[8] and put the total in ProductUnitPrice1. The results are being retrieved from an external database. I have tried a few things and i just cant get it to work, all I keep getting is the contents or result 5 and 8 both put into the box. I know I need to get it to look at the results as a integer and not a string but everything I have tried has not worked.
This may be a really simple solution but I am very much a beginner and I need this to work in order to pass the Java unit in my HND.
Any help will be much appreciated.

int result=Integer.valueOf(result[5])*Integer.valueOf(result[8]);
ProductUnitPrice1.setText(result);
you might need to change datatypes to doubles. maybe this works too:
ProductUnitPrice1.setText(String.valueOf(Integer.valueOf(result[5])*Integer.valueOf(result[8])));

Related

How Can I Sort JTable With A Button?

Example:
I made a table, and I want a search box for each column. I hid the column titles with this code:
table.setTableHeader(null);
And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.
I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.
Is there any way to do it? Or all the thing i tried useless and there is much easy way to do it? I hope explained it right.
Note :
I have found this code.I dont even know if it does what i need. I did try it but getting error.
/** Default sort behaviour, plus every third click removes the sort. */
private final class CustomSorter extends MouseAdapter {
#Override public void mouseClicked(MouseEvent aEvent) {
int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
//build a list of sort keys for this column, and pass it to the sorter
//you can build the list to fit your needs here
//for example, you can sort on multiple columns, not just one
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
//cycle through all orders; sort is removed every 3rd click
SortOrder order = SortOrder.values()[fCountClicks % 3];
sortKeys.add(new RowSorter.SortKey(columnIdx, order));
fSorter.setSortKeys(sortKeys);
++fCountClicks;
}
private int fCountClicks;
}
}
And did try this and getting same error.
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.getRowSorter().toggleSortOrder(1);
}
});
Error:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
This is the code: Code
This is the what program looks like : Picture
In the ActionListener of your JButton you can try sorting the column with code like:
table.getRowSorter().toggleSortOrder(columnIndex);
This should allow you to click the button to reverse the sort order each time it is clicked.
Edit:
As I said in my comment you need to learn how to solve a NullPointerException.
The stack trace when I run the code states:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frame1$2.actionPerformed(frame1.java:83)
Line 83 is:
table.getRowSorter().toggleSortOrder(0);
So you have two variables at that statement:
table
table.getRowSorter()
It is up to you to determine which variable is null
So you add debug code before that statement:
System.out.println( table );
System.out.println( table.getRowSorter() );
If you do you will see that table.getRowSorter() returns null.
So now you can ask a proper question like:
"Why does table.getRowSorter() return null?"
The answer is simple you didn't set the properties of the table to do sorting.
This is easily done by adding:
table.setModel(model);
table.setAutoCreateRowSorter(true); // added
In the future do some basic debugging BEFORE asking a question. You can't code if you don't know the basics of debugging code.
My original answered assumed you new how to sort columns in a table when using the table header and you just wanted to know how to use a separate button. That is why a "MRE" should be posted with EVERY question so we don't have to guess what your code is really doing.

Using variable from another java file

I am trying to make an app which import data from database and use it in another function.
I got connection with database and it returns me a variable called miejsce:
public void sprawdzAuto(String nrRej, String miejsce){
try{
String query = "select lokalizacja from samochody75 where nrRej=?";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, nrRej);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
miejsce = rs.getString(1);
System.out.println(miejsce);
}
JOptionPane.showMessageDialog(null, "Znaleziono.");
} catch(SQLException e) {
System.out.print(e);
}
}
Now when i got miejsce i want to use it in another .java file called Mapa.
public class Mapa extends MapView{
private Map map;
public Mapa(String nName)
{
JFrame frame = new JFrame(nName);
setOnMapReadyHandler(new MapReadyHandler() {
#Override
public void onMapReady(MapStatus status) {
if (status == MapStatus.MAP_STATUS_OK){
map=getMap();
MapOptions mapOptions = new MapOptions();
MapTypeControlOptions controlOptions= new MapTypeControlOptions();
mapOptions.setMapTypeControlOptions(controlOptions);
map.setOptions(mapOptions);
map.setCenter(new LatLng(1,1));
map.setZoom(17.0);
Marker mark = new Marker(map);
mark.setPosition(map.getCenter());
}
}
});
frame.add(this, BorderLayout.CENTER);
frame.setSize(700,500);
frame.setVisible(true);
}
}
I want result of miejsce to map.setCenter();
I tried diffrent things but none of them works.
Is there any solution to make it possible?
Thank you in advance.
You seem to missunderstand a lot of concepts about how scope and Java in general works. You should try and find a java tutorial before posting on StackOverflow.
Here are some tips that can help you in your problem.
You are iterating through a ResultSet which means you probably won't have only one result. So when you write miejsce = rs.getString(1); only the last value of your result set will be stored in your string.
String is an immutable object. Which means that when you pass a String as a parameter to a method, you will not be able to access the value of your String from the calling method unless you return it from the called method. And that's not what you are doing here.
To complete my two previous points and to solve partially yours, you can take a look at List in java. Where you can store objects and values, strings included, and you will be able to access the content of your list, filled from the called method (sprawdzAuto here), from your calling method.
I won't do the code for you, I think it is better if you do some digging yourself.
Hope this helps.

JavaFX How to get all values and sum of specific column from Table View by button?

I have a problem with adding functionality to my program. I'm using JavaFX and Table View. I don't know how can I implement a method witch will get data from specific column.
I try to implement solution from this said:
JavaFX How to get all values of one column from TableView?
But I don't understand exactly how should I send initialized TableColumn class to method totalPaidSaving
And: How to get selected TableCell in JavaFX TableView
I Also found a couple of different solutions using getSelectionModel().getSelectedCells() but in this case I need to use button and some sort of code witch will get data from specific column.
Fragment of MainControl class. Place where the method is called :
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Operation operation = new Operation();
operation.addRecord(dateTextField, distanceTextField, lpgAmountTextField, lpgPriceTextField,
petrolAmountTextField, petrolPriceTextField, paidLabel, savingLabel, gasEfficiencyLabel,
contentTable, totalSavingsLabel);
operation.totalPaidSaving(contentTable, totalSavingsLabel);
}
});
A fragment of the configuration of my TableView also in the MainControl class.
#SuppressWarnings("unchecked")
public void configurateTable() {
TableColumn<GasRecords, String> savingColumn = new TableColumn<GasRecords, String>(SAVING_COLUMN);
savingColumn.setCellValueFactory(new PropertyValueFactory<>("saving"));
contentTable.getColumns().addAll(dateColumn, distanceColumn, lpgAmountColumn, lpgPriceColumn, petAmountColumn,
petPriceColumn, paidColumn, savingColumn, gasEfficiencyColumn);
}
A fragment of Operation class:
public void totalPaidSaving(TableView<GasRecords> cT, Label tSL) {
String totalSavingValue = "0";
//the code that calculates the sum of the values ​​of a particular column
tSL.setText(String.format("%.2f zł", totalSavingValue));
}
I know that using String instead of double is bad but for now I would like to solve it in this form.
Link of visualization of me application and example of column i want to sum.
https://zapodaj.net/d8fc7ece3f629.jpg.html
My goal is to, after press the "Add" button application shows me the sum of all savings rows from saving column in specific label. Rest of application is working.
In this ways you can calculate the values of a column. you can get cell value by the index of the column. you have to use contentTable.getColumns().get(7).getCellObservableValue(i).getValue() get the cell value of that column Savings.
int totalSavingValue=0;
for (int i= 0;i<tblDispatchHistory.getItems().size();i++){
total = total+Integer.valueOf(String.valueOf(contentTable.getColumns().get(7).getCellObservableValue(i).getValue()));
}
System.out.println(totalSavingValue);
tSL.setText(totalSavingValue);

Issue with default Sorting on Virtual Table & ViewerComparator

We have a Virtual Table in my Eclipse RCP application. We make a call to the backend to retrieve the data to be populated in the virtual table.
We want default sorting on the table on a single column. We use ViewerComparator to achieve sorting functionality. My problem is, I am not able to get this sorting working when the table loads with the data for the 1st time. But when I click on the column, everything works fine as expected.
This is how, I set the Comparator to the column
TableViewerColumn tvc = viewer.addColumn(100, SWT.LEFT, "Name");
viewer.setColumnComparator(tvc,
new Comparator<Person>() {
#Override
public int compare(Person o1,Person o2) {
double firstValue = Double.parseDouble(o1
.getAge());
double secondValue = Double.parseDouble(o2
.getAge());
return firstValue > secondValue ? 1 : -1;
}
});
setColumnComparator method in custom viewer
public void setColumnComparator(TableViewerColumn tvc, Comparator<T> cmp){
final MyViewerComparator c = new MyViewerComparator(cmp);
final TableColumn tc = tvc.getColumn();
setComparator(c);
getTable().setSortDirection(c.getDirection());
getTable().setSortColumn(tc);
refresh();
tc.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
<same code as above>
}
});
MyViewerComparator
class MyViewerComparator extends ViewerComparator{
Comparator<T> cmp;
boolean desc = true;
MyViewerComparator(Comparator<T> cmp){
this.cmp = cmp;
}
int getDirection(){
return desc?SWT.UP:SWT.DOWN;
}
void flipDirection(){
desc = !desc;
}
#Override
public int compare(Viewer viewer, Object e1, Object e2) {
if(e1 == null || e2==null){
return 0;
}
int rc = cmp.compare((T)e1, (T)e2);
if(desc)
return -rc;
return rc;
}
}
When the table loads the data for the 1st time, it goes inside the Bolded condition in the above code as one of the object is ALWAYS NULL
Note: This functionality works totally fine if I use a Standard table rather than VIRTUAL TABLE. I am not sure whether I can change it to use Standard table as we want the lazy load functionality as well..
ContentProvider used is: ObservableListContentProvider
Please advise..
A late answer that hopefully still helps others. I encountered exactly the same problem when using SWT.VIRTUAL with an ObservableListContentProvider in combination with sorting.
The original intent of SWT.VIRTUAL is that not all elements in the contents need to be fetched to show only part of the contents. A custom content provider needs to be implemented which only has to return the elements that need to be currently shown on the screen. You also have to tell the table the total number of elements in existence. In such a use case, a table cannot be sorted in the normal way with a ViewerComparator because not all elements are known. However SWT.VIRTUAL can also be used as a performance optimization for rendering a table with many elements. This seems to work fine with the non-observable ArrayContentProvider.
But when using ObservableListContentProvider I am seeing exactly the same issue as you have. Somehow it tries to be smart and update only the elements that have actually changed. Somewhere in the depths of it's implementation something goes wrong for virtual tables, I have no clue exactly what. But I do have a solution: don't use ObservableListContentProvider at all and simply refresh the table viewer. You can e.g. use a plain ArrayContentProvider and add the following listener to the IObservableList contents of the viewer:
new IListChangeListener() {
#Override
public void handleListChange(ListChangeEvent event) {
viewer.refresh();
}
};
I actually implemented my own "SimpleObservableListContentProvider" that does exactly this, but also takes care of switching table input by implementing the inputChanged method to remove this listener from the old input list and add it to the new one.

Problem with db4o (java) when running a query

I'm glancing through parts of the official db4o tutorial, and I'm trying to make a modification to the code they give you for running native queries:
//the original
List<Pilot> pilots = db.query(new Predicate<Pilot>() {
public boolean match(Pilot pilot) {
return pilot.getPoints() == 100;
}
});
//modified
List<Pilot> pilots = db.query(new Predicate<Pilot>() {
public boolean match(Pilot pilot) {
return pilot.getGames() >= 100;
}
});
I've added this to their Pilot class:
//in declarations
private ArrayList<String> games;
//modified constructors
public Pilot() {
this.name=null;
this.points=0;
}
public Pilot(String name,int points) {
this.name=name;
this.points=points;
this.games = new ArrayList<String>();
int numGames = (int) (Math.random() * 1000 + 1);
for(int i=0;i<numGames;i++) {
this.games.add(name=" vs Computer");
}
}
//new method
public int getGames() {
return games.size();
}
I've already populated a database with 500 objects using the second constructor, and all the data in the db looks correct with the OME eclipse addon. I've tested getGames() and it works as expected.
My problem is that when I run the modified query, it returns all the objects in the db and I don't understand why. I've tried changing the query to include a more standard if true, else false structure and changing the query to include requiring a certain amount of points to no avail. Whatever I do, it seems it always evaluates (pilot.getGames() >= 100) to be true.
Can anyone help me as to understand why?
I think you've found a bug. db4o tries to translate the native-queries into a soda-query. This avoid instantiating to objects to perform queries. Now here this translation somehow does not work!
When you turn the optimization off it works. You can do this via configuration:
EmbeddedConfiguration cfg = Db4oEmbedded.newConfiguration();
cfg.common().optimizeNativeQueries(false);
ObjectContainer db = Db4oEmbedded.openFile(cfg,DB_FILE)
However I don't recommend this because then all queries will run slowly. I've found an easy workaround. Change the declaration of the games-field to List<String>. (And other, future List-fields). Like this:
class Pilot {
private List<String> games;
// rest
}
This will 'deoptimize' a native query as soon as you access the size() or other methods, hence avoids this bug.
Now a 'deoptimized' query can run quite slow. So if you have lots of objects and the performance is unacceptable I would do this for this query: Create an addional field which stores the current size of the list. Then you use this additional size-field for this kind of query. Additionally you can then index the size-field.
I've reported this as a bug:

Categories