最近用javaFX写了一个音乐播放器,用swing感觉自定义界面太麻烦了所以用了 javaFX 因为时间关系我就只学了自定义界面和音乐的触发事件,小白一枚 写的代码可能会不规范。请大家谅解
然后用到了数据库的方式存放歌曲的地址,因为我这个萌新还没有学用网络爬取歌曲,所以歌曲存放在本地
哇,我一直以为//# java这个才是 标题搞了好久一直提示我请勿使用默认标题搞了好久才知道
这个才是标题(捂脸)
public class Main extends Application{
public static void main(String[] args) {
launch(args);
}
Music_Dao music_Dao =new Music_Dao();//这个是dao层下的包等会调用数据库时用到的
Media media;
MediaPlayer mediaPlayer;
HashMap<Integer, String> hashMap_song;
help help_method;
ObservableList<String> observableList;//一个存放歌曲地址的一个集合
int flage=0;//歌曲列表的索引
//用来拖动
double x=0;//定义一个x用来存放鼠标在窗口的当前x轴位置
double y=0;//定义一个y用来存放鼠标在窗口的当前y轴位置
boolean max_is=true;//用来判断当前窗口是否是最大化状态 true:是 false:否
boolean is_play=true;//判断一个歌曲是否真正播放
boolean is_mouse=false;//用来判断鼠标是否在进度条上
Label setbackgroud;//用来存放播放时用的模糊图片
Slider slider;
//以下是歌曲的信息 名字、演唱者、歌曲类型、歌曲图片
Label song_name;
Label song_songer;
Label song_type;
Label song_image;
@Override
public void start(Stage primaryStage) throws Exception {
//下面是给关闭 最大化 最小化 按钮 自定义样式
HBox hBox_title=new HBox();
//给关闭按钮设置图片
ImageView imageView =new ImageView("image/关闭.png");
imageView.setFitWidth(23);
imageView.setFitHeight(13);
Button close_button=new Button("",imageView);
close_button.setStyle("-fx-background-color:#FF8C0000;");
ImageView imageView2 =new ImageView("image/最大化.png");
imageView2.setFitWidth(23);
imageView2.setFitHeight(13);
Button Max_button=new Button("",imageView2);
Max_button.setStyle("-fx-background-color:#FF8C0000;");
ImageView imageView3 =new ImageView("image/最小化.png");
imageView3.setFitWidth(23);
imageView3.setFitHeight(13);
Button Min_button=new Button("",imageView3);
Min_button.setStyle("-fx-background-color:#FF8C0000;");
hBox_title.getChildren().addAll(Min_button,Max_button,close_button);
//以下是登录注册按钮
HBox hBox_LoginandRegister=new HBox(2);
Button Login_Button=new Button("登录");
Login_Button.setPrefWidth(60);//设置宽
Login_Button.setPrefHeight(20);//设置高
Login_Button.setTextFill(Color.web("#d479f2"));//设置文本颜色
Login_Button.setFont(Font.font(18));
Login_Button.setStyle(
"-fx-background-color:#26075100;" +// 设置按钮背景颜色
"-fx-border-insets:5;" //边框距离按钮的距离
);
Label division =new Label("|");
division.setTextFill(Color.web("#e08afc"));
Button Register_Button =new Button("注册");
Register_Button.setPrefWidth(60);
Register_Button.setPrefHeight(20);
Register_Button.setFont(Font.font(18));
Register_Button.setTextFill(Color.web("#d479f2"));
Register_Button.setStyle(
"-fx-background-color:#26075100;" +// 设置按钮背景颜色
"-fx-border-insets:5;" //边框距离按钮的距离
);
hBox_LoginandRegister.getChildren().addAll(Login_Button,division,Register_Button);
hBox_LoginandRegister.setAlignment(Pos.CENTER);
//以下是播放和暂停按钮以及切歌按钮的自定义样式
HBox hBox_play =new HBox();
ImageView imageView4 =new ImageView("image/播放.png");
imageView4.setFitWidth(76);
imageView4.setFitHeight(55);
Button play_button=new Button("",imageView4);
play_button.setStyle("-fx-background-color:#FF8C0000;");
ImageView imageView5 =new ImageView("image/下一首.png");
imageView5.setFitWidth(76);
imageView5.setFitHeight(55);
Button next_button=new Button("",imageView5);
next_button.setStyle("-fx-background-color:#FF8C0000;");
ImageView imageView6 =new ImageView("image/上一首.png");
imageView6.setFitWidth(76);
imageView6.setFitHeight(55);
Button last_button =new Button("",imageView6);
last_button.setStyle("-fx-background-color:#FF8C0000;");
hBox_play.getChildren().addAll(last_button,play_button,next_button);
//以下是界面中左边的一个列表
VBox vBox_listView=new VBox();
observableList=FXCollections.observableArrayList();
getsongname();查询数据库的歌曲列表 并放进list 里面
ListView<String> listView=new ListView<>(observableList);
listView.setPrefWidth(200);
listView.setPrefHeight(410);
//这个也不知道为什么没有用
// listView.setStyle("-fx-background-insets:0;"
// + "-fx-padding:0;"
// + "-fx-background-color:#eb9de9;"
// + "-fx-background-fills:#eb9de9;"
// + "-fx-border-radius:10;"
// );
vBox_listView.getChildren().add(listView);
hashMap_song =new HashMap<>();
get_song_map();
URL frist_music=this.getClass().getClassLoader().getResource(hashMap_song.get(0));
media =new Media(frist_music.toExternalForm());
mediaPlayer =new MediaPlayer(media);
//进度条初始化
slider =new Slider();
slider.setPrefWidth(825);
//模糊背景标签初始化 因为我在
setbackgroud=new Label();
//歌曲信息标签初始化
VBox vbox_TitleandImage=new VBox(10);
song_image =new Label();
VBox vBox_songmessage=new VBox(10);
song_name=new Label();
song_songer=new Label();
song_type=new Label();
vbox_TitleandImage.getChildren().addAll(song_name,song_image);
vbox_TitleandImage.setAlignment(Pos.CENTER_LEFT);
vBox_songmessage.getChildren().addAll(song_songer,song_type);
AnchorPane aPane =new AnchorPane();
//把小容器都装到大容器里面
aPane.getChildren().addAll(hBox_title,hBox_play,vBox_listView,slider,setbackgroud,vbox_TitleandImage,vBox_songmessage
,hBox_LoginandRegister);
aPane.setBottomAnchor(vBox_listView, 55.0);
aPane.setRightAnchor(hBox_title, 10.0);
aPane.setBottomAnchor(hBox_play, 30.0);
aPane.setRightAnchor(hBox_play, 310.0);
aPane.setBottomAnchor(slider, 90.0);
aPane.setRightAnchor(slider,0.0);
aPane.setLeftAnchor(setbackgroud, 201.0);
aPane.setBottomAnchor(setbackgroud, 107.0);
aPane.setBottomAnchor(vbox_TitleandImage, 251.0);
aPane.setLeftAnchor(vbox_TitleandImage,497.0);
aPane.setLeftAnchor(vBox_songmessage, 499.0);
aPane.setBottomAnchor(vBox_songmessage, 190.0);
aPane.setTopAnchor(hBox_LoginandRegister, 30.0);
aPane.setLeftAnchor(hBox_LoginandRegister, 20.0);
//设置根节点圆角显示
Background bg =new Background(new BackgroundFill(Paint.valueOf("#00000000"), new CornerRadii(20) , new Insets(0)));
aPane.setBackground(bg);
aPane.setStyle("-fx-background-radius: 20px;"+ "-fx-background-image:url(image/背景.png);");
Scene scene =new Scene(aPane);
//把场景图的颜色设置为透明不然会露出来一点角
scene.setFill(Paint.valueOf("#00000000"));
primaryStage.setScene(scene);
primaryStage.setWidth(1025);
primaryStage.setHeight(603);
primaryStage.setTitle("Mark1");
primaryStage.setResizable(false);
// //设置窗口的样式为null,所以你要自己定义一个关闭、最小化、最大化的按钮
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.getIcons().add(new Image("/image/logo.jpg"));
primaryStage.setTitle("捡垃圾播放器");
primaryStage.show();
//以下都是监听方法
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
x=event.getScreenX()-primaryStage.getX();
y=event.getScreenY()-primaryStage.getY();
}
});
scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
primaryStage.setX(event.getScreenX()-x);
primaryStage.setY(event.getScreenY()-y);
}
});
//下面是标题栏按钮的监听方法
close_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
primaryStage.close();
}
});
//设置当鼠标移动在按钮上面的监听
close_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(true) {
// ImageView imageView =new ImageView("image/关闭副.png");
imageView.setFitWidth(23);
imageView.setFitHeight(13);
//改变按钮里的图片我也不知道它干嘛弄一个Graphic这个来设置这些,我裂开了
close_button.setGraphic(new ImageView("image/关闭副.png"));
// close_button=new Button("",imageView);
close_button.setStyle("-fx-background-color:#FF8C0000;");
// hBox_title.getChildren().add(close_button);
}
}
});
//设置当鼠标离开按钮上面的监听
close_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
close_button.setGraphic(new ImageView("image/关闭.png"));
}
});
Max_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(max_is);
if(max_is) {
primaryStage.setMaximized(true);
max_is=false;
}else {
max_is=true;
primaryStage.setMaximized(false);
}
}
});
Max_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(true) {
Max_button.setGraphic(new ImageView("image/最大化副.png"));
Max_button.setStyle("-fx-background-color:#FF8C0000;");
}
}
});
Max_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Max_button.setGraphic(new ImageView("image/最大化.png"));
}
});
Min_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
primaryStage.setIconified(true);
}
});
Min_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(true) {
Min_button.setGraphic(new ImageView("image/最小化副.png"));
Min_button.setStyle("-fx-background-color:#FF8C0000;");
}
}
});
Min_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Min_button.setGraphic(new ImageView("image/最小化.png"));
}
});
//以下是登录和注册按钮事件监听
Login_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Stage LoginStage=new Stage();
Login login =new Login();
try {
login.start(LoginStage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Login_Button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Login_Button.setTextFill(Color.web("#eb9de9"));
}
});
Login_Button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Login_Button.setTextFill(Color.web("#d479f2"));
}
});
Register_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
}
});
Register_Button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Register_Button.setTextFill(Color.web("#eb9de9"));
}
});
Register_Button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Register_Button.setTextFill(Color.web("#d479f2"));
}
});
//以下是播放和暂停按钮以及切歌按钮的事件监听
play_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if(is_play==true) {
mediaPlayer.pause();
is_play=false;
setbackgroud.setGraphic(null);
}else {
is_play=true;
play_button.setGraphic(new ImageView("image/暂停副.png"));
mediaPlayer.play();
SliderListener();
SetbackgroudAndsongImage();
}
}
});
play_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(is_play==true) {
play_button.setGraphic(new ImageView("image/播放副.png"));
}else {
play_button.setGraphic(new ImageView("image/暂停副.png"));
}
// play_button.setGraphic(new ImageView("image/播放副.png"));
// play_button.setStyle("-fx-background-color:#FF8C0000;");
}
});
play_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(is_play==true) {
play_button.setGraphic(new ImageView("image/播放.png"));
}else {
play_button.setGraphic(new ImageView("image/暂停.png"));
}
}
});
play_button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// play_button.setGraphic(new ImageView("image/暂停副.png"));
}
});
last_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
mediaPlayer.dispose();
flage=flage-1;
if(flage==-1) {
flage=hashMap_song.size()-1;
}
URL flage_music=this.getClass().getClassLoader().getResource(hashMap_song.get(flage));
media =new Media(flage_music.toExternalForm());
mediaPlayer =new MediaPlayer(media);
mediaPlayer.play();
SliderListener();
}
});
last_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(true) {
last_button.setGraphic(new ImageView("image/上一首副.png"));
last_button.setStyle("-fx-background-color:#FF8C0000;");
}
}
});
last_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
last_button.setGraphic(new ImageView("image/上一首.png"));
}
});
next_button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
mediaPlayer.dispose();
flage=flage+1;
System.out.println("nextflag "+flage);
if(flage==hashMap_song.size()) {
flage=0;
}
URL flage_music=this.getClass().getClassLoader().getResource(hashMap_song.get(flage));
media =new Media(flage_music.toExternalForm());
mediaPlayer =new MediaPlayer(media);
mediaPlayer.play();
SliderListener();
}
});
next_button.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(true) {
next_button.setGraphic(new ImageView("image/下一首副.png"));
next_button.setStyle("-fx-background-color:#FF8C0000;");
}
}
});
next_button.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
next_button.setGraphic(new ImageView("image/下一首.png"));
}
});
//下面是自定义列表的初始化
listView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// TODO Auto-generated method stub
mediaPlayer.dispose();
flage=listView.getSelectionModel().getSelectedIndex();
System.out.println(hashMap_song.get(flage));
URL flage_music=this.getClass().getClassLoader().getResource(hashMap_song.get(flage));
media =new Media(flage_music.toExternalForm());
mediaPlayer =new MediaPlayer(media);
mediaPlayer.play();
SliderListener();
SetbackgroudAndsongImage();
System.out.println(flage);
}
});
listView.setCellFactory(TextFieldListCell.forListView(new StringConverter<String>() {
public String toString(String object) {
// TODO Auto-generated method stub
String string =object;
return string;
}
@Override
public String fromString(String string) {
// TODO Auto-generated method stub
return null;
}
}));
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
// TODO Auto-generated method stub
ListCell<String> listCell =new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
// TODO Auto-generated method stub
super.updateItem(item, empty);
if(empty== false) {
HBox hBox =new HBox();
Label label =new Label(item.toString());
hBox.getChildren().add(label);
hBox.setStyle("-fx-background-color:#eb9de9");
this.setGraphic(hBox);
}
}
};
return listCell;
}
});
//以下是进度条监听方法
slider.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
// TODO Auto-generated method stub
is_mouse=false;
mediaPlayer.seek(Duration.seconds(slider.getValue()));
SliderListener();
}
});
slider.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
// TODO Auto-generated method stu
is_mouse=true;
}
});
}
public void getsongname() throws SQLException {
//使用数据库添加数据
List<Music_Bean> list_music=music_Dao.select();
for(Music_Bean music:list_music) {
observableList.add(music.getName());
}
}
//查询数据库的歌曲列表 并放进list 里面
public void get_song_map() throws SQLException {
List<Music_Bean> list_music=music_Dao.select();
for(Music_Bean music:list_music) {
System.out.println(music.getId()-1+" "+music.getUrl());
hashMap_song.put(music.getId()-1, music.getUrl());
}
System.out.println(hashMap_song);
}
//用来加载歌曲的信息,歌曲的image\name\type\time
public void SliderListener() {
mediaPlayer.setOnPlaying(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
slider.setMin(0.0);
slider.setMax(mediaPlayer.getTotalDuration().toSeconds());
mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
@Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue,
Duration newValue) {
// TODO Auto-generated method stub
if(is_mouse==false)
slider.setValue(newValue.toSeconds());
}
});
ObservableMap<String, Object> map =media.getMetadata();
Image songimage=(Image)map.get("image");
ImageView songimageview=new ImageView(songimage);
songimageview.setFitWidth(347/2);
songimageview.setFitHeight(350/2);
song_image.setGraphic(songimageview);
song_name.setText(map.get("title").toString());
song_name.setFont(new Font("Microsoft Yahei",25));
song_name.setStyle("-fx-font-weight: bold;");
song_name.setTextFill(Paint.valueOf("#962aec"));
song_songer.setText("演唱者:"+map.get("artist").toString());
song_songer.setFont(new Font("STHeiti", 15));
song_songer.setTextFill(Paint.valueOf("#dd8fe5"));
song_type.setText("歌曲类型:"+map.get("genre").toString());
song_type.setFont(new Font("STHeiti", 15));
song_type.setTextFill(Paint.valueOf("#dd8fe5"));
}
});
}
public void SetbackgroudAndsongImage() {
Image setbackgound=new Image("image/背景副.png");
setbackgroud.setGraphic(new ImageView(setbackgound));
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Dbhelper {
private static final String DRIVERNAME="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://localhost:3306/music_library";
private static final String USERNAME="root";
private static final String PASSWORD="123456";
static {
try {
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getconnetion() throws SQLException {
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
public static void close(ResultSet result,PreparedStatement ps,Connection conn) throws SQLException {
if(result!=null)
result.close();
if(ps!=null)
ps.close();
if(conn!=null)
conn.close();
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.Music_Bean;
import utils.Dbhelper;
public class Music_Dao {
//查询
public List<Music_Bean> select() throws SQLException{
Connection conn=Dbhelper.getconnetion();
String sql="SELECT * FROM music";
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet result=ps.executeQuery();
List<Music_Bean> list=new ArrayList<Music_Bean>();
while(result.next()) {
Music_Bean music=new Music_Bean();
music.setId(result.getInt(1));
music.setName(result.getString(2));
music.setUrl(result.getString(3));
list.add(music);
}
return list;
}
}
public class Music_Bean {
private int id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String url;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
然后这是我自己建立的包
存放歌曲的包
以上就是这个项目的全部代码了
做的不好的地方请各位大神指出,后期我还会对这个播放器添加一下功能