经过几个小时的代码挖掘和网页浏览以寻找解决方案后,我决定在这里发布我的问题。
我目前正在使用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 );
}
}
是否可以在不编写自己的皮肤的情况下使其工作?无法替换TextAreaBehavior
内的TextAreaSkin
(就像TextFieldBehavior
传入TextFieldSkin
的构造函数)。
如果有任何帮助,我将不胜感激。