Bar*_*ron 5 textarea drag-and-drop javafx-8
经过数小时的代码挖掘和Web浏览以寻找解决方案之后,我决定将我的问题发布在这里。
我目前正在使用Java 8u45。我需要允许从TextField和拖动选定的文本TextArea。尽管它可以正常运行TextField,但不能运行TextArea-选择在拖动之前就更改了。
在一些工作示例下面-只需选择部分文本并将其拖到例如记事本的某个位置即可:
public class DnD extends Application
{
private static final GridPane rootPane = new GridPane();
private TextField textField;
private TextArea textArea;
public static void main( final String[] args )
{
launch( args );
}
@Override
public void start( final Stage primaryStage )
{
primaryStage.setTitle( "Drag and Drop Application" );
buildGui();
installDnd();
primaryStage.setScene( new Scene( rootPane, 400, 325 ) );
primaryStage.show();
}
private void installDnd()
{
textField.setOnDragDetected( e -> {
if( canDrag( textField, e ) )
{
Dragboard dragboard = textField.startDragAndDrop( TransferMode.COPY );
putIntoDragboard( dragboard, textField.getSelectedText() );
e.consume();
}
} );
textArea.setOnDragDetected( e -> {
if( canDrag( textArea, e ) )
{
Dragboard dragboard = textArea.startDragAndDrop( TransferMode.COPY );
putIntoDragboard( dragboard, textArea.getSelectedText() );
e.consume();
}
} );
}
private void putIntoDragboard( final Dragboard aDragboard, final String aText )
{
ClipboardContent content = new ClipboardContent();
content.put( DataFormat.PLAIN_TEXT, aText );
aDragboard.setContent( content );
}
private boolean canDrag( final HitInfo aHitInfo, final IndexRange aSelection, final String aSelectedText )
{
int insertionPoint = aHitInfo.getInsertionIndex();
// Start drag only if started over selected text
boolean dragOverText = aSelection.getStart() < insertionPoint && aSelection.getEnd() > insertionPoint;
return dragOverText && !(aSelectedText == null || aSelectedText.length() == 0);
}
private boolean canDrag( final TextField aTextField, final MouseEvent aEvent )
{
TextFieldSkin skin = (TextFieldSkin)aTextField.getSkin();
HitInfo insertionPointInfo = skin.getIndex( aEvent.getX(), aEvent.getY() );
return canDrag( insertionPointInfo, aTextField.getSelection(), aTextField.getSelectedText() );
}
private boolean canDrag( final TextArea aTextArea, final MouseEvent aEvent )
{
TextAreaSkin skin = (TextAreaSkin)aTextArea.getSkin();
HitInfo insertionPointInfo = skin.getIndex( aEvent.getX(), aEvent.getY() );
return canDrag( insertionPointInfo, aTextArea.getSelection(), aTextArea.getSelectedText() );
}
private void buildGui()
{
textField = new TextField( "text field: sample text" );
textArea = new TextArea( "text area: sample text" );
rootPane.add( textField, 0, 0 );
rootPane.add( textArea, 0, 1 );
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在不自己写皮肤的情况下使它工作?无法替换TextAreaBehavior内部TextAreaSkin(就像TextFieldBehavior传递到TextFieldSkin的构造函数中一样)。
对此,我将不胜感激。
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |