反向乘法表javafx

时间:2015-03-03 05:25:35

标签: java javafx

对于这个应用程序,我需要输入一个数字并显示数字,当它们相乘时会给你相关的数字。例如,如果输入42,那么6 * 7和7 * 6的标签将改变颜色。我想出了如何得到答案,但我不知道如何操纵乘法表中的标签来改变颜色。为了给你一个想法,

enter image description here

主要课程

package application;

import java.util.List;

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane pane = new BorderPane();
        pane.setTop(getHbox1());

        HBox prompt = new HBox(15);
        prompt.setPadding(new Insets(15, 15, 15, 15));
        prompt.setAlignment(Pos.TOP_CENTER);
        prompt.getStyleClass().add("hbox2");

        Label lblProblem = new Label("Enter problem: ");
        prompt.getChildren().add(lblProblem);

        TextField tfProblem = new TextField();
        prompt.getChildren().add(tfProblem);

        Button btnFindAnswer = new Button("Find answers");
        btnFindAnswer.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {

            @Override
            public void handle(Event arg0) {
                int x = showFactors(tfProblem);

            }

        });

        prompt.getChildren().add(btnFindAnswer);

        pane.setCenter(prompt);
        pane.setBottom(setUpGrid());

        Scene scene = new Scene(pane, 550, 650);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setTitle("lab 7");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    private HBox getHbox1() {
        HBox hbox = new HBox(15);
        hbox.setPadding(new Insets(15, 15, 15, 15));
        hbox.setAlignment(Pos.TOP_CENTER);
        hbox.getStyleClass().add("hbox1");

        Label lblProblem = new Label("Reverse Multiplication Table");
        hbox.getChildren().add(lblProblem);

        return hbox;
    }

    public GridPane setUpGrid() {
        GridPane pane = new GridPane();
        Label[][] labels = new Label[11][11];

        for (int row = 0; row < 11; row++)
            for (int col = 0; col < 11; col++) {
                Label l = new Label();
                setUpLabel(l, col, row);
                labels[row][col] = l;
                pane.add(l, col, row);
            }

        return pane;
    }

    public void setUpLabel(final Label l, final int col, final int row) {
        l.setPrefHeight(50);
        l.setPrefWidth(50);
        l.setAlignment(Pos.CENTER);
        l.setStyle("-fx-stroke-border: black; -fx-border-width: 1;");
        String a = String.valueOf(row);
        String b = String.valueOf(col);

        if (row == 0 || col == 0) {
            l.getStyleClass().add("gridBorders");

            if(row == 0) 
                l.setText(b);
            else if (col == 0) 
                l.setText(a);
        } else {
            l.setText(a + " * " + b);   
            l.getStyleClass().add("gridInside");

        }
    }

    public int showFactors(TextField problem) {
        FactorCalculator calc = new FactorCalculator();
        int number = Integer.parseInt(problem.getText());
        List<Integer> factors = calc.findFactor(number);

        for(int i = 0; i < factors.size() - 1; i++) {
            return factors.get(i);

        }

        return 0;
    }

    public static void main(String[] args) {
        launch(args);
    }

}

factorCalculator class

package application;

import java.util.ArrayList;
import java.util.List;

public class FactorCalculator {
    public List<Integer> list = new ArrayList<Integer>();

    public List<Integer> findFactor(int problem) {

        int incrementer = 1;

        if(problem % 2 != 0) {
            incrementer = 2;
        }

        while(incrementer <= problem) {
            if(problem % incrementer == 0) {
                list.add(incrementer);
            }

            incrementer++;
        }
        return list;
    }

}

申请css

{
    -fx-text-alignment: center;
}

.hbox1 {
    -fx-background-color: gray;


}

.hbox2 {
    -fx-background-color: white;

}

.gridBorders {
    -fx-background-color: gray;
    -fx-text-fill:#A3FF47;
    -fx-border-style: solid;
    -fx-border-width: 1;
    -fx-stroke-border: black;

}

.gridInside {
    -fx-background-color: red;
    -fx-text-fill: white;
    -fx-border-style: solid;
    -fx-border-width: 1;
    -fx-stroke-border: black;
}

.gridAnswer {
    -fx-background-color: white;
    -fx-text-fill: black;

}

3 个答案:

答案 0 :(得分:2)

只需使用你的风格&#34; gridAnswer&#34;并设置它

l.getStyleClass().add( "gridAnswer");

或将其删除

l.getStyleClass().remove( "gridAnswer");

取决于您的需求。


修改我可以建议采用不同的方法吗?

只需创建一个包含您需要的所有信息的自定义单元格。像这样:

private class AnswerCell extends Label {

    int a;
    int b;
    int value;

    public AnswerCell( int a, int b) {
        this.a = a;
        this.b = b;
        this.value = a * b;
        setText( a + " * " + b);
    }

    public boolean matches( int matchValue) {
        return value == matchValue;
    }

    public void highlight() {
        getStyleClass().add( "gridAnswer");
    }

    public void unhighlight() {
        getStyleClass().remove( "gridAnswer");
    }
}

在您的设置方法中,您只需添加单元格并将它们放入全局列表中:

List<AnswerCell> answerCells = new ArrayList<>();

要找到答案,你可以这样做:

for( AnswerCell cell: answerCells) {
    cell.unhighlight();
}

for( AnswerCell cell: answerCells) {
    if( cell.matches(number)) {
        cell.highlight();
    } 
}

答案 1 :(得分:1)

ReverseMultiplication.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reversemultiplication;

import java.util.List;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 *
 * @author reegan
 */
public class ReverseMultiplication extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane pane = new BorderPane();
        pane.setTop(getHbox1());

        HBox prompt = new HBox(15);
        prompt.setPadding(new Insets(15, 15, 15, 15));
        prompt.setAlignment(Pos.TOP_CENTER);
        prompt.getStyleClass().add("hbox2");

        Label lblProblem = new Label("Enter problem: ");
        prompt.getChildren().add(lblProblem);

        TextField tfProblem = new TextField();
        prompt.getChildren().add(tfProblem);
        GridPane gridPane = setUpGrid();
        GridpaneHelper gh = new GridpaneHelper(gridPane);
        Button btnFindAnswer = new Button("Find answers");
        btnFindAnswer.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {

            @Override
            public void handle(Event arg0) {
                List<int[]> x = showFactors(tfProblem);
                for (int[] x1 : x) {
                    Node node = gh.getChildren()[x1[0]][x1[1]];
                    node.setStyle("-fx-background-color: green");
                }
            }

        });

        prompt.getChildren().add(btnFindAnswer);

        pane.setCenter(prompt);
        pane.setBottom(gridPane);

        Scene scene = new Scene(pane, 550, 650);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setTitle("lab 7");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    private HBox getHbox1() {
        HBox hbox = new HBox(15);
        hbox.setPadding(new Insets(15, 15, 15, 15));
        hbox.setAlignment(Pos.TOP_CENTER);
        hbox.getStyleClass().add("hbox1");

        Label lblProblem = new Label("Reverse Multiplication Table");
        hbox.getChildren().add(lblProblem);

        return hbox;
    }

    public GridPane setUpGrid() {
        GridPane pane = new GridPane();
        Label[][] labels = new Label[11][11];

        for (int row = 0; row < 11; row++) {
            for (int col = 0; col < 11; col++) {
                Label l = new Label();
                setUpLabel(l, col, row);
                labels[row][col] = l;
                pane.add(l, col, row);
            }
        }

        return pane;
    }

    public void setUpLabel(final Label l, final int col, final int row) {
        l.setPrefHeight(50);
        l.setPrefWidth(50);
        l.setAlignment(Pos.CENTER);
        l.setStyle("-fx-stroke-border: black; -fx-border-width: 1;");
        String a = String.valueOf(row);
        String b = String.valueOf(col);

        if (row == 0 || col == 0) {
            l.getStyleClass().add("gridBorders");

            if (row == 0) {
                l.setText(b);
            } else if (col == 0) {
                l.setText(a);
            }
        } else {
            l.setText(a + " * " + b);
            l.getStyleClass().add("gridInside");

        }
    }

    public List<int[]> showFactors(TextField problem) {
        FactorCalculator calc = new FactorCalculator();
        int number = Integer.parseInt(problem.getText());
        System.out.println(number);
        List<int[]> factors = calc.findFactor(number, 10);

        System.out.println(factors);
        return factors;

    }

    public static void main(String[] args) {
        launch(args);
    }

}

GridpaneHelper.java帮助gridpane节点访问。     package reversemultiplication;

import javafx.scene.Node;
import javafx.scene.layout.GridPane;

public class GridpaneHelper {

    GridPane gridPane;

    public GridpaneHelper(GridPane gridPane) {

        this.gridPane = gridPane;

    }

    private int size() {

        return gridPane.getChildren().size();

    }

    public int getColumnSize() {

        int numRows = gridPane.getRowConstraints().size();

        for (int i = 0; i < gridPane.getChildren().size(); i++) {

            Node child = gridPane.getChildren().get(i);

            if (child.isManaged()) {

                int columnIndex = GridPane.getColumnIndex(child);

                int columnEnd = GridPane.getColumnIndex(child);

                numRows = Math.max(numRows, (columnEnd != GridPane.REMAINING ? columnEnd : columnIndex) + 1);

            }

        }

        return numRows;

    }

    public int getRowSize() {

        int numRows = gridPane.getRowConstraints().size();

        for (int i = 0; i < gridPane.getChildren().size(); i++) {

            Node child = gridPane.getChildren().get(i);

            if (child.isManaged()) {

                int rowIndex = GridPane.getRowIndex(child);

                int rowEnd = GridPane.getRowIndex(child);

                numRows = Math.max(numRows, (rowEnd != GridPane.REMAINING ? rowEnd : rowIndex) + 1);

            }

        }

        return numRows;

    }

    public Node[] getColumnChilds(int columnNo) {

        if (columnNo < getRowSize()) {

            return getChildren()[columnNo];

        }

        return null;

    }

    public Node[] getRowChilds(int rowNo) {

        Node n[] = new Node[getRowSize()];

        if (rowNo <= getRowSize()) {

            for (int i = 0; i < getRowSize(); i++) {

                n[i] = getColumnChilds(i)[rowNo];

            }

            return n;

        }

        return null;

    }

    public Node[] getChildRowVia() {
        Node n[] = new Node[size()];
        int col = getColumnSize();
        int arrIncre = 0;

        for (int i = 0; i < col; i++) {

            for (Node n1 : getRowChilds(i)) {

                if (n1 != null) {

                    n[arrIncre] = n1;

                    arrIncre++;

                }

            }

        }
        return n;
    }

    public Node[][] getChildren() {
        Node[][] nodes = new Node[getRowSize()][getColumnSize()];
        for (Node node : gridPane.getChildren()) {
            int row = gridPane.getRowIndex(node);
            int column = gridPane.getColumnIndex(node);
            nodes[row][column] = node;
        }
        return nodes;
    }

    public Integer postion(Node node, Pos pos) {
        if (node != null) {
            switch (pos) {
                case Row:
                    return gridPane.getRowIndex(node);
                case Column:
                    return gridPane.getColumnIndex(node);
            }
        }
        return null;

    }

    enum Pos {

        Row,
        Column;

    }
}

FactorCalculator.java类文件添加了一个新方法,这有助于实现多少组合。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reversemultiplication;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author reegan
 */
class FactorCalculator {

    public List<Integer> list = new ArrayList<Integer>();
    private int problem = 0;

    public List<int[]> findFactor(int problem, int limit) {
        int incrementer = 1;
        this.problem = problem;
        while (incrementer <= limit) {
            if (problem % incrementer == 0) {
                list.add(incrementer);
            }

            incrementer++;
        }


        return combinational();
    }

    public List<int[]> combinational() {
        List<int[]> arrays = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (list.get(i) * list.get(j) == problem) {
                    int[] inx = new int[2];
                    inx[0] = list.get(i);
                    inx[1] = list.get(j);
                    arrays.add(inx);
                }
            }
        }

        return arrays;
    }

}

在您的项目中添加您的css文件,但此示例代码在之前的设置样式中不明确。之后我会告诉您。

答案 2 :(得分:1)

Roland / ItachiUchiha的答案很好:这是另一种方法。

定义IntegerProperty以保存当前值:

public class Main extends Application {

    private final IntegerProperty value = new SimpleIntegerProperty();

    // ...
}

现在让每个标签都观察到值:

public void setUpLabel(final Label l, final int col, final int row) {

    value.addListener((obs, oldValue, newValue) -> {
        if (col * row == newValue.intValue()) {
            l.getStyleClass().add("gridAnswer");
        } else {
            l.getStyleClass().remove("gridAnswer");
        }
    });

    // all previous code...
}

最后,只需在按下按钮时设置值:

    btnFindAnswer.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            // you probably don't need this any more:
            int x = showFactors(tfProblem);

            value.set(Integer.parseInt(tfProblem.getText()));

        }

    });
相关问题