I am developing a download manager.I can not update label. I am trying to update label with downloading in run() method but exception occurred. How I update Label.Where I write code of updating label and ProgressBar.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;
import javafx.event.*;
import javafx.scene.image.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class DownloadFile implements Runnable
{
Thread thread;
private static final int BUFFER_SIZE=1024;
public final int DOWNLOADING=0;
public final int PAUSED=1;
public final int COMPLETE=2;
public final int CANCELLED=3;
public final int ERROR=4;
private URL url;
private int size;
private int downloaded;
private int status;
static int check=0;
Stage dStage;
Label fileNameLabel;
Label fileNameValueLabel;
Label statusLabel;
Label statusValueLabel;
Label fileSizeLabel;
Label fileSizeValueLabel;
Label downloadedLabel;
Label downloadedValueLabel;
Label speedLabel;
Label speedValueLabel;
Label timeRemainingLabel;
Label timeRemainingValueLabel;
ProgressBar downloadingProgressBar;
public void startStage()
{
dStage=new Stage();
dStage.setResizable(false);
dStage.getIcons().add(new Image("images\\webdownloadmanager.png"));
dStage.setTitle("Friends Download Manager");
BorderPane root=new BorderPane();
root.setPadding(new Insets(10, 10, 10, 10));
Scene dScene=new Scene(root,520,250);
dStage.setScene(dScene);
Label titleLabel=new Label(" Download Status ");
titleLabel.setStyle("-fx-background-color:#FFFFFF;");
GridPane gpCenter=new GridPane();
gpCenter.setPadding(new Insets(10, 10, 10, 10));
gpCenter.setStyle("-fx-background-color:#FFFFFF;");
fileNameLabel =new Label("File Name");
fileNameValueLabel=new Label();
statusLabel =new Label("Status");
statusValueLabel =new Label();
fileSizeLabel =new Label("File size");
fileSizeValueLabel =new Label();
downloadedLabel =new Label("Downloaded");
downloadedValueLabel =new Label();
speedLabel =new Label("Speed");
speedValueLabel =new Label();
timeRemainingLabel =new Label("Time Remaining ");
timeRemainingValueLabel =new Label();
gpCenter.add(fileNameLabel,0,0);
gpCenter.add(fileNameValueLabel,2,0);
gpCenter.add(statusLabel ,0,3);
gpCenter.add(statusValueLabel ,2,3);
gpCenter.add(fileSizeLabel ,0,4);
gpCenter.add(fileSizeValueLabel ,2,4);
gpCenter.add(downloadedLabel ,0,5);
gpCenter.add(downloadedValueLabel ,2,5);
gpCenter.add(speedLabel ,0,6);
gpCenter.add(speedValueLabel ,2,6);
gpCenter.add(timeRemainingLabel ,0,7);
gpCenter.add(timeRemainingValueLabel ,2,7);
AnchorPane anchorPaneBottom=new AnchorPane();
VBox vb=new VBox();
HBox progressBarHB=new HBox();
progressBarHB.setPadding(new Insets(10, 0, 30, 0));
downloadingProgressBar=new ProgressBar();
downloadingProgressBar.prefWidthProperty().bind(root.widthProperty().subtract(20));
progressBarHB.getChildren().add(downloadingProgressBar);
vb.getChildren().addAll(progressBarHB);
HBox labelHB=new HBox();
Label message=new Label("Whould you like to perform ?");
labelHB.getChildren().add(message);
HBox buttonHB=new HBox();
buttonHB.setSpacing(20);
Button startPauseButton=new Button("Start");
startPauseButton.setPrefWidth(80);
Button cancelButton=new Button("Cancel");
cancelButton.setPrefWidth(80);
buttonHB.getChildren().addAll(startPauseButton,cancelButton);
anchorPaneBottom.getChildren().addAll(vb,labelHB,buttonHB);
AnchorPane.setTopAnchor(buttonHB, 40.0);
AnchorPane.setRightAnchor(buttonHB,30.0);
AnchorPane.setLeftAnchor(labelHB,40.0);
AnchorPane.setTopAnchor(labelHB,40.0);
AnchorPane.setTopAnchor(vb, 0.0);
root.setTop(titleLabel);
root.setCenter(gpCenter);
root.setBottom(anchorPaneBottom);
dStage.show();
dStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent we)
{ /*
if(WebDownloadManager.check==0)
Platform.exit();
else
check--;
*/
}
});
}
public DownloadFile(URL url)
{
this.url=url;
size=-1;
downloaded=0;
status=DOWNLOADING;
startStage();
fileNameValueLabel.setText(getFileName(url).toString());
statusValueLabel.setText("Waiting..");
fileSizeValueLabel.setText(getSize()+"");
downloadedValueLabel.setText("0.00 MB ("+getProgress()+" %)");
speedValueLabel.setText("450.123 KB/sec");
timeRemainingValueLabel.setText("1 hr ");
download();
}
public String getUrl()
{
return url.toString();
}
public int getSize()
{
return size;
}
public float getProgress()
{
float tf=(downloaded/size)*100;
return tf;
}
public int getStatus()
{
return status;
}
public void pause()
{
status=PAUSED;
}
public void resume()
{
status=DOWNLOADING;
download();
}
public void cancel()
{
status=CANCELLED;
}
private void error()
{
status=ERROR;
}
private void download()
{
thread=new Thread(this);
thread.start();
}
private String getFileName(URL url)
{
String fileName=url.getFile();
String str=fileName.substring(fileName.lastIndexOf('/')+1).replace("%20"," ");
return str;
}
public void run()
{
RandomAccessFile file=null;
InputStream stream=null;
try
{
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestProperty("Range","bytes="+downloaded+"-");
conn.connect();
if(conn.getResponseCode()/100!=2)
{
error();
}
int contentLength=conn.getContentLength();
if(contentLength<1)
{
error();
}
if(size==-1)
{
size=contentLength;
}
file=new RandomAccessFile(getFileName(url),"rw");
file.seek(downloaded);
stream=conn.getInputStream();
while(status==DOWNLOADING)
{
statusValueLabel.setText("Running..");
byte buffer[];
if(size-downloaded>BUFFER_SIZE)
{
buffer=new byte[BUFFER_SIZE];
}
else
{
buffer=new byte[size-downloaded];
}
int read=stream.read(buffer);
if(read== -1)
{
break;
}
file.write(buffer,0,read);
downloaded+=read;
}
if(status==DOWNLOADING)
{
status=COMPLETE;
}
}
catch(Exception exp)
{
error();
System.out.println("Error :"+exp);
}
finally
{
if(file!=null)
{
try
{
file.close();
}
catch(Exception e)
{
}
}
if(stream!=null)
{
try
{
stream.close();
}
catch(Exception exp)
{
}
}
}
}
}
You cannot update JavaFX element outside FX threads. what you need to do is :
Platform.runLater(new Runnable(updateMethod());
Related
I would like to implement a frame where you can press a button to make a call, and then either the respondent, the manager or the director would respond to the call, and it would output on the screen who answered the call.
If an employee is not available, I would like to show on the console. So for example if respondent and manager are not available, I would like the output to look like this:
Respondent busy. Forwarding to manager.
Manager busy. Forwarding to Director.
Director answered the call.
With my implementations these messages are shown, but they are all showed instantly. I would like to set some waiting time between the messages, like:
shows message: "Manager is busy. Forwarding to director"
waits 2 seconds
shows message: "Director answered the call"
CallHandler.java:
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class CallHandler implements Runnable{
private ArrayList<Employee> employees = new ArrayList<>();
private MyFrame view;
public CallHandler(){
employees.add(new Respondent());
employees.add(new Manager());
employees.add(new Director());
view = new MyFrame(this);
}
public void dispatchCall() throws InterruptedException {
boolean dialing = true;
while(dialing) {
for (Employee employee : getAvailableEmployees()) {
Status status = employee.call();
if (status == Status.ANSWERED) {
(new Thread(employee)).start();
sendMessage(employee.getClass().getName() + " has answered the call.");
dialing = false;
break;
}
sendMessage(employee.getClass().getName() + " is busy. You will be redirected to the next available employee.");
}
if (dialing)
sendMessage("No one is available at the moment. Please wait...");
}
}
private void sendMessage(String msg) throws InterruptedException {
view.addMessage(msg);
}
private ArrayList<Employee> getAvailableEmployees(){
return employees.stream().filter(Employee::isFree).collect(Collectors.toCollection(ArrayList::new));
}
public static void main(String args[]){
CallHandler handler = new CallHandler();
}
#Override
public void run() {
try{
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException e) {
System.out.println("Call got interrupted");
}
}
}
MyFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class MyFrame extends JFrame implements Runnable {
private static final int WIDTH = 800;
private static final int HEIGHT = 500;
private static final int PANEL_WIDTH = 600;
private static final int PANEL_HEIGHT = 290;
private final JPanel panel = new JPanel();
private final ArrayList<JLabel> labels = new ArrayList<>();
private int rowIndex = 0;
private static final int ROWS = 17;
private CallHandler handler = null;
private Timer timer;
MyFrame(CallHandler callHandler) {
handler = callHandler;
this.setLayout(null);
setVisible(true);
setSize(WIDTH, HEIGHT);
add(panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBackground(Color.GREEN);
panel.setBounds(100, 50, PANEL_WIDTH, PANEL_HEIGHT);
JButton btn = new JButton("Make call");
btn.setBounds(350, 370, 100, 80);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
handler.dispatchCall();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
});
this.add(btn);
initiateRows();
}
public void addMessage(String msg) throws InterruptedException {
if (rowIndex < ROWS) {
getLabel(rowIndex).setText(msg);
rowIndex++;
} else {
System.out.println("removing first component");
removeComponent(0);
addRow(msg);
}
panel.updateUI();
// Thread.sleep(1000);
}
private void initiateRows() {
for (int i = 0; i < ROWS; i++) {
addRow("");
}
}
private void addRow(String msg) {
JLabel label = new JLabel(msg);
label.setAlignmentX(Component.CENTER_ALIGNMENT);
labels.add(label);
panel.add(label);
}
private JLabel getLabel(int i) {
return (JLabel) panel.getComponent(i);
}
private void removeComponent(int i) {
panel.remove(i);
}
public static void main(String args[]) {
MyFrame f = new MyFrame(new CallHandler());
}
#Override
public void run() {
try{
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException e) {
System.out.println("Call got interrupted");
}
}
}
I'm designing a JPanel in which there are some buttons which have their own action listeners and would do certain things when clicked (for example, one of them would remove the panel). In case the user closes the program, panels shouldn't be deleted and should be retrieved. for this purpose I serialize panels and deserialize them when needed. but the problem is listeners such as action listeners and mouse listeners wouldn't work when the panel is retrieved. is there any way to solve this problem? or is there any alternative to do the same thing without problem?
My panel code in case it's needed:
import jdk.internal.org.objectweb.asm.commons.SerialVersionUIDAdder;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.text.Format;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;
public class Download extends JPanel implements Serializable {
private String fileName;
private boolean removed = false;
private double downloadSpeed;
private double downloadedSize;
private double sizeOfFile;
LocalTime downloadTime;
LocalDate downloadDate;
private boolean checked = false;
private static final long serialVersionUID = 1113799434508676095L;
JLabel test = new JLabel("test");
public Download (MainPage c,URL url,LocalTime time,LocalDate date) {
setLayout(null);
downloadDate = date;
downloadTime = time;
fileName = url.getFile();
JCheckBox checkbox = new JCheckBox();
checkbox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
setChecked(true);
else
setChecked(false);
}
});
checkbox.setBackground(new Color(186,212,215));
checkbox.setBounds(95,42,17,15);
add(checkbox);
MouseAdapter a = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
setBackground(new Color(224,235,252));
checkbox.setBackground(new Color(224,235,252));
}
#Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
setBackground(new Color(186,212,255));
checkbox.setBackground(new Color(186,212,255));
}
};
UIManager.put("ProgressBar.background", new Color (235,255,255));
UIManager.put("ProgressBar.foreground", new Color (10,109,63));
UIManager.put("ProgressBar.selectionBackground", Color.RED);
UIManager.put("ProgressBar.selectionForeground", Color.GREEN);
setBackground(new Color(186,212,255));
setPreferredSize(new Dimension(600,100));
JPanel file = new JPanel();
/* test fileImg = new test("file.png");
fileImg.setBounds(10,10,40,50);
add(fileImg); */
JLabel fileNameLabel = new JLabel(fileName);
fileNameLabel.setBounds(100,5,400,15);
fileNameLabel.setForeground(new Color(109,111,114));
add(fileNameLabel);
JProgressBar jpb = new JProgressBar(0,100);
Random r = new Random();
jpb.setValue(r.nextInt(100));
jpb.setBounds(100,25,400,10);
JLabel progressBarValue = new JLabel("%" + jpb.getValue() + "");
progressBarValue.setBounds(510,18,25,20);
add(progressBarValue);
this.setBorder(BorderFactory.createMatteBorder(0,0,2,0,new Color(18,42,79)));
addMouseListener(a);
add(jpb);
JButton trash = new JButton(new ImageIcon("trash.png"));
trash.setBounds(130,40,25,25);
/* trash.setContentAreaFilled(false);
trash.setFocusPainted (false);
trash.setBorderPainted(false); */
trash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("text");
}
});
add(trash);
test.setBounds(180,40,25,25);
test.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
System.out.println("text");
}
});
add(test);
double lower = 0;
double upper = 999.99;
sizeOfFile = Math.random() * (upper - lower) + lower;
downloadSpeed = Math.random() * (upper - lower) + lower;
downloadedSize = jpb.getValue() * sizeOfFile / 100;
JLabel downloadSpeedLabel = new JLabel (String.format ("%.1fKbs",downloadSpeed));
JLabel downloadedSizeLabel = new JLabel (String.format ("%.1fMG / %.2fMG",downloadedSize,sizeOfFile));
downloadedSizeLabel.setForeground(new Color(109,111,114));
downloadSpeedLabel.setForeground(new Color(109,111,114));
downloadSpeedLabel.setBounds(250,35,100,30);
downloadedSizeLabel.setBounds(420,35,150,30);
add(downloadSpeedLabel); add(downloadedSizeLabel);
}
public boolean isRemoved() {
return removed;
}
public void setRemoved(boolean removed) {
this.removed = removed;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public double getDownloadSpeed() {
return downloadSpeed;
}
public void setDownloadSpeed(double downloadSpeed) {
this.downloadSpeed = downloadSpeed;
}
public double getDownloadedSize() {
return downloadedSize;
}
public void setDownloadedSize(double downloadedSize) {
this.downloadedSize = downloadedSize;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public double getSizeOfFile() {
return sizeOfFile;
}
public void setSizeOfFile(double size) {
this.sizeOfFile = size;
}
}
I have created this app with many other classes and it seems to run okay. However, when I finish the quiz, I cant add a button to restart the quiz? I have tried Jbutton and Jframe but I have no idea how to do it? Is there a simple code to add?
package sample;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javax.xml.bind.JAXBException;
public class Controller implements Initializable{
static int count = 1;
static int score=0;
static int multiplayerCounter = 1;
static int scoreOfComputer = 0;
static int scoreOfHuman = 0;
static String level;
static XmlToObject ob = new XmlToObject();
static List<String[]> questionsList = ob.readQuestionsAndAnswers("easy");
static boolean isCheatSet;
static boolean isSkipSet;
static String username;
public static String getLevel() {
return level;
}
public static void setLevel(String level) {
Controller.level = level;
}
#FXML
public RadioButton rdEasy;
#FXML
public RadioButton rdHard;
#FXML
public TextField txtAnswer;
#FXML
private Label lblMessage;
#FXML
private TextField txtUsername;
#FXML
private PasswordField txtPassword;
#FXML
private ListView lstHistoryScore;
#FXML
private Button btnNext;
#FXML
private Button btnCheat;
#FXML
private Button btnSkip;
#FXML
private Button btnStart;
#FXML
private Label headerCaption;
#FXML
private Label quizCaption;
#FXML
public Label question;
#FXML
public RadioButton optionOne;
#FXML
public RadioButton optionTwo;
#FXML
public Button btnPass;
#FXML
public RadioButton rdSinglePlayer;
#FXML
public ToggleGroup answerGroup;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML
private void btnLoginAction(ActionEvent actionEvent) throws IOException {
List<String[]> loginList = ob.readUserLogins();
for(String[] s:loginList ){
if(txtUsername.getText().equals(s[0]) && txtPassword.getText().equals(s[1])){
lblMessage.setText("Success");
((Node) (actionEvent.getSource() )).getScene().getWindow().hide();
Parent parent = FXMLLoader.load(getClass().getResource("/sample/Start.fxml"));
username = txtUsername.getText();
Stage stage = new Stage();
Scene scene = new Scene(parent);
stage.setScene(scene);
stage.show();
}else{
lblMessage.setText("Invalid username or password");
}
}
}
public void btnNextAction(ActionEvent actionEvent) throws IOException, JAXBException {
Stage stage = (Stage) ((Node)actionEvent.getSource()).getScene().getWindow();
int index = count - 1;
String[] criteria = questionsList.get(index);
if(getLevel().equals("hard")){
if (criteria[2].toLowerCase().equals(txtAnswer.getText().toLowerCase()) && !isCheatSet && !isSkipSet) {
score++;
}
if(count == 10) {
quizCaption.setText("Over");
question.setText("Your Score: " + score);
txtAnswer.setVisible(false);
btnNext.setVisible(false);
btnCheat.setVisible(false);
btnSkip.setVisible(false);
lstHistoryScore.setVisible(true);
lstHistoryScore.setItems(new XmlToObject().readXml());
ObjectToXML obx = new ObjectToXML();
obx.saveToXml(score);
}else {
txtAnswer.setText("");
String[] cr = questionsList.get(count);
quizCaption.setText("Quiz " + (count + 1));
question.setText(cr[1]);
isCheatSet = false;
isSkipSet = false;
count++;
}
}else {
RadioButton selectedRadio = (RadioButton) answerGroup.getSelectedToggle();
optionOne.setSelected(false);
optionTwo.setSelected(false);
if(!isSkipSet) {
if (getAnswer(criteria[4], selectedRadio.getText()) && !isCheatSet) {
score++;
}
}
if(count == 10) {
quizCaption.setText("Over");
question.setText("Your Score: " + score);
optionOne.setVisible(false);
optionTwo.setVisible(false);
btnNext.setVisible(false);
btnCheat.setVisible(false);
btnSkip.setVisible(false);
lstHistoryScore.setVisible(true);
lstHistoryScore.setItems(new XmlToObject().readXml());
ObjectToXML obx = new ObjectToXML();
obx.saveToXml(score);
}else {
String[] cr = questionsList.get(count);
quizCaption.setText("Quiz " + (count + 1));
question.setText(cr[1]);
optionOne.setText(cr[2]);
optionTwo.setText(cr[3]);
isCheatSet = false;
isSkipSet = false;
count++;
}
}
}
public void btnCheatAction(ActionEvent actionEvent) throws IOException, JAXBException {
isCheatSet = true;
int index = count -1;
if(getLevel().equals("hard")){
txtAnswer.setText(getCheatAnswerForHardLevel(index));
}else {
if(getCheatAnswer(index) == 1){
optionOne.setSelected(true);
}else {
optionTwo.setSelected(true);
}
}
Task<Void> sleeper = new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
return null;
}
};
sleeper.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
try {
btnNextAction(actionEvent);
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
});
new Thread(sleeper).start();
}
public void btnSkipAction(ActionEvent actionEvent) throws IOException, JAXBException {
isSkipSet = true;
btnNextAction(actionEvent);
}
public void setName(String name) {
quizCaption.setText(name);
}
public void btnStartAction(ActionEvent actionEvent) throws IOException, JAXBException {
if(rdSinglePlayer.isSelected()){
((Node) (actionEvent.getSource())).getScene().getWindow().hide();
if(rdHard.isSelected()) {
final FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample/SinglePlayerHardLevel.fxml"));
questionsList = ob.readQuestionsAndAnswers("hard");
String[] criteria = questionsList.get(0);
setLevel("hard");
loader.getNamespace().put("caption", ("Quiz"+ criteria[0]) );
loader.getNamespace().put("quiz", criteria[1]);
Parent root = loader.load();
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}else {
final FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample/SinglePlayerEasyLevel.fxml"));
String[] criteria = questionsList.get(0);
loader.getNamespace().put("caption", ("Quiz" + criteria[0]));
loader.getNamespace().put("quiz", criteria[1]);
loader.getNamespace().put("one", criteria[2]);
loader.getNamespace().put("two", criteria[3]);
Parent root = loader.load();
setLevel("easy");
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}else{
((Node) (actionEvent.getSource())).getScene().getWindow().hide();
final FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample/Multiplayer.fxml"));
String[] criteria = questionsList.get(0);
loader.getNamespace().put("player", "Human");
loader.getNamespace().put("caption", ("Quiz" + criteria[0]));
loader.getNamespace().put("quiz", criteria[1]);
loader.getNamespace().put("one", criteria[2]);
loader.getNamespace().put("two", criteria[3]);
Parent root = loader.load();
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
public void btnPassAction(ActionEvent actionEvent) {
RadioButton selectedRadio = (RadioButton) answerGroup.getSelectedToggle();
optionOne.setSelected(false);
optionTwo.setSelected(false);
int index = multiplayerCounter - 1;
if (multiplayerCounter == 10) {
question.setText("Computer score: " + scoreOfComputer);
quizCaption.setText("Your Score: " + scoreOfHuman);
optionOne.setVisible(false);
optionTwo.setVisible(false);
btnPass.setVisible(false);
}else {
String[] criteria = questionsList.get(index);
if (multiplayerCounter % 2 == 0) {
headerCaption.setText("Human");
optionOne.setDisable(false);
optionTwo.setDisable(false);
if (getAnswer(criteria[4], selectedRadio.getText())) {
scoreOfComputer++;
}
} else {
headerCaption.setText("Computer");
int ans = findRandomAnswer(Math.random());
if (ans == 1) {
optionOne.setSelected(true);
optionTwo.setDisable(true);
} else {
optionTwo.setSelected(true);
optionOne.setDisable(true);
}
if (getAnswer(criteria[4], selectedRadio.getText())) {
scoreOfHuman++;
}
}
String[] cr = questionsList.get(multiplayerCounter);
quizCaption.setText("Quiz " + cr[0]);
question.setText(cr[1]);
optionOne.setText(cr[2]);
optionTwo.setText(cr[3]);
multiplayerCounter++;
}
}
public boolean getAnswer(String answer, String quizOption){
if(answer.equals(quizOption)){
return true;
}else{
return false;
}
}
public int findRandomAnswer(double rand){
if(rand <= 0.7){
return 1;
}else{
return 2;
}
}
public int getCheatAnswer(int quizNumber){
String[] criteria = questionsList.get(quizNumber);
if(criteria[4].equals(criteria[2])){
return 1;
}else{
return 2;
}
}
public String getCheatAnswerForHardLevel(int quizNumber){
String[] criteria = questionsList.get(quizNumber);
return criteria[2];
}
public void rdSelectSinglePlayer(ActionEvent actionEvent) {
rdEasy.setVisible(true);
rdHard.setVisible(true);
btnStart.setDisable(false);
}
public void rdSelectMultiPlayer(ActionEvent actionEvent) {
rdEasy.setVisible(false);
rdHard.setVisible(false);
btnStart.setDisable(false);
}
}
I'm making a simple database application with JavaFX, but I can't figure out a way of making the Data class less verbose whilst still retaining the functionality of the Add Button.
Does anyone know a good way of streamlining the Data class, and keeping the Add Button, so that the user can input their own data?
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.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class DB extends Application {
private final TableView<Data> table = new TableView<>();
private final ObservableList<Data> data =
FXCollections.observableArrayList(
new Data("one", "one", "one", "one", "one", "one", "one", "one"));
private TableColumn<Data, String> [] tableCol;
private TextField [] textField;
private Button btn;
private HBox hbox;
private VBox vbox;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Custom DB");
stage.setMaximized(true);
table.setEditable(true);
setTableCol();
setCellValue();
addToTable();
setTextField();
setBtn();
addToHBox();
addToVBox();
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private void setTableCol()
{
tableCol = new TableColumn[8];
for(int i = 0; i<8; i++) {
tableCol[i] = new TableColumn();
tableCol[i].setMinWidth(100);
tableCol[i].setGraphic(new TextField("x"));
}
}
private void setCellValue()
{
tableCol[0].setCellValueFactory( new PropertyValueFactory<Data, String>("one"));
tableCol[1].setCellValueFactory( new PropertyValueFactory<Data, String>("two"));
tableCol[2].setCellValueFactory( new PropertyValueFactory<Data, String>("three"));
tableCol[3].setCellValueFactory( new PropertyValueFactory<Data, String>("four"));
tableCol[4].setCellValueFactory( new PropertyValueFactory<Data, String>("five"));
tableCol[5].setCellValueFactory( new PropertyValueFactory<Data, String>("six"));
tableCol[6].setCellValueFactory( new PropertyValueFactory<Data, String>("seven"));
tableCol[7].setCellValueFactory( new PropertyValueFactory<Data, String>("eight"));
}
private void addToTable()
{
table.setItems(data);
for(int i = 0; i<8; i++)
table.getColumns().addAll(tableCol[i]);
}
private void setTextField()
{
textField = new TextField[8];
for(int i = 0; i<8; i++) {
textField[i] = new TextField();
textField[i].setPromptText("Enter");
textField[i].setMaxWidth(tableCol[i].getPrefWidth());
}
}
private void setBtn()
{
btn = new Button("Add Data");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
data.add(new Data(
textField[0].getText(),
textField[1].getText(),
textField[2].getText(),
textField[3].getText(),
textField[4].getText(),
textField[5].getText(),
textField[6].getText(),
textField[7].getText()));
}
});
}
private void addToHBox()
{
hbox = new HBox();
hbox.setSpacing(20);
for(int i = 0; i<8; i++)
hbox.getChildren().addAll(textField[i]);
hbox.getChildren().addAll(btn);
}
private void addToVBox()
{
vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(table, hbox);
}
public static class Data {
private final SimpleStringProperty one;
private final SimpleStringProperty two;
private final SimpleStringProperty three;
private final SimpleStringProperty four;
private final SimpleStringProperty five;
private final SimpleStringProperty six;
private final SimpleStringProperty seven;
private final SimpleStringProperty eight;
private Data(String a, String b, String c, String d, String e, String f, String g, String h)
{
this.one = new SimpleStringProperty(a);
this.two = new SimpleStringProperty(b);
this.three = new SimpleStringProperty(c);
this.four = new SimpleStringProperty(d);
this.five = new SimpleStringProperty(e);
this.six = new SimpleStringProperty(f);
this.seven = new SimpleStringProperty(g);
this.eight = new SimpleStringProperty(h);
}
public String getOne()
{
return one.get();
}
public void setOne(String fName)
{
one.set(fName);
}
public String getTwo()
{
return two.get();
}
public void setTwo(String fName) {
two.set(fName);
}
public String getThree()
{
return three.get();
}
public void setThree(String fName)
{
three.set(fName);
}
public String getFour()
{
return four.get();
}
public void setFour(String fName)
{
four.set(fName);
}
public String getFive()
{
return five.get();
}
public void setFive(String fName)
{
five.set(fName);
}
public String getSix()
{
return six.get();
}
public void setSix(String fName)
{
six.set(fName);
}
public String getSeven()
{
return seven.get();
}
public void setSeven(String fName)
{
seven.set(fName);
}
public String getEight()
{
return eight.get();
}
public void setEight(String fName)
{
eight.set(fName);
}
}
}
I am building a desktop app using javafx, I am downloading a file around 500 MB using ftp. I need to show the progress bar with % while downloading is in progress. I also need to give a option to cancel a ongoing downloading process.
I want the progress bar when the download button is clicked and it show the download progress and if I cancel downloading should stop.
This is my code to download file.
downloadButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// TODO Auto-generated method stub
FTPClient ftpClient = new FTPConnection().makeConnection();
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
success = ftpClient.changeWorkingDirectory(PATH + preset + "/" + file_to_download + offset);
System.out.println("Download Path:-" + PATH + preset + "/" + file_to_download + offset);
if (!success) {
System.out.println("Could not changed the directory to RIBS");
return;
} else {
System.out.println("Directory changed to RIBS");
}
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
if (file.getName().contains(".zip")) {
dfile = file.getName();
}
}
DirectoryChooser dirChooser = new DirectoryChooser();
primaryStage = (Stage) tableView.getScene().getWindow();
primaryStage.setTitle("Background Processes");
File chosenDir = dirChooser.showDialog(primaryStage);
System.out.println(chosenDir.getAbsolutePath());
Task task = new Task<Void>() {
#Override
public Void call() throws IOException {
try {
output = new FileOutputStream(chosenDir.getAbsolutePath() + "/" + dfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ftpClient.sendNoOp();
ftpClient.setConnectTimeout(1000);
int filesize = 0;
if (ftpClient.retrieveFile(dfile, output) == true) {
downloadButton.setDisable(true);
dfile.length();
System.out.println("FILE:LENGTH" + dfile.length());
}
// updateProgress(outByte, inputByte);
return null;
}
};
final Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(primaryStage);
final ProgressBar progressBar = new ProgressBar(0);
final Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
copyWorker.cancel(true);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
System.out.println("cancelled.");
dialog.close();
}
});
final Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialog.close();
}
});
cancelButton.setDisable(false);
closeButton.setDisable(true);
VBox dialogVbox = new VBox();
VBox.setMargin(progressBar, new Insets(10, 10, 10, 10));
VBox.setMargin(cancelButton, new Insets(10, 10, 10, 10));
dialogVbox.setAlignment(Pos.CENTER);
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(cancelButton, closeButton);
dialogVbox.getChildren().addAll(progressBar, hBox);
Scene dialogScene = new Scene(dialogVbox, 160, 100);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setResizable(false);
dialog.setScene(dialogScene);
dialog.setOnShown(e -> {
progressBar.setProgress(0);
copyWorker = createWorker();
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(copyWorker.progressProperty());
copyWorker.messageProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
// TODO: handle succeeded & failed depending on your needs
EventHandler doneHandler = new EventHandler() {
#Override
public void handle(Event event) {
cancelButton.setDisable(true);
closeButton.setDisable(false);
}
};
copyWorker.setOnSucceeded(doneHandler);
copyWorker.setOnFailed(doneHandler);
new Thread(copyWorker).start();
});
dialog.show();
// end
new Thread(task).start();
if (output != null) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
In reference to my question How to show a progress bar while downloading in javafx
I have moved my download code into a different background thread but I am not able to figure out how to display the progress bar.
The example code already provided you a progress bar. It's just like any other node. You can put it wherevery you want. Here's an example about putting it into a dialog:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
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.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
// source: http://www.java2s.com/Code/Java/JavaFX/ProgressBarandBackgroundProcesses.htm
// http://stackoverflow.com/questions/22166610/how-to-create-a-popup-windows-in-javafx
public class ProgressTask extends Application {
Task copyWorker;
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Background Processes");
Group root = new Group();
Scene scene = new Scene(root, 330, 120, Color.WHITE);
BorderPane mainPane = new BorderPane();
root.getChildren().add(mainPane);
final Label label = new Label("Files Transfer:");
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(label);
mainPane.setTop(hb);
final Button startButton = new Button("Start");
startButton.setText("Start");
startButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(primaryStage);
final ProgressBar progressBar = new ProgressBar(0);
final Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
copyWorker.cancel(true);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
System.out.println("cancelled.");
dialog.close();
}
});
final Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialog.close();
}
});
cancelButton.setDisable(false);
closeButton.setDisable(true);
VBox dialogVbox = new VBox();
VBox.setMargin(progressBar, new Insets(10, 10, 10, 10));
VBox.setMargin(cancelButton, new Insets(10, 10, 10, 10));
dialogVbox.setAlignment(Pos.CENTER);
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(cancelButton, closeButton);
dialogVbox.getChildren().addAll(progressBar, hBox);
Scene dialogScene = new Scene(dialogVbox, 160, 100);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setResizable(false);
dialog.setScene(dialogScene);
dialog.setOnShown(e -> {
progressBar.setProgress(0);
copyWorker = createWorker();
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(copyWorker.progressProperty());
copyWorker.messageProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
// TODO: handle succeeded & failed depending on your needs
EventHandler doneHandler = new EventHandler() {
#Override
public void handle(Event event) {
cancelButton.setDisable(true);
closeButton.setDisable(false);
}
};
copyWorker.setOnSucceeded(doneHandler);
copyWorker.setOnFailed(doneHandler);
new Thread(copyWorker).start();
});
dialog.show();
}
});
final HBox hb2 = new HBox();
hb2.setSpacing(5);
hb2.setAlignment(Pos.CENTER);
hb2.getChildren().addAll(startButton);
mainPane.setBottom(hb2);
primaryStage.setScene(scene);
primaryStage.show();
}
public Task createWorker() {
return new Task() {
#Override
protected Object call() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
updateMessage(((i + 1) * 1000) + " milliseconds");
updateProgress(i + 1, 10);
}
return true;
}
};
}
}