KeyEvent не работает - PullRequest
       5

KeyEvent не работает

0 голосов
/ 29 июня 2019

Я сделал новый проект калькулятора JavaFX и Java, но когда я попытался что-то добавить, чтобы что-то было сделано, если нажата эта клавиша или та клавиша, но это не сработало и вместо этого помешало запуску программы. Было бы очень полезно, если у кого-то есть опыт в этом, чтобы я мог двигаться дальше!

Моя ОС - Windows 10. Я импортировал KeyCode и KeyEvent, и попробовал ответ «JavaFX KeyEvent не запускается», что не удалось. Я также попробовал это без scene1.setOnKeyPressed((EventHandler<? super KeyEvent>) root);, который был также отказом. Я также связал действие с моим документом FXML.

Это мой основной класс:

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

public class Essestulator extends Application {

    @Override
    public void start(Stage stage) throws Exception {
   Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene1 = new Scene(root);
        scene1.setOnKeyPressed((EventHandler<? super KeyEvent>) root);

        stage.setScene(scene1);
        stage.show();
    }
}

Мой класс контроллера FXML:

package calculator

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
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.Button;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;


public class FXMLDocumentController implements Initializable {

    double data = 0d;
    int operation = -1;
    private boolean start = false;

    @FXML
    private Label display;

    @FXML
    private Button two;

    @FXML
    private Button five;

    @FXML
    private Button four;

    @FXML
    private Button three;

    @FXML
    private Button one;

    @FXML
    private Button six;

    @FXML
    private Button seven;

    @FXML
    private Button multi;

    @FXML
    private Button add;

    @FXML
    private Button dot;

    @FXML
    private Button divide;

    @FXML
    private Button backspace;

    @FXML
    private Button minus;

    @FXML
    private Button equals;

    @FXML
    private Button clearall;

    @FXML
    private Button clear;

    @FXML
    private Button zero;

    @FXML
    private Button nine;

    @FXML
    private Button eight;

    ArrayList<Integer> arrl = new ArrayList<Integer>(1000);

    @FXML
    void KeyAction(KeyEvent eve) {


        if(start)
        {
            display.setText("");
            start = false;
        }

        if(eve.getSource() == KeyCode.DIGIT1) /* action*/;
        if(eve.getSource() == KeyCode.DIGIT2) /* action*/;
        if(eve.getSource() == KeyCode.DIGIT3) /* action*/;
        if(eve.getSource() == KeyCode.DIGIT4) /* action*/;
        }

    @FXML
    void handleButtonAction(ActionEvent event) {

        if(start)
        {
            display.setText("");
            start = false;
        }

        if(event.getSource() == one)
        {
            display.setText(display.getText() + "1");
        }
        else if(event.getSource() == two)
        {
            display.setText(display.getText() + "2");
        }
        else if(event.getSource() == three)
        {
            display.setText(display.getText() + "3");
        }
        else if(event.getSource() == four)
        {
            display.setText(display.getText() + "4");
        }
        else if(event.getSource() == five)
        {
            display.setText(display.getText() + "5");
        }
        else if(event.getSource() == six)
        {
            display.setText(display.getText() + "6");
        }
        else if(event.getSource() == seven)
        {
            display.setText(display.getText() + "7");
        }
        else if(event.getSource() == eight)
        {
            display.setText(display.getText() + "8");
        }
        else if(event.getSource() == nine)
        {
            display.setText(display.getText() + "9");
        }
        else if(event.getSource() == zero)
        {
            display.setText(display.getText() + "0");
        }
        else if(event.getSource() == dot)
        {
            display.setText(display.getText() + ".");
            dot.setDisable(true);
        }
        else if(event.getSource() == clear)
        {
            display.setText("");
            dot.setDisable(false);
        } 
        else if(event.getSource() == add)
        {
            data = Float.parseFloat(display.getText());
            operation = 1;
            display.setText("");
            dot.setDisable(false);
        }
        else if(event.getSource() == minus)
        {
            data = Float.parseFloat(display.getText());
            operation = 2;
            display.setText("");
            dot.setDisable(false);
        }
        else if(event.getSource() == multi)
        {
            data = Float.parseFloat(display.getText());
            operation = 3;
            display.setText("");
            dot.setDisable(false);
        }
        else if(event.getSource() == divide)
        {
            data = Float.parseFloat(display.getText());
            operation = 4;
            display.setText("");
            dot.setDisable(false);
        }
        else if(event.getSource() == equals)
        {
            Float secondOperand = Float.parseFloat(display.getText());
            dot.setDisable(false);
            switch(operation)
            {
                case 1: //Addition
                    Double ans = data + secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 2: //Subtraction
                    ans = data - secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 3: //Multiplication
                    ans = data * secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 4: //Division
                    ans = 0d;
                    try{
                    ans = data / secondOperand;
                    }catch(Exception ex){display.setText("Error");}
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
            }
            if(event.getSource() != divide && event.getSource() != add && event.getSource() != multi && event.getSource() != minus)
            {
                start = true;
            }
        }

    }

    @FXML
    private void send2sceneconver(ActionEvent event) throws Exception{
        Parent rootBMI = FXMLLoader.load(getClass().getResource("ConversionCal.fxml"));

        Scene scene2 = new Scene(rootBMI);
        Stage calS = (Stage) ((Node) event.getSource()).getScene().getWindow();

        calS.setScene(scene2);
        calS.show();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    

}

И моя консоль, когда я ее запускаю:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: javafx.scene.layout.AnchorPane cannot be cast to javafx.event.EventHandler
    at essestulator.Essestulator.start(Essestulator.java:27)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application essestulator.Essestulator
Java Result: 1

И мой FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.shape.Line?>
<?import javafx.scene.text.Font?>

<AnchorPane id="pane" fx:id="window1" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="806.0" prefWidth="1155.0" stylesheets="@FXMLDocument.css" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="essestulator.FXMLDocumentController">
   <children>
      <Line endX="215.0" endY="1.0" layoutX="632.0" layoutY="227.0" startX="-608.0" />
      <GridPane layoutX="23.0" layoutY="244.0" prefHeight="430.0" prefWidth="823.0">
        <columnConstraints>
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Button fx:id="two" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="2" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="2">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="five" contentDisplay="CENTER" layoutX="216.0" layoutY="115.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="115.0" prefWidth="206.0" text="5" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="3">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="four" contentDisplay="CENTER" layoutX="216.0" layoutY="114.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="4" textAlignment="CENTER" textFill="WHITE" GridPane.rowIndex="3">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="three" contentDisplay="CENTER" layoutX="216.0" layoutY="9.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="210.0" stylesheets="@FXMLDocument.css" text="3" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="2">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="one" contentDisplay="CENTER" layoutX="422.0" layoutY="9.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="1" textAlignment="CENTER" textFill="WHITE" GridPane.rowIndex="2">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="six" contentDisplay="CENTER" layoutX="10.0" layoutY="219.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="115.0" prefWidth="206.0" stylesheets="@FXMLDocument.css" text="6" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="3">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="seven" contentDisplay="CENTER" layoutX="216.0" layoutY="219.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="115.0" prefWidth="206.0" stylesheets="@FXMLDocument.css" text="7" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="3">
               <font>
                  <Font name="System Bold" size="50.0" />
               </font>
            </Button>
            <Button fx:id="multi" contentDisplay="CENTER" layoutX="628.0" layoutY="9.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="106.0" prefWidth="243.0" text="x" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="1">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="add" contentDisplay="CENTER" layoutX="10.0" layoutY="429.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="+" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="1">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="dot" contentDisplay="CENTER" layoutX="422.0" layoutY="429.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="." textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="2">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="divide" contentDisplay="CENTER" layoutX="10.0" layoutY="9.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="÷" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="1">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="backspace" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="→" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="2">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="minus" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="-" textAlignment="CENTER" textFill="WHITE" GridPane.rowIndex="1">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="equals" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="=" textAlignment="CENTER" textFill="WHITE" GridPane.columnIndex="3">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="clearall" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="C" textAlignment="CENTER" textFill="AZURE" GridPane.columnIndex="1">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
            <Button fx:id="clear" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="109.0" prefWidth="243.0" text="CE" textAlignment="CENTER" textFill="WHITE">
               <font>
                  <Font size="50.0" />
               </font>
            </Button>
         </children>
      </GridPane>
      <Button fx:id="zero" contentDisplay="CENTER" layoutX="436.0" layoutY="674.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="107.0" prefWidth="410.0" text="0" textAlignment="CENTER" textFill="WHITE">
         <font>
            <Font name="System Bold" size="50.0" />
         </font>
      </Button>
      <Button fx:id="nine" contentDisplay="CENTER" layoutX="230.0" layoutY="674.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="107.0" prefWidth="206.0" text="9" textAlignment="CENTER" textFill="WHITE">
         <font>
            <Font name="System Bold" size="50.0" />
         </font>
      </Button>
      <Button fx:id="eight" contentDisplay="CENTER" layoutX="24.0" layoutY="674.0" mnemonicParsing="false" onAction="#handleButtonAction" onKeyPressed="#KeyAction" prefHeight="107.0" prefWidth="206.0" text="8" textAlignment="CENTER" textFill="WHITE">
         <font>
            <Font name="System Bold" size="50.0" />
         </font>
      </Button>
      <Button cacheShape="false" centerShape="false" focusTraversable="false" layoutX="261.0" layoutY="101.0" mnemonicParsing="false" onAction="#send2sceneconver" prefHeight="39.0" prefWidth="162.0" scaleShape="false" text="Converter" visible="false">
         <font>
            <Font size="18.0" />
         </font>
      </Button>
      <TabPane layoutX="888.0" layoutY="25.0" prefHeight="757.0" prefWidth="235.0" tabClosingPolicy="UNAVAILABLE">
        <tabs>
          <Tab text="Memory">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="715.0" prefWidth="241.0">
                     <children>
                        <TextArea editable="false" layoutX="-222.0" layoutY="72.0" prefHeight="690.0" prefWidth="235.0" promptText="Memory" AnchorPane.bottomAnchor="38.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                           <font>
                              <Font size="20.0" />
                           </font>
                        </TextArea>
                        <Button layoutY="690.0" mnemonicParsing="false" prefHeight="39.0" prefWidth="114.0" text="M+">
                           <font>
                              <Font name="System Bold" size="18.0" />
                           </font>
                        </Button>
                        <Button layoutX="120.0" layoutY="690.0" mnemonicParsing="false" prefHeight="39.0" prefWidth="115.0" text="MC">
                           <font>
                              <Font name="System Bold" size="18.0" />
                           </font>
                        </Button>
                     </children></AnchorPane>
            </content>
          </Tab>
          <Tab text="Notes">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                     <children>
                        <TextArea layoutX="19.0" layoutY="-1.0" prefHeight="715.0" prefWidth="235.0" promptText="Notes" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                           <font>
                              <Font size="20.0" />
                           </font>
                        </TextArea>
                     </children></AnchorPane>
            </content>
          </Tab>
        </tabs>
      </TabPane>
      <Label fx:id="display" alignment="CENTER_RIGHT" layoutX="23.0" layoutY="25.0" prefHeight="202.0" prefWidth="811.0" text="0" textAlignment="RIGHT">
         <font>
            <Font size="96.0" />
         </font>
      </Label>
   </children>
</AnchorPane>
I was wanting it to do [blank] if [blank] key pressed, but it caused a lot of error messages that I tried to read but did not make it.

1 Ответ

1 голос
/ 01 июля 2019

Ладно, для начала, я бы порекомендовал соглашения по именованию java после того, как вы исправите свой код. Далее, я бы решил эту проблему. Есть много разных способов сделать это.

Сначала нам нужно удалить все onKeyActions в вашем FXML, так что где бы вы ни увидели onKeyPressed="#KeyAction" удалите его

Далее нам нужна функция, чтобы заменить это (ваш старый onKeyPressed), поэтому я смоделировал пример для цифры 1 и 2

public void initKeyActions(Scene scene){
    scene.setOnKeyPressed(keyAction ->{
        System.out.println(keyAction.getCode());
        if(keyAction.getCode()==KeyCode.DIGIT1)
            one.fire();//Fires the necessary button
        else if(keyAction.getCode()==KeyCode.DIGIT2)
            two.fire();
        //Continue as I don't want to type these all out
    });
}

После этого нам нужно вызвать функцию и передать сцену, поэтому нам нужно изменить способ инициализации вашего fxml, чтобы вы могли получить доступ к контроллеру, поэтому сделайте что-то вроде этого

@Override
public void start(Stage stage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(loader.load());

    FXMLDocumentController controller = loader.getController();
    controller.initKeyActions(scene);

    stage.setScene(scene);
    stage.show();
}

После того, как вы внедрили все свои кнопки, они должны работать как положено, дайте мне знать, если у вас есть какие-либо вопросы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...