我正在谈论的事件就是这样:当用户将光标移动到按钮所在的位置时,它将变为不同的颜色。一旦退出,它就会变回原来的颜色。我已经实现了这一点,我要问的是如何编写每个按钮以使用相同的两个事件?请记住,每个按钮的行为都不同,但每个按钮的事件都是相同的。
以下是相关代码
我的FXML控制器类
package millionairetriviagame;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class MenulayoutFXMLController implements Initializable
{
@FXML private Button playButton;
@Override
public void initialize(URL url, ResourceBundle rb)
{
Media gameIntroTheme = new Media(getClass().getResource("/millionairetriviagame/AudioFiles/GameIntroTheme.mp3").toExternalForm());
MediaPlayer mediaPlayer = new MediaPlayer(gameIntroTheme);
mediaPlayer.setAutoPlay(true);
mediaPlayer.setVolume(0.1);
}
@FXML private void changeNewColor(MouseEvent event)
{
playButton.setStyle("-fx-background-color: #0f69b4;");
}
@FXML private void backToOldColor(MouseEvent event)
{
playButton.setStyle("-fx-background-color: #346699;");
}
}
我的FXML
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.media.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import java.net.URL?>
<StackPane fx:id="MainMenu" xmlns:fx="http://javafx.com/fxml/1" fx:controller="millionairetriviagame.MenulayoutFXMLController">
<stylesheets>
<URL value="@ButtonLayout.css"/>
</stylesheets>
<children>
<ImageView>
<image>
<Image url="@ImageFiles/BlueBackgroundColor.jpg"/>
</image>
</ImageView>
<VBox fx:id="MainMenuLayout" spacing="20" alignment="TOP_CENTER" >
<children>
<ImageView>
<image>
<Image url="@ImageFiles/MillionaireLogo1.png"/>
</image>
</ImageView>
<Button fx:id="playButton" onMouseEntered="#changeNewColor" onMouseExited="#backToOldColor" prefWidth="200" prefHeight="30" text="Play" styleClass="ButtonLayout">
<shape>
<javafx.scene.shape.Rectangle width="200" height="30" arcHeight="30" arcWidth="30" />
</shape>
</Button>
<Button fx:id="optionButton" prefWidth="200" prefHeight="30" text="Option" styleClass="ButtonLayout">
<shape>
<javafx.scene.shape.Rectangle width="200" height="30" arcHeight="30" arcWidth="30" />
</shape>
</Button>
<Button fx:id="aboutTheGameButton" prefWidth="200" prefHeight="30" text="How to Play" styleClass="ButtonLayout">
<shape>
<javafx.scene.shape.Rectangle width="200" height="30" arcHeight="30" arcWidth="30" />
</shape>
</Button>
<Button fx:id="exitButton" prefWidth="200" prefHeight="30" text="Exit" styleClass="ButtonLayout">
<shape>
<javafx.scene.shape.Rectangle width="200" height="30" arcHeight="30" arcWidth="30" />
</shape>
</Button>
</children>
</VBox>
</children>
</StackPane>
答案 0 :(得分:2)
用CSS做这件事。您根本不需要任何事件处理:
.button {
-fx-background-color: #346699;
}
.button:hover {
-fx-background-color: #0f69b4;
}