给javafx2的tableview添加行颜色以及字体的颜色

package com.lee.platform.testtry;

import java.text.MessageFormat;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * 
 * @author lee
 */
public class TableCellTextColorExample extends Application {
	public static class TableData {
		SimpleStringProperty one, two, three;

		public TableData(String one, String two, String three) {
			this.one = new SimpleStringProperty(one);
			this.two = new SimpleStringProperty(two);
			this.three = new SimpleStringProperty(three);
		}

		public String getOne() {
			return one.get();
		}

		public void setOne(String one) {
			this.one.set(one);
		}

		public String getThree() {
			return three.get();
		}

		public void setThree(String three) {
			this.three.set(three);
		}

		public String getTwo() {
			return two.get();
		}

		public void setTwo(String two) {
			this.two.set(two);
		}

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String[] args) {
		Application.launch(args);
	}

	@Override
	public void start(Stage stage) {
		VBox vbox = new VBox();
		Scene scene = new Scene(vbox, 200, 200);
		stage.setTitle("Table View - Change color of a particular column");
		stage.setWidth(400);
		stage.setHeight(500);

		TableView<TableData> myTable = new TableView<TableData>();
		ObservableList<TableData> myTableData = FXCollections
				.observableArrayList(new TableData("data", "data2", "data3"),
						new TableData("data", "data2", "data4"), new TableData(
								"Name the song", "867-5309",
								"SomeEmail@gmail.com"));

		TableColumn firstColumn = new TableColumn("First Column");
		firstColumn
				.setCellValueFactory(new PropertyValueFactory<TableData, String>(
						"one"));

		TableColumn secondColumn = new TableColumn("Second Column");
		secondColumn
				.setCellValueFactory(new PropertyValueFactory<TableData, String>(
						"two"));

		TableColumn thirdColumn = new TableColumn("Third Column");
		thirdColumn
				.setCellValueFactory(new PropertyValueFactory<TableData, String>(
						"three"));

		// ** The TableCell class has the method setTextFill(Paint p) that you
		// ** need to override the text color
		// To obtain the TableCell we need to replace the Default CellFactory
		// with one that returns a new TableCell instance,
		// and @Override the updateItem(String item, boolean empty) method.
		//
		thirdColumn.setCellFactory(new Callback<TableColumn, TableCell>() {
			public TableCell call(TableColumn param) {
				return new TableCell<TableData, String>() {
					ObservableValue ov;
					@Override
					public void updateItem(String item, boolean empty) {
						super.updateItem(item, empty);
						if (!isEmpty()) {
							ov = getTableColumn().getCellObservableValue(getIndex());
				        	 System.out.println(ov.getValue());
				        	 
							if(getTableRow() != null&&item.contains("@")){
								this.getTableRow().setStyle("-fx-background-color: green");
							}
							this.setTextFill(Color.RED);
							// Get fancy and change color based on data
							if (item.contains("@"))
								this.setTextFill(Color.YELLOW);
							setText(item);
						}
						/*if (!empty && getTableRow() != null) {
				            int row = this.getTableRow().getIndex();
				            //ProjectionInfo projectionInfo = getTableView().getItems().get(row);
				            Color regionColor = Color.RED;
				            String style = MessageFormat.format("-fx-background-color: rgba({0}%, {1}%, {2}%, 0.3);", regionColor.getRed() * 100, regionColor.getGreen() * 100, regionColor.getBlue() * 100); // NOI18N.
				            setStyle(style);
						}*/
						/*if (!isEmpty()&& getTableRow() != null) {
							int row = this.getTableRow().getIndex();
							System.out.println("row:"+row);
                            this.setStyle("-fx-background-color: linear-gradient(to bottom right, #a1c517, #009045, #0082b6, #151f77, #db004f);");
                            setText(item);
                        }*/
					}
				};
			}
		});

		myTable.setItems(myTableData);
		myTable.getColumns().addAll(firstColumn, secondColumn, thirdColumn);

		vbox.getChildren().addAll(myTable);
		VBox.setVgrow(myTable, Priority.ALWAYS);

		stage.setScene(scene);
		stage.show();
	}
}


如果要对行加颜色,就要在创建列的时候,对每一个列进行判断,然后再赋值,相当于对每一个cell的字体颜色进行赋值。

因为this.getTableRow().setStyle("-fx-text-fill: #006464;"); 并不好用,而this.getTableRow().setStyle("-fx-background-color: "+"#F00FF6");就可以。

是不是Javafx2的bug呢?部分代码如下:

public TableView initTable(JSONArray tablecolJson,JSONObject tableinfo) {
        //JSONArray tablecolJson,JSONObject tableinfo,JSONObject tablePage
        JSONObject jsonObject = null;
        table = new TableView<>();
        String twidth = (String)tableinfo.get("width");
        String theight = (String)tableinfo.get("height");
        String tboder = (String)tableinfo.get("boder");
        String ttop = (String)tableinfo.get("top");
        String tleft = (String)tableinfo.get("left");
        String tisselect = (String)tableinfo.get("isselect");
        String tselectstyle = "";
        if("true".equals(tisselect)){
            tselectstyle = (String)tableinfo.get("selectstyle");
        }
        for (int j = 0; j < tablecolJson.size(); j++) {
            jsonObject = (JSONObject)tablecolJson.get(j);
            String id = jsonObject.get("id").toString().toUpperCase();
            String title = (String)jsonObject.get("title");
            String width = (String)jsonObject.get("width");
            if(id==null||id.equals("")){
                System.out.println("未设置列id,请重新设置!");
                return null;
            }
            if(title==null||title.equals("")){
                title = "请输入标题名";
            }
            if(width==null||width.equals("")){
                title = "60";
            }
            tableColu = new TableColumn<>(title);
            tableColu.setCellValueFactory(new MapValueFactory(id));
            tableColu.setCellFactory(new Callback<TableColumn, TableCell>() {
                public TableCell call(TableColumn param) {
                    return new TableCell<String, String>() {
                        ObservableValue ov;
                        @Override
                        public void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            if (!empty) {
                                ov = getTableColumn().getCellObservableValue(getIndex());
                                if(getTableRow() != null&&!ov.equals("")){
                                    Map<String,String> vmap = (Map<String,String>)this.getTableRow().getItem();
                                    boolean colorFlag = false;
                                    if(vmap.get("TEXT_COLOR")!=null){
                                        if(!vmap.get("TEXT_COLOR").equals("")){
                                            this.setStyle("-fx-text-fill: "+vmap.get("TEXT_COLOR"));
                                            colorFlag = true;
                                        }
                                    }
                                    if(vmap.get("BACKGROUND_COLOR")!=null){
                                        if(!vmap.get("BACKGROUND_COLOR").equals("")){
                                            if(!colorFlag){
                                                this.setStyle("-fx-background-color: "+vmap.get("BACKGROUND_COLOR"));
                                            }else{
                                                this.setStyle("-fx-background-color: "+vmap.get("BACKGROUND_COLOR")+";"+"-fx-text-fill: "+vmap.get("TEXT_COLOR"));
                                            }
                                        }
                                    }
                                }
                                setText(item);
                            }
                        }
                    };
                }
            });
            tableColu.setPrefWidth(Double.valueOf(width));
            table.getColumns().add(tableColu);
        }
        if(ttop==null||ttop.equals("")){
            ttop = "190";
        }
        if(tleft==null||tleft.equals("")){
            ttop = "20";
        }
        AnchorPane.setTopAnchor(table, Double.valueOf(ttop));
        AnchorPane.setLeftAnchor(table, Double.valueOf(tleft));
        return table;
    }



参考:http://stackoverflow.com/questions/6998551/setting-font-color-of-javafx-tableview-cells

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值