【发布时间】:2016-06-06 17:51:06
【问题描述】:
我正在学习 javafx,现在我正在尝试将我学到的技术应用到我的 java 应用程序中。我的程序称为“WhatsTheTime”,它是一个简单的程序,由一个带有时钟图像的 AnchorPane 组成。单击窗格时,应该将 ImageView 后面的标签文本设置为当前时间,并将时钟图像设置为不可见。当我尝试运行该应用程序时,我在loader.load() 语句中得到了一个runtimeException。上网查了一下,发现多半是文件名指定不正确,但我查了一下文件名,绝对正确。
这是我的 fxml 代码:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<fx:root type = "AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity"
minHeight="-Infinity" minWidth="-Infinity" onMouseClicked="#getTheTime" prefHeight="198.0" prefWidth="208.0" type="AnchorPane"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="myPrototypes.WhatsTheTime">
<children>
<Rectangle arcHeight="5.0" arcWidth="5.0" height="200.0" stroke="BLACK" strokeType="INSIDE" width="208.0" />
<Label fx:id="timeLabel" layoutX="90.0" layoutY="90.0" text="Label" />
<ImageView fx:id="clockImage" fitHeight="186.0" fitWidth="193.0" layoutX="7.0" layoutY="7.0">
<image>
<Image url="@../../What'sTheTimeIcon.png" />
</image>
</ImageView>
</children>
</fx:root>
这是我的控制器类:
package myPrototypes;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
public class WhatsTheTime extends AnchorPane{
@FXML
private ImageView clockImage;
@FXML
private Label timeLabel;
WhatsTheTime(){
FXMLLoader loader = new FXMLLoader
(getClass().getResource("WhatsTheTime.fxml"));
loader.setRoot(this);
loader.setController(this);
try{
loader.load();
}
catch(IOException e){
throw new RuntimeException();
}
}
@FXML
public void getTheTime(){
clockImage.setVisible(false);
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
Date date = new Date();
timeLabel.setText(timeFormat.format(date));
}
}
这是我的主要课程:
package myPrototypes;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class WhatsTheTimeMain extends Application {
@Override
public void start(Stage primaryStage) {
WhatsTheTime component = new WhatsTheTime();
Scene scene = new Scene(component);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
请帮我解决这个问题。如果您需要任何其他信息,请告诉我
【问题讨论】:
-
请发布异常堆栈跟踪 - 您可以通过在您的
catch块中添加e.printStackTrace()在控制台中获取它。 -
在 samle 元素中使用
type属性两次可能不是最好的主意... -
@fabian,您的想法也与下面的答案一起工作。非常感谢您的贡献