2014-02-27 55 views
1

我想用我的javafx应用程序设置外部css文件的样式,但是当我添加css文件时,它不会产生任何区别。我使用Netbeans 7.4 IDE和jdk8,虽然代码没有指出任何错误或异常,但我没有得到所需的输出。我总是很困惑该怎么做。我的代码是...如何使用外部css文件来设置javafx应用程序的样式

package manualstyle; 

import java.io.File; 
import java.net.URL; 
import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.stage.Stage; 

/** 
* 
* @author vickyjonnes 
*/ 
public class ManualStyle extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Group root=new Group(); 
     Scene scene = new Scene(root, 300, 250); 

     Button btn = new Button(); 
     btn.setText("Say 'Hello World'"); 
     btn.setLayoutX(100); 
     btn.setLayoutY(100); 
     btn.setOnAction(new EventHandler<ActionEvent>() { 

      @Override 
      public void handle(ActionEvent event) { 
       System.out.println("Hello World!"); 
      } 
     }); 



     root.getChildren().add(btn); 
     primaryStage.setScene(scene); 
     String css = ManualStyle.class.getResource("myStyle.css").toExternalForm(); 
     scene.getStylesheets().add(css); 
     primaryStage.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); 
    } 
} 

我必须驻留在同一目录和css文件的内容是一个CSS文件:

.root{ 
    -fx-background-color: #ff0066; 
} 
+0

你确定你没有得到任何'warnings'? – ItachiUchiha

+0

不,我没有收到任何警告 –

+0

你可以尝试通过在css中添加代码来给按钮添加颜色:.button {{0} {0} {%} -fx-border-color:rgb(49,89,23); }' – ItachiUchiha

回答

2

请通过以下解决方案。让我知道,如果你仍然面临的问题:

https://stackoverflow.com/a/22048338/1759128

+0

当我使用/ myStyle.css之前,我得到一个NullPOinterExecption –

+0

是的,我明白了!问题不在于'/',当它在某个文件夹内部使用css时! – ItachiUchiha

+0

我的src文件夹中没有任何xml文件,我甚至不想制作一个文件,因为我不想让这些东西变得复杂。 我只有两个文件在src文件夹中,一个是我的java主类文件,另一个是我的css文件锄头来连接它们两个 –

相关问题