如何在JavaFX场景构建器中使用onKeyPressed?

时间:2018-09-20 11:03:27

标签: javafx javafx-8

我是JavaFX场景生成器的新手,我使用它开发了文本编辑器,但是最后,我遇到了一个问题,当我按组合键时想调用一个函数,例如,假设我按了CTRL + S,则必须从我的controller.java中调用一个函数。

[这是我的javaScene构建器图片] [1]

  

Main.java

package sample;

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 Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        Scene scene = new Scene(root, 300, 275);
        primaryStage.setScene(scene);

        scene.getStylesheets().add("style.css");

        primaryStage.show();
    }


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

**   Controller.java

package sample;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.ResourceBundle;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyEvent;
import javafx.stage.FileChooser;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javax.xml.soap.Text;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.input.KeyEvent;

import javafx.stage.Stage;
import javafx.scene.input.KeyCode;


public class Controller implements EventHandler <KeyEvent> {
    boolean doesFileHasName=false;
    File selectedFile1;
    File selectedFile;

    FileChooser fileChooser = new FileChooser();
    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private TextArea TextArea;

    @FXML
    private MenuBar MenuBar;

    @FXML
    private MenuItem createFile;

    @FXML
    private Text fileName;


    @FXML
    private javafx.scene.text.Text text;

    @Override
    public void handle(KeyEvent keyEvent)
    {

    }


    @FXML
    public void onKeyPressed(KeyEvent keyEvent) {




        if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.C) {
            System.out.println("Control Down: " + keyEvent.isControlDown() + "  " + keyEvent.getCode() + " was pressed!");
        }
        if (keyEvent.isAltDown() && keyEvent.getCode() == KeyCode.C) {
            System.out.println("Alt Down: " + keyEvent.isAltDown() + "  " + keyEvent.getCode() + " was pressed!");
        }

    }


    @FXML
   void editSaveAs()
    {

    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Java files (*.java)", "*.java");
               /* new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");*/
            fileChooser.getExtensionFilters().add(extFilter);
    selectedFile = fileChooser.showSaveDialog(null);
        if(selectedFile != null){
            SaveFile(TextArea.getText(), selectedFile);
          text.setText(selectedFile.getName());
           doesFileHasName=true;

        }

    }
    @FXML
    void editNew()
    {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("new.fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();

            stage.setTitle("Untitled");
            stage.setScene(new Scene(root1));
            stage.show();
        }catch (Exception e){
            System.out.println("Can't open a new window");

    }
    }
    String[] storeButton = new String[2];

    @FXML
    void editOpen()
    {
       selectedFile1 = fileChooser.showOpenDialog(null);

      if (selectedFile1!=null)
      {
         text.setText(selectedFile1.getName());
         doesFileHasName = true;

          try{
              FileReader fileReader = new FileReader(selectedFile1);
              BufferedReader bufferedReader = new BufferedReader(fileReader);
              String s ;
              String f="" ;
              while((s=bufferedReader.readLine())!=null)
              {

                  f=f+s+"\n";


              }
              TextArea.setText(f);
              bufferedReader.close();
          }catch(Exception error)
          {
              System.out.println("hello world!!!");
          }



      }
    }

    @FXML
    void Save() {
        if (doesFileHasName == false) {
            editSaveAs();
            //System.out.println(selectedFile.getName());
        } else {
            if (doesFileHasName == true) {



                try {
                    if(selectedFile!= null && text.getText().equals( selectedFile.getName())) {
                        SaveFile(TextArea.getText(), selectedFile);
                        System.out.println("selectFile block is done");

                    }else
                    {

                        if(selectedFile1!=null && text.getText().equals(selectedFile1.getName())) {
                            SaveFile(TextArea.getText(), selectedFile1);
                            System.out.println("selectFile1 block is done");

                    }
                }
            }catch (Exception E) {

                    System.out.println(E);

                }
        }}
    }
    private void SaveFile(String content, File file){
        try {
            FileWriter fileWriter;

            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {

            Logger.getLogger(Main.class
                    .getName()).log(Level.SEVERE, null, ex);
        }

    }


    @FXML
    void onKeyTyped()
    {
        TextArea.setStyle("-fx-font-size: 18");
        if (doesFileHasName == true) {



            try {
                if(selectedFile!= null && text.getText().equals( selectedFile.getName())) {
                    SaveFile(TextArea.getText(), selectedFile);
                    //System.out.println("selectFile block is done");

                }else
                {

                    if(selectedFile1!=null && text.getText().equals(selectedFile1.getName())) {
                        SaveFile(TextArea.getText(), selectedFile1);
                        //System.out.println("selectFile1 block is done");

                    }
                }
            }catch (Exception E) {

                System.out.println(E);

            }
        }

    }

    @FXML
    void initialize() {
        text.setText("Untitled");
        assert TextArea != null : "fx:id=\"TextArea\" was not injected: check your FXML file 'textEditor.fxml'.";
        assert MenuBar != null : "fx:id=\"MenuBar\" was not injected: check your FXML file 'textEditor.fxml'.";


    }
}

**

  

sample.fxml

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

<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.ScrollBar?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane id="AnchorPane" onKeyPressed="#onKeyPressed" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="499.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <MenuBar fx:id="MenuBar" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <menus>
                <Menu mnemonicParsing="false" text="File">
                    <items>
                        <MenuItem mnemonicParsing="false" onAction="#editNew" text="New          " />
                        <MenuItem mnemonicParsing="false" onAction="#editOpen" text="Open         " />
                        <MenuItem mnemonicParsing="false" onAction="#Save" text="Save          " />
                        <MenuItem mnemonicParsing="false" onAction="#editSaveAs" text="Save As...    " />
                        <MenuItem mnemonicParsing="false" text="Exit" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Undo          (Ctrl+Z)" />
                        <MenuItem mnemonicParsing="false" text="Cut             (Ctrl+X)" />
                        <MenuItem mnemonicParsing="false" text="Copy          (Ctrl+C)" />
                        <MenuItem mnemonicParsing="false" text="Paste          (Ctrl+V)" />
                        <MenuItem mnemonicParsing="false" text="Delete        (Del)" />
                        <MenuItem mnemonicParsing="false" text="Find...         (Ctrl+F)" />
                        <MenuItem mnemonicParsing="false" text="Replace...   (Ctrl+H)" />
                        <MenuItem mnemonicParsing="false" text="Select All     (Ctrl+A)" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                    <items>
                        <MenuItem mnemonicParsing="false" text="About" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Font Size">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Unspecified Action">
                            <graphic>
                                <ScrollBar orientation="VERTICAL" />
                            </graphic>
                        </MenuItem>
                    </items>
                </Menu>
            </menus>
        </MenuBar>
        <TextArea fx:id="TextArea" layoutY="25.0"  onKeyTyped="#onKeyTyped" prefHeight="474.0" prefWidth="500.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="51.0" />
        <Text fx:id="text" layoutX="7.0" layoutY="48.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
         <font>
            <Font size="15.0" />
         </font></Text>
    </children>
</AnchorPane>

我们将不胜感激...

0 个答案:

没有答案