bitFuzzy
bitFuzzy

Reputation: 37

On Mouse Entered Method to swap Button position

I would like to develop a mouse entered method that swaps the locations of two buttons in real time using FXML and JavaFX which I am unfortunately very new to. Relocate(x,y), get/setLayoutX/Y and below get/setTranslateX/Y all throw IllegalArgumentEceptions with not much more understandable information in the stack trace. What is the preferred Button Property to use in order to get and then set a real-time location swap?

@FXML protected void neinHover (ActionEvent evt){

        double jTmpX, jTmpY, nTmpX, nTmpY;
        nTmpX = neinButton.getTranslateX();
        nTmpY = neinButton.getTranslateY();
        jTmpX = jaButton.getTranslateX();
        jTmpY = jaButton.getTranslateY();
        jaButton.setTranslateX(nTmpX);
        jaButton.setTranslateY(nTmpY);
        neinButton.setTranslateX(jTmpX);
        neinButton.setTranslateY(jTmpY);    
    }

Upvotes: 0

Views: 500

Answers (1)

Suicide Platypus
Suicide Platypus

Reputation: 185

I supose you want something like this:

FXML:

<fx:root onMouseClicked="#swap" type="Pane" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
    <children>
        <Button fx:id="b1" mnemonicParsing="false" text="1" />
        <Button fx:id="b2" layoutX="90.0" mnemonicParsing="false" text="2" />
    </children>
</fx:root>

Controller:

public class MockPane extends Pane {
    @FXML
    private Button b1;
    @FXML
    private Button b2;


    public MockPane() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(
                "MockPane.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @FXML
    private void swap() {
        double b1x = b1.getLayoutX();
        double b1y = b1.getLayoutY();
        double b2x = b2.getLayoutX();
        double b2y = b2.getLayoutY();
        b1.setLayoutX(b2x);
        b1.setLayoutY(b2y);
        b2.setLayoutX(b1x);
        b2.setLayoutY(b1y);
    }
}

App:

public class MockApp extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }


    @Override
    public void start(Stage stage) throws Exception {
        MockPane root = new MockPane();
        Scene scene = new Scene(root, 200, 100);
        stage.setScene(scene);
        stage.show();
    }
}

Upvotes: 1

Related Questions