在JavaFX中如何使Text内容在一段时间后消失?
b1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
preparedStatement = connect
.prepareStatement("select * from mark where clsnum = " + txt1.getText() + "");
rs = preparedStatement.executeQuery();
if (rs.next()) {
delete();
} else {
msg.setText("Student Not Found...!");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DeleteMark.class.getName()).log(Level.SEVERE,null,ex);
}
}
});
这是我的代码,如果查询不起作用,则显示消息(我的意思是如果没有行返回到ResultSet rs). msg是Text的对象,其声明和其他细节是 – Text msg = new Text();
msg.setFont(Font.font("Calibri",FontWeight.THIN,18));
msg.setFill(Color.RED);
我希望文本在一段时间后消失,比如3或4秒.是否可以在JavaFX中执行此操作(借助计时器或您知道的其他内容)?如果有,怎么样? 解决方法
使用
Timelines和/或
Transitions.
这个答案是针对问题的前一次迭代. 示例解决方案代码 import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class BlinkingAndFading extends Application {
@Override
public void start(Stage stage) {
Label label = new Label("Blinking");
label.setStyle("-fx-text-fill: red; -fx-padding: 10px;");
Timeline blinker = createBlinker(label);
blinker.setOnFinished(event -> label.setText("Fading"));
FadeTransition fader = createFader(label);
SequentialTransition blinkThenFade = new SequentialTransition(
label,blinker,fader
);
stage.setScene(new Scene(new StackPane(label),100,50));
stage.show();
blinkThenFade.play();
}
private Timeline createBlinker(Node node) {
Timeline blink = new Timeline(
new KeyFrame(
Duration.seconds(0),new KeyValue(
node.opacityProperty(),1,Interpolator.DISCRETE
)
),new KeyFrame(
Duration.seconds(0.5),new KeyFrame(
Duration.seconds(1),Interpolator.DISCRETE
)
)
);
blink.setCycleCount(3);
return blink;
}
private FadeTransition createFader(Node node) {
FadeTransition fade = new FadeTransition(Duration.seconds(2),node);
fade.setFromValue(1);
fade.setToValue(0);
return fade;
}
public static void main(String[] args) {
launch(args);
}
}
其他问题的答案
您应该使用Java 8而不是设置-source 1.7.如果您希望坚持使用Java 7(我不建议JavaFX工作),您可以替换Lambda: blinker.setOnFinished(event -> label.setText("Fading"));
有: blinker.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
label.setText("Fading");
}
});
同样,您应该使用Java 8.但是如果您希望使用Java 7,请替换: stage.setScene(new Scene(new StackPane(label),50)); 有: StackPane layout = new StackPane(); layout.getChildren().add(label); stage.setScene(new Scene(layout,50)); 进一步建议 好的呼吁没有文字眨眼和褪色.闪烁的文字会让人分心,但只是褪色很好. 我不认为我建议淡出错误消息,至少在用户点击它之前或类似之前.如果用户在消失之前没有看到错误消息怎么办? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
