【问题标题】:getting variables from other files in the project (like from main class and from other .class file) [duplicate]从项目中的其他文件(如从主类和其他.class文件)获取变量[重复]
【发布时间】:2017-03-05 08:35:00
【问题描述】:

编辑:有人将此标记为重复。我已经多次阅读了另一个问题,但我真的不明白如何将它应用到我的程序中。如果有人可以在这个特定的上下文中帮助我,那就太好了,因为我还没有太多关于 Java 的知识。一个简短的起点甚至可能会帮助我。我的问题与弹出窗口无关。


我有问题。我不想将服务器代码放入FXMLControllerinitialize() 方法中。相反,我将服务器启动代码放入MainAppstart() 方法中,并创建了一个RemoteReader 类。但是如何将RemoteReaderMainApp 的输入和输出流变量放入FXMLController 类?我正在使用 SceneBuilder。

代码:

FXMLController.java:

package de.freakyonline.ucone;

import de.freakyonline.ucone.Player;
import de.freakyonline.ucone.PlayerList;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class FXMLController {

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private BorderPane borderPane;
    
    @FXML
    private TableView<Player> playerTable;
    final Tooltip playerTableToolTip = new Tooltip("Rightclick for more options ...");
    
    @FXML
    private TableColumn<Player, String> nickColumn;

    @FXML
    private TableColumn<Player, String> groupColumn;
    
    @FXML
    private TableColumn<Player, String> yearOfBirthColumn;

    @FXML
    private TableColumn<Player, Integer> ageColumn;

    @FXML
    private TableColumn<Player, String> genderColumn;
    
    @FXML
    private TableColumn<Player, String> lastQuitColumn;
    
    @FXML
    private Tab consoleOneTab;
    
    @FXML
    private MenuBar mainMenuBar;
    
    @FXML
    private TextArea consoleOneTextArea;
    
    @FXML
    private TextField consoleOneTextField;
    
    @FXML
    void handleConsoleOneAction(ActionEvent event) {
      
        switch(consoleOneTextField.getText().toLowerCase()) {
            case "freaky": 
                consoleOneTextArea.appendText("Freaky rulez! :D\n"); 
                break;
            case "ky3ak":
                consoleOneTextArea.appendText("Ky3ak rulez! :D\n");
                break;
            case "testserver":
                consoleOneTextArea.appendText("Sending an object ...");
                // PROBLEM: I don't know how I can get the out variable of remote (RemoteReader) to here.
                remote.out.writeObject(new Player("freakyy85","Owner","1810",31,"m","missing...")); 
                
            case "help":
                consoleOneTextArea.appendText("This console is mainly to log stuff which is done by the program to the user, so they can see what's going on.");
                break;                    
            default: consoleOneTextArea.appendText("Unknown Command\n");
        }
        
        consoleOneTextField.clear();
    }
    
    @FXML
    void handleConsoleOneTabSelected(Event event) {
        consoleOneTextField.requestFocus();
    }
    
    @FXML
    void handleFileClose(ActionEvent event) {
        Platform.exit();
    }
    
    @FXML
    void handleHelpAbout(ActionEvent event) {
        Stage haStage = new Stage();
        haStage.setTitle("Help --> About");
        Label aboutText = new Label("UCOne by freakyy85\nInitially developed for Ky3ak and UnityCraft");
        aboutText.setPadding(new Insets(20));
        haStage.setScene(new Scene(new StackPane(aboutText)));
        haStage.initOwner(borderPane.getScene().getWindow());
        haStage.initModality(Modality.WINDOW_MODAL);
        haStage.show();
    }
    
    @FXML
    void handlePlayerEditCommit(TableColumn.CellEditEvent<Player, String> event) {
        System.out.println(event.getRowValue().toString());
    }
    
    @FXML
    void handleTextChanged(InputMethodEvent event) {

    }
    
    @FXML
    private void handlePTContextMenuRequest(ContextMenuEvent event) {
        System.out.println("Target: " + event.getTarget().toString());
        System.out.println("Source: " + event.getSource().toString());
        
        final ContextMenu playerTableContextMenu = new ContextMenu();
        
        MenuItem testMenuItem = new MenuItem("Test");
        testMenuItem.setOnAction( e -> consoleOneTextArea.appendText("Used ContextMenu in Playertable, here: " + event.getTarget().toString()));
        
        MenuItem colorizeFont = new MenuItem("Colorize Font");
        colorizeFont.setOnAction( e -> consoleOneTextArea.appendText("PickResult: " + event.getPickResult().toString()));

        MenuItem makeLocalNotes = new MenuItem("Local Player Notes");
        makeLocalNotes.setOnAction( (e) -> {
                Stage plnStage = new Stage();
                plnStage.setTitle("(nickHere) - PlayerLocalNotesEditor");
                HTMLEditor playerLocalNotes = new HTMLEditor();
                plnStage.setScene(new Scene(new StackPane(playerLocalNotes)));
                plnStage.initOwner(borderPane.getScene().getWindow());
                plnStage.initModality(Modality.WINDOW_MODAL);
                plnStage.show();
        });
       
        
        
        playerTableContextMenu.getItems().add(testMenuItem);
        playerTableContextMenu.getItems().add(colorizeFont);
        playerTableContextMenu.getItems().add(makeLocalNotes);
        playerTableContextMenu.show(borderPane.getScene().getWindow(),event.getScreenX(),event.getScreenY());
    }

    @FXML
    void initialize() {
        assert nickColumn != null : "fx:id=\"nickColumn\" was not injected: check your FXML file 'Scene.fxml'.";
        assert groupColumn != null : "fx:id=\"groupColumn\" was not injected: check your FXML file 'Scene.fxml'.";
        
        PlayerList playerList = new PlayerList();

        playerTable.setItems(playerList.playerList);

        nickColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("nick"));
        groupColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("group"));
        
        yearOfBirthColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("yearOfBirth"));
        yearOfBirthColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        
        ageColumn.setCellValueFactory(new PropertyValueFactory<Player,Integer>("age"));
        
        genderColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("gender"));
        genderColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        
        lastQuitColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("lastQuit"));
        
        playerTable.setTooltip(playerTableToolTip);
        
        
    }  
}

MainApp.java:

package de.freakyonline.ucone;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    String ver = "v0.1-SNAPSHOT";
    ObjectOutputStream out;
    ObjectInputStream in;
    
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        // Connect to Server
        try {
            Socket sock = new Socket("unitycraft.de", 2009);
            out = new ObjectOutputStream(sock.getOutputStream());
            in = new ObjectInputStream(sock.getInputStream());
            
            // Listen for remote stuff comming in ...
            Thread remote = new Thread(new RemoteReader(in,out,sock));
            remote.start();
        } catch (Exception ex) { ex.printStackTrace(); }
        
        
        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");
        
        stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

RemoteReader.java:

package de.freakyonline.ucone;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author uwe
 */
public class RemoteReader implements Runnable {
    Object obj = null;
    ObjectInputStream in;
    ObjectOutputStream out;
    Socket sock;
    
    public RemoteReader (ObjectInputStream in, ObjectOutputStream out, Socket sock) {
        this.in = in;
        this.out = out;
        this.sock = sock;
    }
    
    public void run() {
        try {
            while((obj=in.readObject()) != null)
                System.out.println("Got object from server ...");
        } catch (Exception ex) { ex.printStackTrace(); }
    }

}

顺便说一句,我正在学习。 ;)

【问题讨论】:

    标签: class javafx-8 scenebuilder


    【解决方案1】:

    我让它工作了。我将主类更改为:

    public class MainApp extends Application {
    
        String ver = "v0.1-SNAPSHOT";
        ObjectOutputStream out;
        ObjectInputStream in;
        Socket sock;
        Thread remote;
    
        @Override
        public void start(Stage stage) throws Exception {
    
            FXMLLoader root = new FXMLLoader(
                getClass().getResource("/fxml/Scene.fxml")
            );
    
    //        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
    
            // Connect to Server
            try {
                Socket sock = new Socket("unitycraft.de", 2009);
                out = new ObjectOutputStream(sock.getOutputStream());
                in = new ObjectInputStream(sock.getInputStream());
    
                // Listen for remote stuff comming in ...
                Thread remote = new Thread(new RemoteReader(in,out,sock));
                remote.start();
            } catch (Exception ex) { ex.printStackTrace(); }
    
    
    
            Scene scene = new Scene(root.load());
            scene.getStylesheets().add("/styles/Styles.css");
    
            FXMLController controller = root.<FXMLController>getController();
            controller.initData(in,out,sock);
    
            // Connect to Server
            try {
                Socket sock = new Socket("unitycraft.de", 2009);
                out = new ObjectOutputStream(sock.getOutputStream());
                in = new ObjectInputStream(sock.getInputStream());
    
                // Listen for remote stuff comming in ...
                remote = new Thread(new RemoteReader(in,out,sock,controller.));
                remote.start();
            } catch (Exception ex) { ex.printStackTrace(); }
            stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
            stage.setScene(scene);
            stage.show();
        }
    
        /**
         * The main() method is ignored in correctly deployed JavaFX application.
         * main() serves only as fallback in case the application can not be
         * launched through deployment artifacts, e.g., in IDEs with limited FX
         * support. NetBeans ignores main().
         *
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    并且我在FXMLController中添加了这个方法,加上类字段的声明(in,out,sock):

    void initData(ObjectInputStream in, ObjectOutputStream out, Socket sock) {
            this.in = in;
            this.out = out;
            this.sock = sock;
        }
    

    现在我可以从 FXMLController 中访问输出流。但现在我无法从 RemoteReader.java 中访问 textarea。我开始了一个新问题。 ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 2022-10-07
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多