2014-04-25 39 views
2

我知道如何使用JFXPanel在swing中集成javafx組件。但它很難編寫組件的所有屬性。而且,也不可能爲javafx組件提供css屬性。那麼是否有可能將整個fxml文件集成到JFXPanel中? 謝謝使用JFXPanel在swing中集成fxml文件

回答

3

要爲javafx組件提供css屬性,只需將樣式表添加到您在JFXPanel上設置的場景。

要使用FXML來定義JFXPanel顯示的部件,使用FXMLLoader照常加載FXML文件,並使用其結果作爲SceneJFXPanel根。

例如:

import java.awt.BorderLayout; 
import java.io.IOException; 

import javafx.application.Platform; 
import javafx.embed.swing.JFXPanel; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 


public class Test { 
    private void initSwingComponents() { 
     JFrame frame = new JFrame("Java FX in Swing"); 
     frame.setLayout(new BorderLayout()); 
     final JFXPanel jfxPanel = new JFXPanel(); 
     frame.add(jfxPanel, BorderLayout.CENTER); 
     final JPanel swingButtons = new JPanel(); 
     final JButton okButton = new JButton("OK"); 
     okButton.addActionListener(event -> System.out.println("Swing says 'OK'")); 
     final JButton exitButton = new JButton("Exit"); 
     exitButton.addActionListener(event -> System.exit(0)); 
     swingButtons.add(okButton); 
     swingButtons.add(exitButton); 
     frame.add(swingButtons, BorderLayout.SOUTH); 

     frame.setSize(300, 200); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
      okButton.requestFocus(); 

     Platform.runLater(() -> initFX(jfxPanel)); 
    } 

    private void initFX(JFXPanel jfxPanel) { 
     try { 
      Parent root = FXMLLoader.load(getClass().getResource("FXComponents.fxml")); 
      Scene scene = new Scene(root, 250, 150); 
      scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm()); 
      jfxPanel.setScene(scene); 
     } catch (IOException exc) { 
      exc.printStackTrace(); 
      System.exit(1); 
     } 
    } 

    public static void main(String[] args) { 
     Test test = new Test(); 
     SwingUtilities.invokeLater(() -> test.initSwingComponents()); 
    } 
} 

FXComponents.fxml:

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

<?import javafx.scene.layout.VBox?> 
<?import javafx.scene.control.TextField?> 
<?import javafx.scene.control.Button?> 

<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="Controller" spacing="5" alignment="CENTER"> 
<TextField fx:id="textField" promptText="Enter message here"/> 
    <Button text="Print message" onAction="#printMessage" />  
</VBox> 

的style.css:

@CHARSET "UTF-8"; 
.button { 
    -fx-base: cornflowerblue ; 
} 
.text-field { 
    -fx-text-fill: blue ; 
    -fx-font-size: 18pt ; 
} 

Controller.java:

import javafx.fxml.FXML; 
import javafx.scene.control.TextField; 

public class Controller { 
    @FXML 
    private TextField textField ; 

    @FXML 
    private void printMessage() { 
     System.out.println(textField.getText()); 
    } 
}