I'm in a Programming and Problem Solving 1 class and this lab that we have is giving me a bit of trouble. Our professor has written out the bare bones code for the game "Cookie Clicker" and has asked us to fill in the rest to make the game actually work (if you aren't already familiar with the game, you most likely will not be able to help). As of now, the game has all the buttons already but if you click any of them, nothing happens. If anybody could show me how to update the JLabels so that the buttons show the correct numbers each time they're clicked, it'd be greatly appreciated. The part that needs the code is marked by //Start and //End, almost all the way at the bottom.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class CookieClickerGUI extends javax.swing.JFrame {
//Instance variables
public int cookies;
public int cursors;
public int grandmas;
public int farms;
public int factories;
//Getters
public int getCookies()
{
return cookies;
}
public int getCursors()
{
return cursors;
}
public int getGrandmas()
{
return grandmas;
}
public int getFarms()
{
return farms;
}
public int getFactories()
{
return factories;
}
//Setters
public void setCookies()
{
this.cookies = cookies;
}
public void setCursors()
{
this.cursors = cursors;
}
public void setGrandmas()
{
this.grandmas = grandmas;
}
public void setFarms()
{
this.farms = farms;
}
public void setFactories()
{
this.factories = factories;
}
/**
* Creates new form CookieClickerGUI
*/
public CookieClickerGUI() {
initComponents();
cookieUpdater();
}
public void cookieUpdater() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
//here is your action
//update your cookies
}
};
Timer displayTimer = new Timer(1000, listener);
displayTimer.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
cookieButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
numberOfCookiesLabel = new javax.swing.JLabel();
cursorButton = new javax.swing.JButton();
grandmaButton = new javax.swing.JButton();
farmButton = new javax.swing.JButton();
factoryButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
helperLabel = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
grandmaLabel = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
farmsLabel = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
factoriesLabel = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
helperCostLabel = new javax.swing.JLabel();
grandmaCostLabel = new javax.swing.JLabel();
farmsCostLabel = new javax.swing.JLabel();
factoriesCostLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
cookieButton.setText("Cookie");
cookieButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cookieButtonActionPerformed(evt);
}
});
jLabel1.setText("Cookies:");
numberOfCookiesLabel.setText("0");
cursorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cursorButtonActionPerformed(evt);
}
});
grandmaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
grandmaButtonActionPerformed(evt);
}
});
farmButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
farmButtonActionPerformed(evt);
}
});
factoryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
factoryButtonActionPerformed(evt);
}
});
jLabel2.setText("Number of Helpers:");
helperLabel.setText("0");
jLabel4.setText("Number of Grandmas:");
grandmaLabel.setText("0");
jLabel6.setText("Number of Farms:");
farmsLabel.setText("0");
jLabel8.setText("Number of Factories:");
factoriesLabel.setText("0");
jLabel3.setText("Cost:");
jLabel5.setText("Cost:");
jLabel7.setText("Cost:");
jLabel9.setText("Cost:");
helperCostLabel.setText("0");
grandmaCostLabel.setText("0");
farmsCostLabel.setText("0");
factoriesCostLabel.setText("0");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numberOfCookiesLabel))
.addComponent(cookieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cursorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(helperLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(helperCostLabel))))
.addGroup(layout.createSequentialGroup()
.addComponent(grandmaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(grandmaLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(grandmaCostLabel))))
.addGroup(layout.createSequentialGroup()
.addComponent(farmButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(farmsLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(farmsCostLabel))))
.addGroup(layout.createSequentialGroup()
.addComponent(factoryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(factoriesLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(factoriesCostLabel)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(numberOfCookiesLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cursorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(helperLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(helperCostLabel))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(grandmaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(grandmaLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(grandmaCostLabel)))))
.addComponent(cookieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(farmButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(farmsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(farmsCostLabel))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(factoryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(factoriesLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(factoriesCostLabel))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//Start
private void cookieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cookieButtonActionPerformed
cookies = cookies + 1;
}//GEN-LAST:event_cookieButtonActionPerformed
private void cursorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cursorButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cursorButtonActionPerformed
private void grandmaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_grandmaButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_grandmaButtonActionPerformed
private void farmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_farmButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_farmButtonActionPerformed
private void factoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_factoryButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_factoryButtonActionPerformed
//End
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CookieClickerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CookieClickerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CookieClickerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CookieClickerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CookieClickerGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cookieButton;
private javax.swing.JButton cursorButton;
private javax.swing.JLabel factoriesCostLabel;
private javax.swing.JLabel factoriesLabel;
private javax.swing.JButton factoryButton;
private javax.swing.JButton farmButton;
private javax.swing.JLabel farmsCostLabel;
private javax.swing.JLabel farmsLabel;
private javax.swing.JButton grandmaButton;
private javax.swing.JLabel grandmaCostLabel;
private javax.swing.JLabel grandmaLabel;
private javax.swing.JLabel helperCostLabel;
private javax.swing.JLabel helperLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel numberOfCookiesLabel;
// End of variables declaration//GEN-END:variables
}
Related
I try to get emails from csv file and start mailing process. Everything works fine if I do it in the main thread. But if I start a new thread and try to do it threre it gives me NullPointer on this line:
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
For some reason it cannot get a list of emails.
Full code is here:
package com.company;
import javax.mail.MessagingException;
import javax.swing.*;
import static com.company.MainFormAppearance.mailingSubject;
import static com.company.MainFormAppearance.mailingText;
public class NewThead implements Runnable {
public JTextArea jTextAreaStatus;
public Reader readerEmail;
private boolean doStop = false;
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
#Override
public void run() {
while (keepRunning()){
Email email = new Email();
try {
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
} catch (MessagingException e) {
e.printStackTrace();
}
}
jTextAreaStatus.setText("completed");
}
}
Main class:
public class MainFormAppearance {
private JTextArea jTextAreaText;
private JTextArea jTextAreaSubject;
private JTextArea jTextAreaEmail;
private JTextArea jTextAreaStatus;
private JLabel blueLabel;
private JLabel copyRightLabel;
public JButton parceButton;
private JButton mailButton;
private JButton stopButton;
private String FILE_PATH_TEXT = "c:/Users/R2D2/Desktop/Main.txt";
private String FILE_PATH_SUBJECT = "c:/Users/R2D2/Desktop/Subject.txt";
public String CsvEmailsPath = "C:\\Users\\R2D2\\Desktop\\Emailstest.csv";
public String CsvBusinessesPath = "C:\\Users\\R2D2\\Desktop\\Businessestest.csv";
public static String mailingText = null;
public static String mailingSubject = null;
public Reader readerEmail;
public Reader readerBusiness;
public JPanel createContentPanel() {
JPanel totalGui = new JPanel();
totalGui.setLayout(null);
totalGui.setBackground(new Color(72, 209, 204));
jTextAreaText = new JTextArea();
jTextAreaSubject = new JTextArea();
jTextAreaEmail = new JTextArea();
jTextAreaStatus = new JTextArea();
blueLabel = new JLabel("Java Mailing Program");
copyRightLabel = new JLabel("\u00a9" + " Alex B - 2018");
parceButton = new JButton("Upload");
mailButton = new JButton("!Start!");
stopButton = new JButton("Stop");
readerEmail = new Reader();
readerBusiness = new Reader();
NewThead newThead = new NewThead();
Thread thread = new Thread(newThead);
//set program label
copyRightLabel.setLocation(10, 230);
copyRightLabel.setSize(400, 20);
copyRightLabel.setFont(new Font("Courier New", Font.ITALIC, 12));
copyRightLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(copyRightLabel);
//set program label
blueLabel.setLocation(10, 10);
blueLabel.setSize(400, 20);
blueLabel.setFont(new Font("Courier New", Font.ITALIC, 15));
blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(blueLabel);
//set Button 1 and click
parceButton.setLocation(270, 50);
parceButton.setSize(100, 30);
totalGui.add(parceButton);
parceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//parce data from files to Strings
mailingText = readLineByLineJava8(FILE_PATH_TEXT);
mailingSubject = readLineByLineJava8(FILE_PATH_SUBJECT);
try {
readerEmail.readCsvFile(CsvEmailsPath);
readerBusiness.readCsvFile(CsvBusinessesPath);
} catch (IOException e1) {
e1.printStackTrace();
}
if (isNullOrEmpty(mailingText)) {
jTextAreaText.setText("Text is empty! Check it!!!");
} else {
jTextAreaText.setText("***Text is Ready***");
}
if (isNullOrEmpty(mailingSubject)) {
jTextAreaSubject.setText("Subject is empty! Check it!!!");
} else {
jTextAreaSubject.setText("***Subject is Ready***");
}
}
});
//set Button 2 and click
mailButton.setLocation(270, 100);
mailButton.setSize(100, 30);
totalGui.add(mailButton);
mailButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
newThead.doStop();
jTextAreaStatus.setText("Stopped");
}
});
stopButton.setLocation(270, 150);
stopButton.setSize(100, 30);
totalGui.add(stopButton);
jTextAreaText.setLocation(20, 52);
jTextAreaText.setSize(200, 16);
jTextAreaText.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaText.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaText);
jTextAreaSubject.setLocation(20, 82);
jTextAreaSubject.setSize(200, 16);
jTextAreaSubject.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaSubject.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaSubject);
jTextAreaEmail.setLocation(20, 112);
jTextAreaEmail.setSize(200, 16);
jTextAreaEmail.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaEmail.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaEmail);
jTextAreaStatus.setLocation(20, 182);
jTextAreaStatus.setSize(200, 16);
jTextAreaStatus.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaStatus.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaStatus);
totalGui.setOpaque(true);
return totalGui;
}
public static boolean isNullOrEmpty(String str) {
if (str != null && !str.isEmpty())
return false;
return true;
}
}
Class that reads emails from csv (should be correct):
package com.company;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Reader {
public CSVReader reader;
public LinkedList myList;
public void readCsvFile(String path) throws IOException {
try {
reader = new CSVReader(new FileReader(path));
String[] column;
myList = new LinkedList<>();
LinkedList <String> map;
while ((column = reader.readNext()) != null) {
map = new LinkedList<String>();
map.add(column[0]);
myList.add(String.valueOf(map).replace("[","").replace("]",""));
//myList.add(String.valueOf(map));
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why i do it in another thread? Because I want to have a chance to stopp mailing process by clicking in stop button and killing a new thread.
my problem is in the onClick method. I just can't seem to figure out the how to properly construct a running Runnable/Thread/Handler.
package sed.jeff.conversion;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity
{
private static final String TAG = "MainActivity";
Button btConvert;
EditText etInitialValue;
TextView tvAnswer;
Spinner spInitialType, spFinalType;
int mInitialValue, mInitialType, mFinalValue, mFinalType, mRegion = 0;
Distance D1;
Handler handler;
Runnable r;
//initialization
#Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "entered onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btConvert = (Button)findViewById(R.id.btnConvert);
etInitialValue = (EditText)findViewById(R.id.etInitialValue);
spInitialType = (Spinner)findViewById(R.id.spInitialType);
spFinalType = (Spinner)findViewById(R.id.spFinalType);
D1 = new Distance();
}
//implementation
protected void onStart()
{
Log.i(TAG, "entered onStart()");
super.onStart();
spInitialType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 1: " + position);
mInitialType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
spFinalType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 2: " + position);
mFinalType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
btConvert.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.i(TAG, "entered onClick()");
handler = new Handler();
r = new Runnable()
{
#Override
public void run()
{
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
handler.post(this);
}
};
handler.post(r);
}
});
}
}
This is the class I am using to do the conversion. The only important methods here as of right now are the constructor with no inputs and the String getAnswer() method.
package sed.jeff.conversion;
public class Distance
{
double league, mile, yard, feet, inch, line, thou;
double decameter, hectometer, kilometer, megameter, meter, decimeter, centermeter, micrometer;
double fathom, nauticalMile;
double chain, rod;
double furlong, horseLength;
double hubbleLength, parsec, lightYear, astronomicalUnit;
/*(
private static double[] THOU = {1, 83.333333, 1000, 12000, 36000, 63360000, 190080000};
private static double[] LINE = {.012, 1, 12, 144, 432, 760320, 2280960};
private static double[] INCH = {.001, .083333, 1, 12, 36, 63360, 190080};
private static double[] FOOT = {.000083, .006944, .083333, 1, 3, 5280, 15840};
private static double[] YARD = {.000028, .002315, .027778, .333333, 1, 1760, 5280};
private static double[] MILE = {.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3};
private static double[] LEAGUE = {.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1};
*/
private static double[][] CONVERSION_USA = {{1, 83.333333, 1000, 12000, 36000, 63360000, 190080000},
{.012, 1, 12, 144, 432, 760320, 2280960},
{.001, .083333, 1, 12, 36, 63360, 190080},
{.000083, .006944, .083333, 1, 3, 5280, 15840},
{.000028, .002315, .027778, .333333, 1, 1760, 5280},
{.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3},
{.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1}
};
public double[] answer;
public Distance()
{
answer = new double[7];
}
public Distance(int type, int initialMeasurement, double value)
{
answer = new double[7];
switch(type)
{
case 0:
uSMeasurments(initialMeasurement, value);
break;
}
}
private void uSMeasurments(int initialType, double value)
{
for(int i = 0; i < 7; i++ )
{
answer[i] = CONVERSION_USA[initialType][i] * value;
}
}
public String getAnswer(int region, int initialType, int finalType, double value)
{
String answer = null;
switch(region)
{
case 0:
answer = Double.toString(CONVERSION_USA[initialType][finalType] * value);
break;
}
return answer;
}
public String toString()
{
String finalAnswer = "";
for(int i = 0; i < 7; i++ )
{
finalAnswer += answer[i] + " ";
}
return finalAnswer;
}
}
In this case i do not think that you need to use a handler.
Otherwise a proper way would be to do something on these lines:
Runnable r=new Runnable() {
#Override
public void run() {
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
}
};
handler.post(r);
i've looking for How to cancel my thread, found some answers but it didn't help me.
My app needs to go from 0-X and by pressing Cancel button the thread is canceled and update Atual Label value with the last counting number.
Again: I've found some examples and explications and didn't help me, so please, do not post another post example.
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class SwingWorker extends JFrame {
Thread worker=new Thread();
boolean parar=false;
int em;
public int quantos;
public int sleep;
private JLabel contador = new JLabel("0");
private JLabel statusLabel = new JLabel("N\u00E3o completado");
private JButton startButton = new JButton("Iniciar");
private JLabel atual = new JLabel("0");
JButton btnNewButton = new JButton("Cancelar");
JLabel lblltimoNmero = new JLabel("\u00DAltimo n\u00FAmero");
public SwingWorker(String title) {
super(title);
setTitle("Contador do n\u00FAmero!");
getContentPane().setLayout(null);
contador.setBounds(106, 97, 48, 37);
contador.setFont(new Font("serif", Font.BOLD, 28));
getContentPane().add(contador);
statusLabel.setBounds(76, 155, 139, 14);
getContentPane().add(statusLabel);
startButton.setBounds(35, 210, 79, 23);
getContentPane().add(startButton);
//Button cancelar
btnNewButton.setBounds(118, 210, 100, 23);
getContentPane().add(btnNewButton);
btnNewButton.setEnabled(false);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
parar=true;
atual.setText(""+(em-1));
//----------------------------------------
// Worker cancel action
//worker.cancel();
//-------------------------
}
});
lblltimoNmero.setBounds(10, 288, 110, 14);
getContentPane().add(lblltimoNmero);
atual.setFont(new Font("Serif", Font.BOLD, 28));
atual.setBounds(106, 269, 59, 37);
getContentPane().add(atual);
JButton btnQuantosNmeros = new JButton("Ir at\u00E9");
btnQuantosNmeros.setBounds(35, 244, 79, 23);
getContentPane().add(btnQuantosNmeros);
JButton btnSleepPor = new JButton("Sleep por");
btnSleepPor.setBounds(118, 244, 89, 23);
getContentPane().add(btnSleepPor);
btnSleepPor.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sleep =Integer.parseInt(JOptionPane.showInputDialog("Thread dormir por(ms): "));
startButton.setEnabled(true);
}
});
btnQuantosNmeros.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
quantos =Integer.parseInt(JOptionPane.showInputDialog("Ir até o número :"));
}
});
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.setEnabled(true);
start();
startButton.setEnabled(false);
}
});
setSize(244, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JOptionPane.showMessageDialog(null, "Clique em -Ir até- e em -Sleep por-");
}
private void start() {
worker = new Thread() {
public void run() {
if(quantos!=0){
for(int i=0; i<=quantos; i++) {
final int count = i;
em++;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
contador.setText(Integer.toString(count));
}
});
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
}}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusLabel.setText("Completo");
startButton.setEnabled(true);
atual.setText(Integer.toString( em-1 ));
em=0;
parar=false;
}
});
}
};
worker.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwingWorker("SwingWorker");
}
});
}
}
The correct way to use SwingWorker is to make a subclass of it and override its doInBackground method. See the tutorial for an example: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html, as well as the tutorial on canceling a SwingWorker: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/cancel.html.
You've created a subclass of JFrame and just named it SwingWorker, so I don't quite understand what you're trying to do. You should possibly find some tutorials on how inheritance works in Java, such as http://docs.oracle.com/javase/tutorial/java/IandI/index.html.
Can you help me to fix this code. It's not working working properly as I expected.
package javafxapplication2;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
class Person {
private StringProperty aliasName;
private StringProperty newPanelName;
private StringProperty newPanelDescription;
private ObservableList<Person> panels = FXCollections.observableArrayList();
public final void setAliasName(String value) {
aliasNameProperty().set(value);
}
public final String getAliasName() {
return aliasNameProperty().get();
}
public StringProperty aliasNameProperty() {
if (aliasName == null) {
aliasName = new SimpleStringProperty();
}
return aliasName;
}
public final void setNewPanelName(String value) {
newPanelNameProperty().set(value);
}
public final String getNewPanelName() {
return newPanelNameProperty().get();
}
public StringProperty newPanelNameProperty() {
if (newPanelName == null) {
newPanelName = new SimpleStringProperty();
}
return newPanelName;
}
public final void setNewPanelDescription(String value) {
newPanelDescriptionProperty().set(value);
}
public final String getNewPanelDescription() {
return newPanelDescriptionProperty().get();
}
public StringProperty newPanelDescriptionProperty() {
if (newPanelDescription == null) {
newPanelDescription = new SimpleStringProperty();
}
return newPanelDescription;
}
public ObservableList<Person> panelsProperty() {
return panels;
}
public Person(String alias, String newPanelName, String newPanelDescription) {
setAliasName(alias);
setNewPanelName(newPanelName);
setNewPanelDescription(newPanelDescription);
}
}
public class JavaFXApplication2 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("test");
Group root = new Group();
Scene scene = new Scene(root, 500, 250, Color.WHITE);
// create a grid pane
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(10);
gridpane.setVgap(10);
ObservableList<Person> leaders = FXCollections.observableArrayList();
leaders.add(new Person("test 1", "test 11", "test 111"));
leaders.add(new Person("test 2", "test 22", "test 222"));
leaders.add(new Person("test 3", "test 33", "test 333"));
leaders.add(new Person("test 4", "test 44", "test 444"));
final ListView<Person> leaderListView = new ListView<>(leaders);
leaderListView.setPrefWidth(450);
leaderListView.setPrefHeight(150);
//
leaderListView.setCellFactory(new Callback<ListView<Person>, ListCell<Person>>() {
#Override
public ListCell<Person> call(ListView<Person> param) {
final Label leadLbl = new Label();
final Tooltip tooltip = new Tooltip();
final ListCell<Person> cell = new ListCell<Person>() {
#Override
public void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
leadLbl.setText(item.getAliasName());
setText(item.getNewPanelName());// + " " + item.getNewPanelDescription());
tooltip.setText(item.getAliasName());
setTooltip(tooltip);
}
}
}; // ListCell
return cell;
}
}); // setCellFactory
// Double click
leaderListView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
}
}
});
gridpane.add(leaderListView, 0, 1);
// Buttons
// Button "Open"
Button btnYes = new Button("Open");
btnYes.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
leaderListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>() {
#Override
public void changed(ObservableValue<? extends Person> observable, Person oldValue, Person newValue) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
System.out.println("selection changed");
}
});
}
});
// Button "Cancel"
Button btnNo = new Button("Cancel");
btnNo.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
primaryStage.close();
}
});
HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().add(btnYes);
hbox.getChildren().add(btnNo);
gridpane.add(hbox, 0, 2);
root.getChildren().add(gridpane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
I want to select one row and then to open a new window when I click the button Select to open a new window. Can you help me to fix the code?
Replace the btnYes.setOnAction with the following :
btnYes.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
});
It should be this the action of the btnYes:
btnYes.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
});
(there might be an axtra braket, just edited online.)
Also, this is exactly the same code as in the list doubleclick event, might want to put it in a diferent method, so that you dont repeat code:
public void openNewWindow(){
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
My application uses JPA read data into TableView then modify and display them. The table refreshed modified record under JavaFx 2.0.3. Under JavaFx 2.1, 2.2, the table wouldn't refresh the update anymore. I found other people have similar issue. My plan was to continue using 2.0.3 until someone fixes the issue under 2.1 and 2.2. Now I know it is not a bug and wouldn't be fixed. Well, I don't know how to deal with this. Following are codes are modified from sample demo to show the issue. If I add a new record or delete a old record from table, table refreshes fine. If I modify a record, the table wouldn't refreshes the change until a add, delete or sort action is taken. If I remove the modified record and add it again, table refreshes. But the modified record is put at button of table. Well, if I remove the modified record, add the same record then move the record to the original spot, the table wouldn't refresh anymore. Below is a completely code, please shine some light on this.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
private TextField firtNameField = new TextField();
private TextField lastNameField = new TextField();
private TextField emailField = new TextField();
private Stage editView;
private Person fPerson;
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Person(String fName, String lName, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
private TableView<Person> table = new TableView<Person>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com"));
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(535);
stage.setHeight(535);
editView = new Stage();
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setMinWidth(150);
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setMinWidth(150);
TableColumn emailCol = new TableColumn("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("email"));
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
//--- create a edit button and a editPane to edit person
Button addButton = new Button("Add");
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
fPerson = null;
firtNameField.setText("");
lastNameField.setText("");
emailField.setText("");
editView.show();
}
});
Button editButton = new Button("Edit");
editButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (table.getSelectionModel().getSelectedItem() != null) {
fPerson = table.getSelectionModel().getSelectedItem();
firtNameField.setText(fPerson.getFirstName());
lastNameField.setText(fPerson.getLastName());
emailField.setText(fPerson.getEmail());
editView.show();
}
}
});
Button deleteButton = new Button("Delete");
deleteButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (table.getSelectionModel().getSelectedItem() != null) {
data.remove(table.getSelectionModel().getSelectedItem());
}
}
});
HBox addEditDeleteButtonBox = new HBox();
addEditDeleteButtonBox.getChildren().addAll(addButton, editButton, deleteButton);
addEditDeleteButtonBox.setAlignment(Pos.CENTER_RIGHT);
addEditDeleteButtonBox.setSpacing(3);
GridPane editPane = new GridPane();
editPane.getStyleClass().add("editView");
editPane.setPadding(new Insets(3));
editPane.setHgap(5);
editPane.setVgap(5);
Label personLbl = new Label("Person:");
editPane.add(personLbl, 0, 1);
GridPane.setHalignment(personLbl, HPos.LEFT);
firtNameField.setPrefWidth(250);
lastNameField.setPrefWidth(250);
emailField.setPrefWidth(250);
Label firstNameLabel = new Label("First Name:");
Label lastNameLabel = new Label("Last Name:");
Label emailLabel = new Label("Email:");
editPane.add(firstNameLabel, 0, 3);
editPane.add(firtNameField, 1, 3);
editPane.add(lastNameLabel, 0, 4);
editPane.add(lastNameField, 1, 4);
editPane.add(emailLabel, 0, 5);
editPane.add(emailField, 1, 5);
GridPane.setHalignment(firstNameLabel, HPos.RIGHT);
GridPane.setHalignment(lastNameLabel, HPos.RIGHT);
GridPane.setHalignment(emailLabel, HPos.RIGHT);
Button saveButton = new Button("Save");
saveButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (fPerson == null) {
fPerson = new Person(
firtNameField.getText(),
lastNameField.getText(),
emailField.getText());
data.add(fPerson);
} else {
int k = -1;
if (data.size() > 0) {
for (int i = 0; i < data.size(); i++) {
if (data.get(i) == fPerson) {
k = i;
}
}
}
fPerson.setFirstName(firtNameField.getText());
fPerson.setLastName(lastNameField.getText());
fPerson.setEmail(emailField.getText());
data.set(k, fPerson);
table.setItems(data);
// The following will work, but edited person has to be added to the button
//
// data.remove(fPerson);
// data.add(fPerson);
// add and remove refresh the table, but now move edited person to original spot,
// it failed again with the following code
// while (data.indexOf(fPerson) != k) {
// int i = data.indexOf(fPerson);
// Collections.swap(data, i, i - 1);
// }
}
editView.close();
}
});
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
editView.close();
}
});
HBox saveCancelButtonBox = new HBox();
saveCancelButtonBox.getChildren().addAll(saveButton, cancelButton);
saveCancelButtonBox.setAlignment(Pos.CENTER_RIGHT);
saveCancelButtonBox.setSpacing(3);
VBox editBox = new VBox();
editBox.getChildren().addAll(editPane, saveCancelButtonBox);
Scene editScene = new Scene(editBox);
editView.setTitle("Person");
editView.initStyle(StageStyle.UTILITY);
editView.initModality(Modality.APPLICATION_MODAL);
editView.setScene(editScene);
editView.close();
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.getChildren().addAll(label, table, addEditDeleteButtonBox);
vbox.setPadding(new Insets(10, 0, 0, 10));
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
}
See the answer to Updating rows in Tableview. Add these getters and it will just work.
Additionally since the data is an ObservableList which is set as items to tableView, any changes to this data list will be reflected to the table.getItems() too. Namely no need to table.setItems(data) again.
I have found a simple workaround for triggering the refresh of the TableView in JavaFX 2.1 TableView refresh items. It solved the issue for me.
Add this to your code:
tableView.getColumns().get(0).setVisible(false);
tableView.getColumns().get(0).setVisible(true);
looking into the TableView.java code, there's private refresh() which just executes
getProperties().put(TableViewSkinBase.REFRESH, Boolean.TRUE);
At last, the code below worked for me(Java8). (be careful, the constant's name is not REFRESH but RECREATE)
tableView.getProperties().put(TableViewSkinBase.RECREATE, Boolean.TRUE);
(reading javafx's code, this will force cell re-creation)
Notification-based updates of JavaFX controls typically require that the properties of the data model object backing your GUI meet the minimum definition for a JavaFX Bean.
The following exemplifies the minimum code needed in order for a JavaFX property to satisfy these requirements:
public class Client extends DB {
private IntegerProperty id = new SimpleIntegerProperty();
private StringProperty lastName = new SimpleStringProperty();
private StringProperty firstName = new SimpleStringProperty();
public final int getID() {return this.id.get(); }
void setID(int id) { this.id.set(id); }
public final IntegerProperty idProperty() { return this.id; }
public final String getLastName() { return this.lastName.get(); }
public final void setLastName(String ln) { this.lastName.set(ln); }
public final StringProperty lastNameProperty() { return this.lastName; }
public final String getFirstName() { return this.firstName.get(); }
public final void setFirstName(String fn) { this.firstName.set(fn); }
public final StringProperty firstNameProperty() { return this.firstName; }
:
:
}
Glancing over your code, it does not appear that your properties satisfy the requirements for a JavFX Bean. As such, automatic notification-based updates will not occur.
I have the same problem, and not being able to add SimpleStringProperty to the POJO's used by JPA makes this a bit problematic. But it seems to me that this should be fixable issue because I have noticed the following behavior:
In my application, clicking on a row in the table populates some text fields on the screen, that the user can then edit.
At that point the user can save the data, or create a new item with the same or changed data. If the user creates a new item, which is then inserted into the observable list that the tableview represents, the change is immediately reflected in the contents of the tableview. However if the user just saves the change the new data is not reflected in the table. To put the new data in the list I'm simply doing
trialList.set(currentIndex, tempTrial);
And here's what I think points to this as a fixable issue: if I scroll the affected row out of view on the table and then scroll it back, the 'new' value(s) are now presented.
Hopefully, this can be fixed. Sorry this isn't an answer, so to speak, but might provide some insight for a fix.
this worked for me
#FXML
private void refreshTableView()
{
firstNameCol.setVisible(false);
lastNameCol.setVisible(false);
emailCol.setVisible(false);
firstNameCol.setVisible(true);
lastNameCol.setVisible(true);
emailCol.setVisible(true);
}
I had the same problem and after some search this is my workaround. I found that if the columns are removed and then re-added the table is updated.
public static <T,U> void refreshTableView(final TableView<T> tableView, final List<TableColumn<T,U>> columns, final List<T> rows) {
if (tableView == null) {
throw new NullPointerException();
}
if (columns == null) {
throw new NullPointerException();
}
if (rows == null) {
throw new NullPointerException();
}
tableView.getColumns().clear();
tableView.getColumns().addAll(columns);
ObservableList<T> list = FXCollections.observableArrayList(rows);
tableView.setItems(list);
}
Example of usage:
refreshTableView(myTableView, Arrays.asList(col1, col2, col3), rows);