我想在表格视图中添加一个上下文菜单,更具体地说,我想在右键单击时在表格行上显示上下文菜单。
我试过这段代码
final EventHandler click = new EventHandler() {
public void handle(MouseEvent t) {
}
@Override
public void handle(Event arg0) {
}
};
final Context menu = new ContextMenu();
MenuItem item = new MenuItem("Add Image");
item.setOnAction(new EventHandler() {
public void handle(ActionEvent t)
{
}
@Override
public void handle(Event arg0)
{
//some code here
}});
menu.getItems().addAll(item);
EditingCell cellFactory = new EditingCell(click,menu);
TableColumn col = new TableColumn("column1");
col.setCellFactory(cellFactory);
上面的代码在 JAVAFX 2.0 中正常工作,我在右键单击时获得了一个上下文菜单,但是当我使用 JAVAFX 2.1 运行我的代码时,上下文菜单不起作用。
我尝试使用showingProperty()方法获取上下文菜单的显示属性,它在JAVAFX 2.1中返回false,在JAVAFX 2.0中返回true
此外,我还尝试制作我的自定义 cellfactory 类,这是我的代码(我从官方 JAVAFX TreeView 上下文菜单示例中获取)
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
class TextFieldTreeCellImpl extends TableCell<String,String> {
private TextField textField;
private ContextMenu addMenu = new ContextMenu();
public TextFieldTreeCellImpl() {
MenuItem addMenuItem = new MenuItem("Add Employee");
addMenu.getItems().add(addMenuItem);
addMenuItem.setOnAction(new EventHandler() {
public void handle(Event t) {
}
});
setContextMenu(addMenu);
}
@Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setText(null);
setGraphic(textField);
textField.selectAll();
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
//setGraphic(getTableCell().getGraphic());
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
//setGraphic(getTreeItem().getGraphic());
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
我将此自定义单元工厂添加为:
final Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new TextFieldTreeCellImpl();
}
};
col.setCellFactory(cellFactory);
它在 JAVAFX 2.0 中仍然可以正常工作,但在 JAVAFX 2.1 中却不行
请帮助我,我很难...