JavaFX begginer's simple calculator event handling - java

Hey I'm a begginer at java and i've only been doing this for a short period of time, anyways for my final project in java basics i need to make a simple calculator with a gui, i thought it won't be that hard but i was kinda wrong :P i have managed to do the most (i think) but am stuck atm with the event handling for the operations and setting the value to calculate, here is my code and could you please give me suggestions or tips on how to do it :D
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.WritableObjectValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Calculator extends Application {
private DoubleProperty value = new SimpleDoubleProperty();
#Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets ( 30 , 20 , 30 , 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
TextField Rezultat = new TextField();
Rezultat.setEditable(false);
Rezultat.setAlignment(Pos.CENTER);
Rezultat.setMinSize(336, 40);
Rezultat.textProperty().bind(Bindings.format("%.0f" , value));
pane.getChildren().add(Rezultat);
Button sedmica = new Button("7");
Button osmica = new Button("8");
Button devetka = new Button("9");
Button plus = new Button("+");
sedmica.setMinSize(80, 80);
osmica.setMinSize(80, 80);
devetka.setMinSize(80, 80);
plus.setMinSize(80, 80);
pane.getChildren().add(sedmica);
sedmicaHandler handler7 = new sedmicaHandler();
sedmica.setOnAction(handler7);
pane.getChildren().add(osmica);
osmicaHandler handler8 = new osmicaHandler();
osmica.setOnAction(handler8);
pane.getChildren().add(devetka);
devetkaHandler handler9 = new devetkaHandler();
devetka.setOnAction(handler9);
pane.getChildren().add(plus);
plusHandler handlerplus = new plusHandler();
plus.setOnAction(handlerplus);
Button cetvorka = new Button("4");
Button petica = new Button("5");
Button sestica = new Button("6");
Button minus = new Button("-");
cetvorka.setMinSize(80, 80);
petica.setMinSize(80, 80);
sestica.setMinSize(80, 80);
minus.setMinSize(80, 80);
pane.getChildren().add(cetvorka);
cetvorkaHandler handler4 = new cetvorkaHandler();
cetvorka.setOnAction(handler4);
pane.getChildren().add(petica);
peticaHandler handler5 = new peticaHandler();
petica.setOnAction(handler5);
pane.getChildren().add(sestica);
sesticaHandler handler6 = new sesticaHandler();
sestica.setOnAction(handler6);
pane.getChildren().add(minus);
minusHandler handlerminus = new minusHandler();
minus.setOnAction(handlerminus);
Button trica = new Button("3");
Button dvica = new Button("2");
Button jedinica = new Button("1");
Button puta = new Button("*");
trica.setMinSize(80, 80);
dvica.setMinSize(80, 80);
jedinica.setMinSize(80, 80);
puta.setMinSize(80, 80);
pane.getChildren().add(jedinica);
jedinicaHandler handler1 = new jedinicaHandler();
jedinica.setOnAction(handler1);
pane.getChildren().add(dvica);
dvicaHandler handler2 = new dvicaHandler();
dvica.setOnAction(handler2);
pane.getChildren().add(trica);
tricaHandler handler3 = new tricaHandler();
trica.setOnAction(handler3);
pane.getChildren().add(puta);
putaHandler handlerputa = new putaHandler();
puta.setOnAction(handlerputa);
Button nula = new Button("0");
Button jednako = new Button("=");
Button podijeljeno = new Button("/");
Button EE = new Button ("EE");
nula.setMinSize(80, 80);
jednako.setMinSize(80, 80);
podijeljeno.setMinSize(80, 80);
EE.setMinSize(80, 80);
pane.getChildren().add(EE);
EEHandler handlerEE = new EEHandler();
EE.setOnAction(handlerEE);
pane.getChildren().add(nula);
nulaHandler handler0 = new nulaHandler();
nula.setOnAction(handler0);
pane.getChildren().add(jednako);
jednakoHandler handlerjednako = new jednakoHandler();
jednako.setOnAction(handlerjednako);
pane.getChildren().add(podijeljeno);
podijeljenoHandler handlerpodijeljeno = new podijeljenoHandler();
podijeljeno.setOnAction(handlerpodijeljeno);
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main (String[] args) {
Application.launch(args);
}
}
class nulaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
value.set(0);
}
}
class jedinicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("1");
}
}
class dvicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("2");
}
}
class tricaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("3");
}
}
class cetvorkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("4");
}
}
class peticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("5");
}
}
class sesticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("6");
}
}
class sedmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("7");
}
}
class osmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("8");
}
}
class devetkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("9");
}
}
class plusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("+");
}
}
class minusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("-");
}
}
class putaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("*");
}
}
class podijeljenoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("/");
}
}
class jednakoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("=");
}
}
class EEHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("EE");
}
}
My handlers are just basic ones, they print the number into the console so you can disregard them, i saw some examples with the value.set commands should i go with them or ? please help deadline is in 2 weeks. Thanks a lot

I will not do the homework for you, but just a few tips:
variable-names should start with a lowercase letter (TextField rezultat, not Rezultat)
think about what exactly you expect to happen when you press the buttons:
what should your calculator do, if you press 5 '-' '+' 55. should it subtract or add 55 from 5)
do you want to calculate more than one operation? (5+5+5+5/5)
what about decimal numbers? (you can not fill them in, at your current design)
And you do nearly the same thing for every button.(or at least for 10 buttons you have the same logic)
you can create your application in a loop:
public class Calculator extends Application {
private TextField textField = new TextField();
#Override
public void start(Stage primaryStage) {
List<String> buttons = Arrays.asList("7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", "=", "/", "EE");
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(30, 20, 30, 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
textField.setEditable(false);
textField.setAlignment(Pos.CENTER);
textField.setMinSize(336, 40);
// Rezultat.textProperty().bind(Bindings.format("%.0f", value));
pane.getChildren().add(textField);
for (String button : buttons) {
Button b = new Button(button);
b.setMinSize(80, 80);
pane.getChildren().add(b);
b.setOnAction((e) -> doSomething(b.getText()));
}
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void doSomething(String text) {
if (text.equalsIgnoreCase("=")) {
// Calc
}
else if (text.equalsIgnoreCase("EE")) {
// EE
} else if (text.equalsIgnoreCase("+") || text.equalsIgnoreCase("-") || text.equalsIgnoreCase("*") || text.equalsIgnoreCase("/")) {
// + - * /
}
// ....
else {
// numeric
textField.appendText(text);
}
}
public static void main(String[] args) {
Application.launch(args);
}
}

public class View extends Application{
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage){
primaryStage.setTitle("Calculator");
GridPane root = new GridPane();
Label textBox1 = new Label("Text1");
root.add(textBox1, 0, 0, 5, 1);
Label textBox2 = new Label("Text2");
root.add(textBox2, 0, 1, 5, 1);
textBox1.setId("lblTextBox1");
textBox2.setId("lblTextBox2");
Button btn0 = new Button("0");
Button btn1 = new Button("1");
Button btn2 = new Button("2");
Button btn3 = new Button("3");
Button btn4 = new Button("4");
Button btn5 = new Button("5");
Button btn6 = new Button("6");
Button btn7 = new Button("7");
Button btn8 = new Button("8");
Button btn9 = new Button("9");
btn0.setId("btn0");
btn1.setId("btn1");
btn2.setId("btn2");
btn3.setId("btn3");
btn4.setId("btn4");
btn5.setId("btn5");
btn6.setId("btn6");
btn7.setId("btn7");
btn8.setId("btn8");
btn9.setId("btn9");
Button btnDot = new Button(".");
Button btnPlus = new Button("+");
Button btnMinus = new Button("-");
Button btnTimes = new Button("*");
Button btnDivide = new Button("/");
Button btnEquals = new Button("=");
Button btnMC = new Button("MC");
Button btnMR = new Button("MR");
Button btnMS = new Button("MS");
Button btnMPlus = new Button("M+");
Button btnMMinus = new Button("M-");
Button btnBack = new Button("<=");
Button btnCE = new Button("CE");
Button btnC = new Button("C");
Button btnPlusOrMinus = new Button("+/-");
Button btnSqrt = new Button("sqrt");
Button btnPercentage= new Button("%");
Button btn1OverX = new Button("1/x");
btnPlus.setId("btnPlus");
btnTimes.setId("btnTimes");
btnDot.setId("btnDot");
btnEquals.setId("btnEquals");
btnC.setId("btnClear");
btn0.setMaxHeight(Double.MAX_VALUE);
btn0.setMaxWidth(Double.MAX_VALUE);
btn1.setMaxHeight(Double.MAX_VALUE);
btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxHeight(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);
btn3.setMaxHeight(Double.MAX_VALUE);
btn3.setMaxWidth(Double.MAX_VALUE);
btn4.setMaxHeight(Double.MAX_VALUE);
btn4.setMaxWidth(Double.MAX_VALUE);
btn5.setMaxHeight(Double.MAX_VALUE);
btn5.setMaxWidth(Double.MAX_VALUE);
btn6.setMaxHeight(Double.MAX_VALUE);
btn6.setMaxWidth(Double.MAX_VALUE);
btn7.setMaxHeight(Double.MAX_VALUE);
btn7.setMaxWidth(Double.MAX_VALUE);
btn8.setMaxHeight(Double.MAX_VALUE);
btn8.setMaxWidth(Double.MAX_VALUE);
btn9.setMaxHeight(Double.MAX_VALUE);
btn9.setMaxWidth(Double.MAX_VALUE);
btnEquals.setMaxHeight(Double.MAX_VALUE);
btnEquals.setMaxWidth(Double.MAX_VALUE);
btnMC.setMaxHeight(Double.MAX_VALUE);
btnMC.setMaxWidth(Double.MAX_VALUE);
btnMMinus.setMaxHeight(Double.MAX_VALUE);
btnMMinus.setMaxWidth(Double.MAX_VALUE);
btnPlusOrMinus.setMaxHeight(Double.MAX_VALUE);
btnPlusOrMinus.setMaxWidth(Double.MAX_VALUE);
btnPercentage.setMaxHeight(Double.MAX_VALUE);
btnPercentage.setMaxWidth(Double.MAX_VALUE);
btnSqrt.setMaxHeight(Double.MAX_VALUE);
btnSqrt.setMaxWidth(Double.MAX_VALUE);
btn1OverX.setMaxHeight(Double.MAX_VALUE);
btn1OverX.setMaxWidth(Double.MAX_VALUE);
btnPlus.setMaxHeight(Double.MAX_VALUE);
btnPlus.setMaxWidth(Double.MAX_VALUE);
btnMinus.setMaxHeight(Double.MAX_VALUE);
btnMinus.setMaxWidth(Double.MAX_VALUE);
btnTimes.setMaxHeight(Double.MAX_VALUE);
btnTimes.setMaxWidth(Double.MAX_VALUE);
btnDivide.setMaxHeight(Double.MAX_VALUE);
btnDivide.setMaxWidth(Double.MAX_VALUE);
btnCE.setMaxHeight(Double.MAX_VALUE);
btnCE.setMaxWidth(Double.MAX_VALUE);
btnC.setMaxHeight(Double.MAX_VALUE);
btnC.setMaxWidth(Double.MAX_VALUE);
btnDot.setMaxHeight(Double.MAX_VALUE);
btnDot.setMaxWidth(Double.MAX_VALUE);
root.add(btnMC,0,1);
root.add(btnMR,1,1);
root.add(btnMS,2,1);
root.add(btnMPlus,3,1);
root.add(btnMMinus,4,1);
root.add(btnBack,0,2);
root.add(btnCE,1,2);
root.add(btnC,2,2);
root.add(btnPlusOrMinus,3,2);
root.add(btnSqrt,4,2);
root.add(btn7,0,3);
root.add(btn8,1,3);
root.add(btn9,2,3);
root.add(btnDivide,3,3);
root.add(btnPercentage,4,3);
root.add(btn4,0,4);
root.add(btn5,1,4);
root.add(btn6,2,4);
root.add(btnTimes,3,4);
root.add(btn1OverX,4,4);
root.add(btn1,0,5);
root.add(btn2,1,5);
root.add(btn3,2,5);
root.add(btnMinus,3,5);
root.add(btnEquals,4,5,1,2);
root.add(btn0,0,6,2,1);
root.add(btnDot,2,6);
root.add(btnPlus,3,6);
root.setVgap(5);
root.setHgap(5);
root.setPadding(new Insets(5,5,5,5));
primaryStage.setScene(new Scene(root));
primaryStage.show();
Controller controller = new Controller(primaryStage.getScene());
}
}
public class Model {
SimpleDoubleProperty totalResult = new SimpleDoubleProperty(0);
SimpleDoubleProperty curNumber = new SimpleDoubleProperty(0);
SimpleStringProperty stringDisplayed = new SimpleStringProperty();
String operatorPressed = "";
Boolean isDecimal = false;
int decimalCouter = 0;
public void plusOperator(){
calculate();
operatorPressed = "+";
}
public void calculate(){
switch (operatorPressed){
case "+" :
totalResult.set(totalResult.get()+ curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" + " +curNumber.get());
break;
case "*" :
totalResult.set(totalResult.get()*curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" * " +curNumber.get());
break;
default:
totalResult.set(curNumber.get());
stringDisplayed.set(curNumber.get()+"");
}
curNumber.set(0);
operatorPressed = "";
isDecimal = false;
decimalCouter = 0;
}
public void multiplyOperator(){
calculate();
operatorPressed = "*";
}
public void equalsOperator(){
calculate();
curNumber.setValue(totalResult.get());
totalResult.set(0);
}
public void clearOperator(){
totalResult.setValue(0);
curNumber.setValue(0);
stringDisplayed.set("");
decimalCouter = 0;
isDecimal = false;
}
public void pressedNumber(int number){
if(!isDecimal){
curNumber.setValue(curNumber.get()*10+number);
}
else{
decimalCouter++;
Double tempCurrentNum = curNumber.get();
tempCurrentNum = tempCurrentNum*Math.pow(10,decimalCouter);
tempCurrentNum = tempCurrentNum+number;
tempCurrentNum = tempCurrentNum*Math.pow(10,-decimalCouter);
curNumber.set(tempCurrentNum);
}
}
public void dotOperator(){
isDecimal = true;
}
}
public class Controller {
Model newModel = new Model();
Controller(Scene scene){
Button btnPlus, btnTimes, btnEquals, btnClear, btnDot;
Label textBox1, textBox2;
for(int ii=0;ii<=9;ii++){
Button button = (Button)scene.lookup("#btn"+ii);
int finalIi = ii;
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
pressedNumber(finalIi);
}
});
}
btnPlus = (Button)scene.lookup("#btnPlus");
btnTimes = (Button)scene.lookup("#btnTimes");
btnEquals = (Button)scene.lookup("#btnEquals");
btnDot = (Button)scene.lookup("#btnDot");
btnClear = (Button)scene.lookup("#btnClear");
textBox1 = (Label)scene.lookup("#lblTextBox1");
textBox2 = (Label)scene.lookup("#lblTextBox2");
btnPlus.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
plusOperator();
}
});
btnTimes.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
multiplyOperator();
}
});
btnEquals.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
equalsOperator();
}
});
btnClear.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
clearOperator();
}
});
btnDot.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dotOperator();
}
});
textBox1.textProperty().bind(newModel.stringDisplayed);
textBox2.textProperty().bind(newModel.curNumber.asString());
}
public void pressedNumber(int number){
newModel.pressedNumber(number);
}
public void plusOperator(){
newModel.plusOperator();
}
public void multiplyOperator(){
newModel.multiplyOperator();
}
public void equalsOperator(){
newModel.equalsOperator();
}
public void clearOperator(){
newModel.clearOperator();
}
public void dotOperator(){
newModel.dotOperator();
}
}

Related

Counting clicks in Java

introduceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
int agex = Integer.parseInt(datafield.getText());
String box[] = {"paws quantity", "tail(cm)","paws qy"};
ArrayList<Integer> objdata = new ArrayList<Integer>();
for(int z = 0; z < 3;){
introduceButton
txtvar.setText(box[z]);
if (introduceButton.getModel().isEnabled() == true){
z++;
}
}
}
});
Hey guys, I try to count step by step how many times the button was pressed, to later navigate in an array.
The problem is that the variable z is not incrementing itself only by 1 after the button was clicked once but it reaches its max instantly after the first click. How can I fix it?
As well I tried to make a class with method counter but it the value remains 0:
class click{
int _incr;
public click(int incr){
_incr = incr;
}
public int count(){
_incr++;
return _incr;
}
}
...
introduceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
int agex = Integer.parseInt(datafield.getText());
String box[] = {"paws quantity", "tail(cm)","paws qy"};
ArrayList<Integer> objdata = new ArrayList<Integer>();
click clck = new click(0);
txtvar.setText(Integer.toString(clck._incr));
/*for(int z = 0; z < 3;){
txtvar.setText(box[z]);
if(introduceButton.getModel().isEnabled() == true){
z++;
}
}*/
objdata.add(agex);
dog abstractdog = new dog(agex, agex, agex);
}
});
I made a example code.
Please have a look at it:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CountClick {
static int clicks = 0;
public static void main(String[] args) {
Frame f = new Frame("Button Example");
Button btn = new Button("Click me");
btn.setBounds(50, 100, 80, 30);
f.add(btn);
// set size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// add listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// increase click int
clicks++;
// print clicks
System.out.println(clicks);
}
});
}
}
Note that the code in "addActionListener" is triggered each time you press the button. Therefore, unnecessary operations in it should be avoided. Initialisations should also be used with care in the "addActionListener" method.
Edit:
If you want to have a separate click class you can have a look at following code example:
class Click {
private int click = 0;
public void increaseClick() {
click++;
}
public int getClick() {
return click;
}
}
public class CountClicks {
public static void main(String[] args) {
Frame f = new Frame("Button Example");
Button btn = new Button("Click me");
btn.setBounds(50, 100, 80, 30);
f.add(btn);
// set size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
Click click = new Click();
// add listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// increase click int
click.increaseClick();
// print clicks
System.out.println(click.getClick());
}
});
}
}

How to add progressbar to Javafx

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;
}
};
}
}

Not allowing draw on button in JavaFX

I am new to JavaFX.
Please have a look at attached image where i want to restrict drawing on button.
And please also suggest me for printing to printer.
(In swing, it is possible with PrintJob and Toolkit class)
Below is my code :
public class PrintScribble extends Application {
private short last_x = 0, last_y = 0; // last click posistion
private Vector lines = new Vector(256, 256); // store the scribble
private Properties printprefs = new Properties(); // store user preferences
private Path path;
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PrintScribble");
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
BorderPane bp = new BorderPane();
bp.setPadding(new Insets(10, 10, 10, 10));
bp.setMinWidth(scene.getWidth());
Button b = new Button("Print");
bp.setRight(b);
root.getChildren().add(bp);
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Printer call");
//print();
}
});
path = new Path();
scene.setOnMouseClicked(mouseHandler);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMouseEntered(mouseHandler);
scene.setOnMouseExited(mouseHandler);
scene.setOnMouseMoved(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
root.getChildren().add(path);
primaryStage.setScene(scene);
primaryStage.show();
}
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
path.getElements()
.add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED) {
path.getElements()
.add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
}
};
/**
* The main method. Create a PrintScribble() object and away we go!
*/
public static void main(String[] args) {
launch(args);
}
}
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
path.getElements()
.add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED) {
path.getElements()
.add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
// Here is an answer
path.toBack();
}

ArrayList to store actions performed when button is clicked

I am having a lot of difficulty with my arrayList. I have got three buttons (in my jPanelBottom page) and when I click on the Start Button, every action i do from then on in (Selecting options from a menu or moving the jSlider) is supposed to be recorded. One I click the Stop button, it is supposed to stop recording and once I click on the Play button, every action I have done is supposed to be output to the screen. I have no idea how to do this.
I will attach some of my classes so you are able to see.
Here is my JPanelBottom page that contains everything ~I have created and my change event (for the jSlider)
public class jPanelBottom extends javax.swing.JPanel {
private JTextField jtfBoundaryLength, jtfArea;
private JSlider jsShapes;
private JLabel jLabelBoundaryLength, jLabelArea, jLabelSlider;
private JButton jbStart, jbStop, jbPlay;
//private JPanel jpBottom;
public jPanelBottom() {
initComponents();
//JSlider jsShapes = new JSlider();
jsShapes = new javax.swing.JSlider();
jsShapes.setMajorTickSpacing(10);
jsShapes.setPaintLabels(true);
jsShapes.setPaintTicks(true);
jsShapes.setSize(300, 100);
this.add(jsShapes);
jsShapes.addChangeListener(new event());
jtfBoundaryLength = new JTextField();
jtfBoundaryLength.setSize(100, 25);
jtfBoundaryLength.setLocation(550, 30);
this.add(jtfBoundaryLength);
jLabelBoundaryLength = new JLabel();
jLabelBoundaryLength.setText("Boundary Length: ");
jLabelBoundaryLength.setSize(130, 25);
jLabelBoundaryLength.setLocation(400, 30);
this.add(jLabelBoundaryLength);
jtfArea = new JTextField();
jtfArea.setSize(100, 25);
jtfArea.setLocation(550, 60);
this.add(jtfArea);
jLabelArea = new JLabel();
jLabelArea.setText("Area: ");
jLabelArea.setSize(100, 25);
jLabelArea.setLocation(400, 60);
this.add(jLabelArea);
jLabelSlider = new JLabel();
jLabelSlider.setText("Select the size please");
jLabelSlider.setSize(150, 150);
jLabelSlider.setLocation(85, 30);
this.add(jLabelSlider);
jbStart = new JButton();
jbStart.setText("Start");
jbStart.setSize(80, 25);
jbStart.setLocation(400, 95);
this.add(jbStart);
jbStop = new JButton();
jbStop.setText("Stop");
jbStop.setSize(80, 25);
jbStop.setLocation(500, 95);
this.add(jbStop);
jbPlay = new JButton();
jbPlay.setText("Play");
jbPlay.setSize(80, 25);
jbPlay.setLocation(600, 95);
this.add(jbPlay);
}
public class event implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
try {
if (MyFrame.shape1 == null) {
jtfBoundaryLength.setText("shape not set");
} else {
DecimalFormat g = new DecimalFormat("0.0");
jtfBoundaryLength.setText("" + g.format(MyFrame.shape1.getBoundaryLength(jsShapes.getValue())));
jtfArea.setText("" + g.format(MyFrame.shape1.getArea(jsShapes.getValue())));
}
MyFrame.shape1.setSliderValue(jsShapes.getValue());
} catch (Throwable ex) {}
}
}
public int getSliderValue() {
return this.jsShapes.getValue();
}
public void actionPerformed(ActionEvent e) {
System.out.println(MyFrame.shape1.getArrayList());
}
}
Here is my code for the Shapes page in which I create my ArrayList
public abstract class Shapes {
ArrayList<String> arrayList = new ArrayList();
protected double boundaryLength;
protected double area;
private int sliderValue;
public int getSliderValue() {
return sliderValue;
}
public void setSliderValue(int sliderValue) {
this.sliderValue = sliderValue;
}
public double getBoundaryLength(double boundaryLength)
{
return boundaryLength;
}
public double getArea(double area)
{
return area;
}
public ArrayList<String> getArrayList() {
return arrayList;
}
public void setArrayList(ArrayList arrayList) {
this.arrayList = arrayList;
}
}
Here is my MyFrame page which is where the menu is created. I have three options from the menu (Triangle, Circle and Square).
public class MyFrame extends javax.swing.JFrame implements ActionListener, ChangeListener {
public static Shapes shape1;
private JMenuItem Square;
private JMenuItem Triangle;
private JMenuItem Circle;
private MyControlPanel controlPanelShapes;
private jPanelTop d1 = new jPanelTop();
private jPanelBottom d2 = new jPanelBottom();
public MyFrame() {
initComponents();
controlPanelShapes = new MyControlPanel();
controlPanelShapes.setSize(1000, 1000);
controlPanelShapes.setLocation(0, 20);
add(controlPanelShapes);
d1.setSize(550, 230);
d1.setVisible(true);
this.add(d1);
JMenuBar jBarShape = new JMenuBar();
JMenu Shape = new JMenu();
Shape.setText("Shape");
Square = new JMenuItem();
Square.setText("Square");
Shape.add(Square);
Square.addActionListener(this);
Triangle = new JMenuItem();
Triangle.setText("Triangle");
Shape.add(Triangle);
Triangle.addActionListener(this);
Circle = new JMenuItem();
Circle.setText("Circle");
Shape.add(Circle);
Circle.addActionListener(this);
jBarShape.add(Shape);
setJMenuBar(jBarShape);
}
#Override
public void stateChanged(ChangeEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Circle) {
shape1 = new Circle();
d1.setCircle(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
} else if (e.getSource() == Triangle) {
shape1 = new Triangle();
d1.setTriangle(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
} else if (e.getSource() == Square) {
shape1 = new Square();
d1.setSquare(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
}
}
}
Basically when I click the play button, any time I click on a menu option or move the slider, it is supposed to be recorded and when I click Stop it stops recording. When I click Play it outputs it to the screen. I am sure it is fairly simple I just have no idea and I have been trying to get it to work for ages!
Thank You in advance for any help, it is extremely appreciated!

Can not fill an array in thread

This gui should draw moving images on frame panel called "system". But first of all i need to make those objects. Here i'm trying to add them to an array and use that array in other classes. But array keeps being empty!
I guess the problem is in declaring(bottom of the code). There is no exception thrown because I let other classes to execute only when this array(Planetarium) is not empty(it should work like that, because other moves depends on planets created(those objects)). But if it is empty that means nothing is declared...
What should i do if I want to fill an array in the thread executed in event listener?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends Frame implements WindowListener,ActionListener {
cpWindow window1 = new cpWindow();
cmWindow window2 = new cmWindow();
Delete window3 = new Delete();
SolarSystem system = new SolarSystem(300,300);
Planet[] Planetarium = null; // using this to make an array
Moon[] Moonarium = null;
/**
* Frame for general window.
*/
public void createFrame0(){
JFrame f0 = new JFrame("Choose what you want to do");
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.addWindowListener(this);
f0.setLayout(new GridLayout(3,1));
JButton cP = new JButton("Create a planet");
JButton cM = new JButton("Create a moon");
JButton Delete = new JButton("Annihilate a planet or moon");
f0.add(cP);
f0.add(cM);
f0.add(Delete);
cP.addActionListener(this);
cM.addActionListener(this);
Delete.addActionListener(this);
cP.setActionCommand("1");
cM.setActionCommand("2");
Delete.setActionCommand("3");
f0.pack();
f0.setVisible(true);
}
/**
* Frame for planet adding window.
*/
class cpWindow implements ActionListener,WindowListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel dist1 = new JLabel("Distance");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField dist2 = new JTextField();
JTextField speed2 = new JTextField();
double distance;
int Speed;
double diameter;
public void createFrame1() {
JFrame f1 = new JFrame("Add planet");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(6,2,5,5));
JButton mygt = new JButton("Create planet");
mygt.addActionListener(this);
name2.setText("belekoks");color2.setText("RED");diam2.setText("30");dist2.setText("60");spe ed2.setText("2");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);f1.add(diam1);
f1.add(diam2);f1.add(dist1);f1.add(dist2);f1.add(speed1);f1.add(speed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
public void createVariables(){
try {
distance = Double.parseDouble(dist2.getText());
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
}
catch(NumberFormatException i) {
}
Main.diametras = diameter;
Main.distancija = distance;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
list.display();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
/**
* Frame for moon adding window
*/
CheckboxGroup planets = new CheckboxGroup();
String which;
class cmWindow implements ActionListener,WindowListener, ItemListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField speed2 = new JTextField();
JLabel info = new JLabel("Which planet's moon it will be?");
JLabel corDist1 = new JLabel("Distance from centre of rotation");
JLabel corSpeed1 = new JLabel("Speed which moon centres");
JTextField corDist2 = new JTextField();
JTextField corSpeed2 = new JTextField();
int cordistance;
int corspeed;
public void createFrame1() {
JFrame f1 = new JFrame("Add moon");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(8,2,5,5));
JButton mygt = new JButton("Create moon");
mygt.addActionListener(this);
for(int i=0;i<Planetarium.length;i++){
add(new Checkbox(Planetarium[i].nam,planets,false));
}
corDist2.setText("15");corSpeed2.setText("3");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);
f1.add(diam1);f1.add(diam2);f1.add(speed1);f1.add(speed2);
f1.add(corDist1);f1.add(corDist2);f1.add(corSpeed1);f1.add(corSpeed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
int Speed;
double diameter;
public void createVariables(){
try {
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
cordistance = Integer.parseInt(corDist2.getText());
corspeed = Integer.parseInt(corSpeed2.getText());
}
catch(NumberFormatException i) {}
Main.diametras = diameter;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
Main.centGrt = corspeed;
Main.centAts = cordistance;
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
#Override
public void itemStateChanged(ItemEvent e) {
which = planets.getSelectedCheckbox().getLabel();
}
}
/**
* Deleting window
*/
class Delete implements ActionListener,WindowListener{
Checkbox[] checkB = new Checkbox[100];
public void createFrame2(){
JFrame f2 = new JFrame("Death Start");
f2.addWindowListener(this);
f2.setLayout(new GridLayout(6,2,5,5));
JButton Del = new JButton("Shoot it!");
Del.addActionListener(this);
JLabel[] planetName = new JLabel[100];
for(int i=0;i<Planetarium.length;i++){
planetName[i].setText(Planetarium[i].nam);
checkB[i].setLabel("This");
checkB[i].setState(false);
f2.add(planetName[i]);f2.add(checkB[i]);
}
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<Planetarium.length;i++){
if(checkB[i].getState()){
Planetarium[i] = null;
}
}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
////////////////////////////////////////////////////////
public GUI() {
createFrame0();
}
public void actionPerformed(ActionEvent e) {
if ("1".equals(e.getActionCommand())) {this.window1.createFrame1();}
else if ("2".equals(e.getActionCommand()) & Planetarium != null) {this.window2.createFrame1();}
else if ("3".equals(e.getActionCommand()) & Planetarium != null) {this.window3.createFrame2();}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
LinkedList list = new LinkedList();
class NewThread extends Thread {
Thread t;
NewThread() {
t = new Thread(this);
t.start();
}
public void run() {
Moon moon = null;
Planet planet = new Planet(Main.vardas,Main.distancija,Main.diametras,Main.spalva,Main.greitis);
if(Planetarium != null){
for(int i=0;i<Planetarium.length;i++){
if (which == Planetarium[i].nam){
moon = new Moon(Main.vardas,Planetarium[i].dist,Main.diametras,Main.spalva,Main.greitis,Main.centGrt,Main.centAts);
}
}}
int a=0,b=0;
int i = 0;
if (Main.centAts == 0){
Planetarium[i] = planet; //i guess problem is here
a++;
list.add(planet);
for(i=0; i <= i+1 0; i++) {
planet.move();
planet.drawOn(system);
system.finishedDrawing();
if (i==360){i=0;}
}
}
else{
Moonarium[i] = moon;
b++;
if(i==Main.greitis){
for(int l = 0; l <= l+1; l++) {
moon.move();
moon.drawOn(system);
system.finishedDrawing();
}}
}
}
}
}
EDIT: add linkedlist(still nothing after display) and moved declaration before infinite loop
You don't appear to have assigned these arrays anything so they should be null rather than empty.
The way you are using them a List might be better.
final List<Planet> planetarium = new ArrayList<Planet>();
planetarium.add(new Planet( .... ));
Planet p = planetarium.get(i);
for(Planet p: planetarium){
// something for each planet.
}
Note: you have to create an array before using it and you have know its length which is fixed. A list can have any length, but you still need to create it first.
Look at the loop before:
Planetarium[i] = planet;
It looks like it will loop infinitely
for(i=0; i >= 0; i++)
i will alway be >= 0.

Categories