[英]Background with 2 colors in JavaFX?
在JavaFX 2中,可以使用CSS創建具有2種顏色的背景嗎? 考慮一下一個高度為10像素的TableCell
。 我希望前2像素(垂直)為紅色,其余8像素(垂直)應保持默認背景色。 在JavaFX 2中使用CSS是否可行? 怎么樣?
例:
原始背景:
所需結果:
(上方的2個像素已替換為紅色)
感謝您對此的任何提示!
我使用了簡單的背景顏色層來產生紅色高光(類似於Stefan建議的解決方案)。
/**
* file: table.css
* Place in same directory as TableViewPropertyEditorWithCSS.java.
* Have your build system copy this file to your build output directory.
**/
.highlighted-cell {
-fx-text-fill: -fx-text-inner-color;
-fx-background-color: firebrick, gainsboro;
-fx-background-insets: 0, 2 0 0 0;
}
對於像堆棧窗格這樣的標准區域,您真正需要做的就是應用上面的css(減去-fx-text-fill
)以獲得所需的結果。
這是使用漸變定義顏色的另一種技巧:
-fx-background-color:
linear-gradient(
from 0px 0px to 0px 2px,
firebrick, firebrick 99%,
gainsboro
);
在下面的屏幕快照中,如果值為false
,則將值單元格突出顯示(通過將highlighted-cell
css類應用於它們)。
突出顯示單元格樣式類切換邏輯:
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
....
getStyleClass().remove("highlighted-cell");
} else {
if (getItem() instanceof Boolean && (Boolean.FALSE.equals((Boolean) getItem()))) {
getStyleClass().add("highlighted-cell");
} else {
getStyleClass().remove("highlighted-cell");
}
...
}
}
當highlighted-cell
樣式類應用於標准表單元格(在對自定義單元格的updateItem調用期間)時,看起來不錯,但確實有一些缺點。 表格的着色方案非常微妙和復雜。 它具有奇數/偶數值的突出顯示,選定行的突出顯示,選定懸停的行的突出顯示,聚焦行和單元格的突出顯示等。此外,它還具有上述所有內容的各種組合。 只是直接在Highlight-Cell類中設置背景顏色是一種實現所需內容的蠻力方式,因為它沒有考慮所有其他細微之處,而是將它們覆蓋了,因此使用此方法突出顯示的單元格無論已將哪種臨時CSS偽類狀態應用於樣式,樣式始終看起來相同。
真的很好,但是更好的解決方案將根據偽類狀態對突出顯示的單元格進行不同的着色。 但這是一件非常棘手的事情,您可能會浪費大量時間來嘗試各種狀態和CSS選擇器組合,以嘗試獲得變化多端的亮點。 總體而言,對於本示例而言,對我來說似乎不值得付出額外的努力,盡管這可能對您而言。
測試程序(對此的長度和復雜性深表歉意,對我而言,將樣式突出顯示邏輯集成到現有程序中比較容易):
import java.lang.reflect.*;
import java.util.logging.*;
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;
// click in the value column (a couple of times) to edit the value in the column.
// property editors are defined only for String and Boolean properties.
// change focus to something else to commit the edit.
public class TableViewPropertyEditorWithCSS extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
final Person aPerson = new Person("Fred", false, false, "Much Ado About Nothing");
final Label currentObjectValue = new Label(aPerson.toString());
TableView<NamedProperty> table = new TableView();
table.setEditable(true);
table.setItems(createNamedProperties(aPerson));
TableColumn<NamedProperty, String> nameCol = new TableColumn("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<NamedProperty, String>("name"));
TableColumn<NamedProperty, Object> valueCol = new TableColumn("Value");
valueCol.setCellValueFactory(new PropertyValueFactory<NamedProperty, Object>("value"));
valueCol.setCellFactory(new Callback<TableColumn<NamedProperty, Object>, TableCell<NamedProperty, Object>>() {
@Override
public TableCell<NamedProperty, Object> call(TableColumn<NamedProperty, Object> param) {
return new EditingCell();
}
});
valueCol.setOnEditCommit(
new EventHandler<CellEditEvent<NamedProperty, Object>>() {
@Override
public void handle(CellEditEvent<NamedProperty, Object> t) {
int row = t.getTablePosition().getRow();
NamedProperty property = (NamedProperty) t.getTableView().getItems().get(row);
property.setValue(t.getNewValue());
currentObjectValue.setText(aPerson.toString());
}
});
table.getColumns().setAll(nameCol, valueCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");
layout.getChildren().setAll(
currentObjectValue,
table);
VBox.setVgrow(table, Priority.ALWAYS);
Scene scene = new Scene(layout, 650, 600);
scene.getStylesheets().add(getClass().getResource("table.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
private ObservableList<NamedProperty> createNamedProperties(Object object) {
ObservableList<NamedProperty> properties = FXCollections.observableArrayList();
for (Method method : object.getClass().getMethods()) {
String name = method.getName();
Class type = method.getReturnType();
if (type.getName().endsWith("Property")) {
try {
properties.add(new NamedProperty(name, (Property) method.invoke(object)));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(TableViewPropertyEditorWithCSS.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return properties;
}
public class NamedProperty {
public NamedProperty(String name, Property value) {
nameProperty.set(name);
valueProperty = value;
}
private StringProperty nameProperty = new SimpleStringProperty();
public StringProperty nameProperty() {
return nameProperty;
}
public StringProperty getName() {
return nameProperty;
}
public void setName(String name) {
nameProperty.set(name);
}
private Property valueProperty;
public Property valueProperty() {
return valueProperty;
}
public Object getValue() {
return valueProperty.getValue();
}
public void setValue(Object value) {
valueProperty.setValue(value);
}
}
public class Person {
private final SimpleStringProperty firstName;
private final SimpleBooleanProperty married;
private final SimpleBooleanProperty hasChildren;
private final SimpleStringProperty favoriteMovie;
private Person(String firstName, Boolean isMarried, Boolean hasChildren, String favoriteMovie) {
this.firstName = new SimpleStringProperty(firstName);
this.married = new SimpleBooleanProperty(isMarried);
this.hasChildren = new SimpleBooleanProperty(hasChildren);
this.favoriteMovie = new SimpleStringProperty(favoriteMovie);
}
public SimpleStringProperty firstNameProperty() {
return firstName;
}
public SimpleBooleanProperty marriedProperty() {
return married;
}
public SimpleBooleanProperty hasChildrenProperty() {
return hasChildren;
}
public SimpleStringProperty favoriteMovieProperty() {
return favoriteMovie;
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public Boolean getMarried() {
return married.get();
}
public void setMarried(Boolean isMarried) {
married.set(isMarried);
}
public Boolean getHasChildren() {
return hasChildren.get();
}
public void setHasChildren(Boolean hasChildren) {
this.hasChildren.set(hasChildren);
}
public String getFavoriteMovie() {
return favoriteMovie.get();
}
public void setFavoriteMovie(String movie) {
favoriteMovie.set(movie);
}
@Override
public String toString() {
return firstName.getValue() + ", isMarried? " + married.getValue() + ", hasChildren? " + hasChildren.getValue() + ", favoriteMovie: " + favoriteMovie.get();
}
}
class EditingCell extends TableCell<NamedProperty, Object> {
private TextField textField;
private CheckBox checkBox;
public EditingCell() {
}
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
if (getItem() instanceof Boolean) {
createCheckBox();
setText(null);
setGraphic(checkBox);
} else {
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
if (getItem() instanceof Boolean) {
setText(getItem().toString());
} else {
setText((String) getItem());
}
setGraphic(null);
}
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
getStyleClass().remove("highlighted-cell");
} else {
if (getItem() instanceof Boolean && (Boolean.FALSE.equals((Boolean) getItem()))) {
getStyleClass().add("highlighted-cell");
} else {
getStyleClass().remove("highlighted-cell");
}
if (isEditing()) {
if (getItem() instanceof Boolean) {
if (checkBox != null) {
checkBox.setSelected(getBoolean());
}
setText(null);
setGraphic(checkBox);
} else {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
}
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
commitEdit(textField.getText());
}
}
});
}
private void createCheckBox() {
checkBox = new CheckBox();
checkBox.setSelected(getBoolean());
checkBox.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
checkBox.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
commitEdit(checkBox.isSelected());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
private Boolean getBoolean() {
return getItem() == null ? false : (Boolean) getItem();
}
}
}
看,如何理解CSSRef:
http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
看着
-fx-background-image:
uri [,uri] *
一系列圖像URI,以逗號分隔。
看着
-fx背景重復
重復樣式[,重復樣式] *
其中repeat-style = repeat-x | 重復- [重復| 空間 圓形 伸展 無重復] {1,2}
一系列用逗號分隔的值。 系列中的每個重復樣式項均適用於背景圖像系列中的相應圖像。
看:-fx-background-position
bg-position [,bg-position] *其中= [[[size | 左| 中心| 對] [大小| 頂部| 中心| 底部]? ] | [[中心| [左| 合適的尺碼? ] || [中心| [頂部| 底部]大小? ]
一系列用逗號分隔的值。 系列中的每個bg-position項目都適用於背景圖像系列中的相應圖像。
因此,您會看到什么:您應該描述2張圖像(每個2x2像素-一個紅色和一個-灰色)兩個bg位置,以及每個圖像對應的兩個重復樣式。
怎么樣?
例如:
{
-fx-backdround-image : "path_to_red", "path_to_grey";
-fx-background-repeat : repeat-x, stretch;
-fx-background-position : 0px 0px, 0px 2px;
}
我不保證代碼的實用性,但是這個想法似乎是正確的。
使用插圖時,可能僅使用顏色而不是圖像。 來自原始JavaFX CSS的示例:
.table-row-cell:odd {
-fx-background-color: -fx-table-cell-border-color, derive(-fx-control-inner-background,-5%);
-fx-background-insets: 0, 0 0 1 0;
}
[6個字符...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.