Java FXML
Java FXML
Java FX (FXML)
ENLACES RECOMANDADOS: Instalacion: https://www.youtube.com/watch?v=ej5YrLYtLF0 charts examples in java:
- https://www.youtube.com/watch?v=c1rwM1LYjIM
- https://www.youtube.com/watch?v=yySQWaxZqx4 Dashboard FX https://github.com/gleidsonmt/DashboardFx#using-in-scenebuilder
Videos recomendados para practicar java :
MOSTRAR DATOS EN UN CHART https://www.youtube.com/watch?v=BrxzmZRaSXE
COMO MOSTRAR DATA DE UNA BASE DE DATOS https://www.youtube.com/watch?v=V9nDH2iBJSM
Desde una perspectiva de Model View Controller (MVC):
El archivo FXML,
que contiene la descripción de la interfaz de usuario, es la vista.El controlado
r es una clase Java, que implementa opcionalmente la clase Initializable, que se declara como el controlador para el archivo FXML.El modelo
consta de objetos de dominio, definidos en el lado de Java, que se pueden conectar a la vista a través del controlador.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package fxmlexample1;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FXMLExample1 extends Application {
@Override
public void start(Stage stage) throws Exception {
// Carga un archivo FXML (una representación de la interfaz de usuario) desde el recurso "FXMLDocument.fxml"
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
// Crea una nueva escena de JavaFX y la establece con el contenido cargado desde el archivo FXML
Scene scene = new Scene(root);
// Establece la escena en el escenario (ventana principal) y muestra la ventana
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// Método principal para iniciar la aplicación JavaFX
launch(args);
}
}
ESTRUCTURA GENERAL DE ARCHIVOS
1
2
3
4
5
6
7
FXMLExample1
->Source Packages
|_>fxmlexample1
|_>FXMLDocument.fxml
|_>FXMLDocumentController.java
|_>FXMLExample1.java
-> Libraries
ARCHIVO PRINCIPAL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class LibraryManagement extends Application {
//variables necesarias para el drag and drop
private double x = 0;
private double y = 0;
@Override
public void start(Stage stage) throws Exception {
//Cargador del FXML inicial a abrir
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
//////METODOS NECESARIOS PARA DRAG AND DROP //////
root.setOnMousePressed((MouseEvent event) ->{
x = event.getSceneX();
y = event.getSceneY();
});
root.setOnMouseDragged((MouseEvent event) ->{
stage.setX(event.getScreenX() - x);
stage.setY(event.getScreenY() - y);
});
////// fin de METODOS NECESARIOS PARA DRAG AND DROP //////
//quitar barra de windows
stage.initStyle(StageStyle.TRANSPARENT);
// crear el stage y asignarle una scena y mostrarlo con .show()
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
CSS
HEX COLOR REMINDER:
#RRGGBB
HEX = Conformado por 6 valores y en pares de dos forman la intensidad y color con R G B
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//To select the id from the panel: start with a point and then the number
//example : .textfield{ Here goes the statements}
//To change the properties from hover function:
//example : .textfield:hover{Here goes the statements}
//There is another one: .textfield:focused{ Here goes the statements}
-fx-background-color: lineargradient(to bottom right, #HEXCOLOR, #HEX COLOR2);
-fx-background-color: #HEX COLOR; // example: transparent
-fx-background-radius: (NUMBER)px;
-fx-cursor: (TYPEofHAndCursor); //example : hand
-fx-font-weight: bold;
-fx-font-size:(NUmber)px;
-fx-text-fill:#HEX COLOR;
-fx-text-inner-color: #HEX COLOR; //this one is to change the font color
-fx-font-family:"Nombre de la fuente" //ejemplo: Microsoft Sans Serif
-fx-border-color: #HEX COLOR;
-fx-border-width: 0px 0px 0px 0px; //patron: Up right down left
-fx-padding: 0px 0px 0px 0px; //patron: Up right down left
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.5), 5,0,0,0);
//////////////NOTAS DE USO //////////////
1. fx-background-color suele ir on fx-background-radius para que surta efecto
2. al igual que el anterior: -fx-border-width y -fx-border-color van de la mano
ICONS
- SIGN_OUT
- CHECK
- QUESTION
DATABASE CLASS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public static Connection connectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
//si no configuraste usuario ni pass: root y contrasena vacia ""
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost/NOMBRE_BASE_DE_DATOS", "USUARIO", "CONTRASENA");
return connect;
}catch(Exception e){e.printStackTrace();}
return null;
}
}
DASHBOARD CONTROLLER
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package librarymanagement;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
//DATABASE TOOLS
private Connection connect;
private PreparedStatement prepare;
private Statement statement;
private ResultSet result;
LOGIN CONTROLLER
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//DATABASE TOOLS
private Connection connect;
private PreparedStatement prepare;
private Statement statement;
private ResultSet result;
public void login(){
String sql = "SELECT * FROM student WHERE studentNumber = ? and password = ?";
connect = Database.connectDB();
try{
prepare = connect.prepareStatement(sql);
prepare.setString(1, studentNumber.getText());
prepare.setString(2, password.getText());
result = prepare.executeQuery();
Alert alert;
if(studentNumber.getText().isEmpty() || password.getText().isEmpty()){
alert = new Alert(AlertType.ERROR);
alert.setTitle("Admin Message");
alert.setHeaderText(null);
alert.setContentText("Please fill all blank fields.");
alert.showAndWait();
}else{
if(result.next()){
getData.studentNumber = studentNumber.getText();
// DON'T FORGET THIS!!!!
getData.path = result.getString("image");
alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Admin Message");
alert.setHeaderText(null);
alert.setContentText("Successfully Login!");
alert.showAndWait();
// TO HIDE THE LOGIN FORM
login_Btn.getScene().getWindow().hide();
// FOR DASHBOARD
Parent root = FXMLLoader.load(getClass().getResource("dashboard.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
root.setOnMousePressed((MouseEvent event) ->{
x = event.getSceneX();
y = event.getSceneY();
});
root.setOnMouseDragged((MouseEvent event) ->{
stage.setX(event.getScreenX() - x);
stage.setY(event.getScreenY() - y);
});
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
}else{
alert = new Alert(AlertType.ERROR);
alert.setTitle("Admin Message");
alert.setHeaderText(null);
alert.setContentText("Wrong Username or Password.");
alert.showAndWait();
}
}
}catch(Exception e){e.printStackTrace();}
}
// ONLY NUMBERS ALLOWED
public void numbersOnly(KeyEvent event){
if(event.getCharacter().matches("[^\\e\t\r\\d+$]")){
event.consume();
studentNumber.setStyle("-fx-border-color:#e04040");
}else{
studentNumber.setStyle("-fx-border-color:#fff");
}
}
// LET'S PROCEED TO DASHBOARD :)
@FXML
public void minimize(){
Stage stage = (Stage)minimize.getScene().getWindow();
stage.setIconified(true);
}
@FXML
public void exit(){
System.exit(0);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
LOGOUT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@FXML
public void logout(ActionEvent event) {
try {
if (event.getSource() == logout_btn) {
// TO SWAP FROM DASHBOARD TO LOGIN FORM
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
root.setOnMousePressed((MouseEvent e) -> {
x = e.getSceneX();
y = e.getSceneY();
});
root.setOnMouseDragged((MouseEvent e) -> {
stage.setX(e.getScreenX() - x);
stage.setY(e.getScreenY() - y);
});
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
logout_btn.getScene().getWindow().hide();
}
} catch (Exception e) {
e.printStackTrace();
}
}
SALIR Y MINIMIZAR
1
2
3
4
5
6
7
8
9
10
@FXML
public void minimize(){
Stage stage = (Stage)minimize.getScene().getWindow();
stage.setIconified(true);
}
@FXML
public void exit(){
System.exit(0);
}
COMBO BOXES
- Utilizan las siguientes clases e interacciones
- List = define el tipo y nombre de la lista
- ArrayList = inicializa el valor de List
- ObservableList = crea la variable
- FXCollections : Inicializa la vairiable ObservableList
- ComboBox
<?>
: la variable proveniente del FXML- .setItems(list) : metodo para las variables combobox de fxml que utiliza como parametro el objeto ObservableList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void gender() {
List<String> combo = new ArrayList<>();
for (String data : comboBox) {
combo.add(data);
}
**ObservableList** list = **FXCollections**.**observableList**(**combo**);
take_Gender.setItems(list);
}
IMAGENES
- utilizan las siguientes clases e interacciones
- FileChooser
- .setTitle(”cadena”);
- .getExtensionFilters().add(new ExtensionFilter(“Image file”, “png”, “jpg”)); para colocar filtros de seleccion
- Stage
- File
- changeProfile();
- FileChooser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void insertImage() {
FileChooser open = new FileChooser();
open.setTitle("Image File");
open.getExtensionFilters().add(new ExtensionFilter("Image file", "*png", "*jpg"));
Stage stage = (Stage) nav_form.getScene().getWindow();
File file = open.showOpenDialog(stage);
if (file != null) {
image = new Image(file.toURI().toString(), 112, 84, false, true);
circle_image.setFill(new ImagePattern(image));
smallCircle_image.setFill(new ImagePattern(image));
getData.path = file.getAbsolutePath();
changeProfile();
}
}
LIMPIAR DATA
- utilizan las siguientes clases e interacciones
Nombre_ID.setText(””);
- En caso de un imageView
Nombre_ID_Imagen.setImage(null);
Ejemplo:
1
2
3
4
5
6
7
8
9
10
public void clearTakeData() {
take_BookTitle.setText("");
take_titleLabel.setText("");
take_authorLabel.setText("");
take_genreLabel.setText("");
take_dateLabel.setText("");
take_imageView.setImage(null);
}
Mostrar Fecha
- utilizan las siguientes clases e interacciones
- SimpleDateFormat
- .format(new java.util.Date());
- String : almacena el metodo .format
ID_LABEL_PARA_MOSTRAR_FECHA.setText(Cadena .format);
- SimpleDateFormat
1
2
3
4
5
6
7
8
9
public void displayDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new java.util.Date());
take_IssuedDate.setText(date);
}
ABRIR OTRO ANCHOR PANE UTILIZANDO UN BOTON
Otra cosa interesante puede ser actualizar un texto con .setText() cada vez que cambies de ventana
- utilizan las siguientes clases e interacciones
- metodo void, parametro ActionEvent
- objeto ActionEvent
- .getSource() : se utiliza con
==
para compararlo con el ID del boton
- .getSource() : se utiliza con
- AnchorPane methods
- .setVisible()
- True = para volver visible el nuevo anchor pane
- False = para esconder el pane donde se hizo click
- .setVisible()
ejemplo: ademas le puedes agregar estilos directamente a cada componente(opcional)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void abTakeButton(ActionEvent event) {
if (event.getSource() == take_btn) {
issue_form.setVisible(true);
availableBooks_form.setVisible(false);
savedBook_form.setVisible(false);
returnBook_form.setVisible(false);
issueBooks_btn.setStyle("-fx-background-color:linear-gradient(to bottom right, #46589a, #4278a7);");
availableBooks_btn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
returnBooks_btn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
savedBooks_btn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
halfNav_takeBtn.setStyle("-fx-background-color:linear-gradient(to bottom right, #46589a, #4278a7);");
halfNav_availableBtn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
halfNav_returnBtn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
halfNav_saveBtn.setStyle("-fx-background-color:linear-gradient(to bottom right, #344275, #3a6389);");
currentForm_label.setText("Issue Books");
}
}
Metodo public void initialize(URL location, ResourceBundle resources)
por defecto viene
1
2
3
4
5
6
@Override
public void initialize(URL url, ResourceBundle rb) {
// Este método se llama al inicializar el controlador de la interfaz de usuario
// Puede utilizarse para realizar configuraciones iniciales o cargar datos
// En este caso, se encuentra como "TODO", lo que sugiere que debe agregarse funcionalidad adicional aquí.
}
pero se usa para inicializar metodos al momento de abrir
ejemplo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Override
public void initialize(URL location, ResourceBundle resources) {
designInserImage();
showProfile();
// TO SHOW THE AVAILABLE BOOKS
showAvailableBooks();
studentNumber();
studentNumberLabel();
displayDate();
gender();
showSavedBooks();
// RETURN FORM
try {
showBookReturn();
} catch (Exception e) {
e.printStackTrace();
}
}
This post is licensed under CC BY 4.0 by the author.