Skip to content

Instantly share code, notes, and snippets.

@renatoathaydes
Created July 7, 2024 14:18
Show Gist options
  • Save renatoathaydes/758f2ccbb1f862026c92d35209a983a0 to your computer and use it in GitHub Desktop.
Save renatoathaydes/758f2ccbb1f862026c92d35209a983a0 to your computer and use it in GitHub Desktop.
JavaFX simple app - illustration of bug setting text fill color inside a Label
.root {
-fx-base: #1d1d1d;
-icons-color: rgb(61, 114, 144);
}
.line {
-fx-font-family: Lucida;
-fx-font-size: 18px;
}
.line.selected {
-fx-background-color: -fx-focus-color;
-fx-text-fill: derive(-fx-focus-color, -80%);
}
package app;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.List;
import java.util.function.Consumer;
public class TestApp extends Application {
public static void main( String[] args ) {
launch( args );
}
@Override
public void start( Stage primaryStage ) throws Exception {
var css = TestApp.class.getResource( "/style.css" ).toExternalForm();
var pane = new SplitPane( makePane(), makePane() );
primaryStage.setWidth( 400.0 );
primaryStage.setHeight( 400.0 );
primaryStage.setTitle( "Test" );
Scene scene = new Scene( pane );
scene.getStylesheets().add( css );
primaryStage.setScene( scene );
primaryStage.show();
}
Node makePane() {
var box = new VBox( 0 );
Consumer<Label> changeSelection = ( label ) -> {
for ( Node child : box.getChildren() ) {
if ( child instanceof Label ) {
if ( child == label && !child.getStyleClass().contains( "selected" ) )
child.getStyleClass().add( "selected" );
else child.getStyleClass().remove( "selected" );
}
}
};
box.getChildren().addAll( List.of(
new MyLabel( changeSelection ),
new MyLabel( changeSelection ),
new MyLabel( changeSelection ),
new HBox( 10, makeButton( "OK", box ) )
) );
return box;
}
private static Button makeButton( String text, Parent parent ) {
var button = new Button( text );
button.setOnAction( event -> {
for ( Node node : parent.getChildrenUnmodifiable() ) {
if ( node instanceof MyLabel myLabel ) {
myLabel.resetColor();
}
}
} );
return button;
}
}
class MyLabel extends Label {
public MyLabel( Consumer<Label> changeSelection ) {
setBackground( new Background( new BackgroundFill( Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY ) ) );
getStyleClass().add( "line" );
setTextFill( Color.YELLOW );
setText( "Hello world" );
setMinWidth( 200.0 );
setOnMouseClicked( event -> changeSelection.accept( this ) );
}
void resetColor() {
setTextFill( Color.YELLOW );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment