Sorry for the delay, here's an example of how to use a class save your objects and not having to repeat code over and over again. There are so many improvements that you could make, and of course many ways to do this, but to get started to see how these things work for sure you're worth, and it saves you trouble!
First, class with the main, to prove it this put it in a different file to the next, no matter what it's called, but very important you have these imports:import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Code:public static void main(String[] args) {
// Primero creo una ventana y le pongo título, medidas, layout a null y DO_NOTHING_ON_CLOSE
JFrame frame = new JFrame("Prueba");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setSize(600, 800);
// También la centro, ya puestos
frame.setLocationRelativeTo(null);
/*
* El método que creé en nuestra "fábrica" de botones de salir requiere que se le pasen
* las medidas y la posición del botón como un Rectangle, que es una de las opciones que
* nos da Swing a la hora de setearle esas medidas/posición, así que empiezo creando uno
*/
Rectangle position1 = new Rectangle(50, 50, 100, 25);
/*
* Y luego añado el botón llamando directamente a la clase StaticWindowComponents
* y el método correspondiente, pasándole el texto y el rectángulo
*/
frame.getContentPane().add(StaticWindowComponents.getExitButton("Salir", position1));
// Otra opción es crear el Rectangle directamente en la llamada al método, puesto que no lo volveré a usar
frame.getContentPane().add(StaticWindowComponents.getExitButton("Salir también",
new Rectangle(200, 225, 250, 100)));
// Incluso podrías guardar el botón que devuelve el método y luego añadirlo como siempre!
JButton button3 = StaticWindowComponents.getExitButton("Tercer botón",
new Rectangle(25, 400, 125, 250));
frame.getContentPane().add(button3);
/*
* Eso está muy bien si solo vamos a poner botones que siempre hagan lo mismo
* pero con diferentes textos... Y si quiero que los botones hagan cosas diferentes?
* Bueno, para eso podemos probar a crear un ActionListener aquí... y pasárselo
* al segundo método de la clase StaticWindowComponents!
* También podrías crear el new ActionListener directamente al llamar al método,
* simplemente lo hago por separado para hacerlo más fácil de leer/seguir.
*/
ActionListener salutationsListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Salutations, human!");
}
};
frame.getContentPane().add(StaticWindowComponents.getCustomButton("Saludar",
new Rectangle(200, 25, 100, 100),
salutationsListener));
/*
* Una manera más corta de escribir el actionListener es usar una lambda!
* Con ellas se hace realmente fácil hacer botones customizados:
*/
frame.getContentPane().add(StaticWindowComponents.getCustomButton("Byeee",
new Rectangle(300, 125, 100, 100),
(e) -> JOptionPane.showMessageDialog(frame, "Adiós! :D")));
/*
* Gracias a la lambda, el "ActionListener" se queda en esa breve línea! Es MUY útil cuando quieres
* hacer un botón que necesitas que llame a un determinado método de alguna clase :)
*/
// Por último muestro el frame con... bueno, un revoltijo de botones :P
frame.setVisible(true);
}
Now, in the same package add class StaticWindowComponents, the file name should be the same as that of the class import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
-test-
@author Benito-B - 10/02/2021
*/
public class StaticWindowComponents {
/**
Este método siempre devolverá un botón que permitirá salir de la aplicación
@param text Texto del botón
@param rectangle Posición y tamaño del botón
@return JButton con actionListener que termina la aplicación
*/
public static JButton getExitButton(String text, Rectangle rectangle){
JButton button = new JButton(text);
button.setBounds(rectangle);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return button;
}
/**
Este método es similar al anterior, pero ... nos permite pasarle el listener! Es decir,
la acción de este botón dependerá de lo que le pasemos al momento de llamar al método!
@param text
@param rectangle
@param listener
@return
*/
public static JButton getCustomButton(String text, Rectangle rectangle, ActionListener listener){
JButton button = new JButton(text);
button.setBounds(rectangle);
// Simplemente le añado el lístener que recibe el método!
button.addActionListener(listener);
return button;
}
}
As you will see, having methods that return objects prefabricated is very useful since it allows us to add multiple objects equal or similar very quickly and without repeating!In addition, the use of lambdas and the passage of listener as a parameter to such methods opens a huge range of possibilities when creating multiple instances of similar elements with functionalities MUY different.I hope this will help you create your own methods and keep learning. In the example I've only used JButtons, but this technique will work with any other object! The sky is the limitSo cheer, practice and learn! For any doubt, here we are.By the way, with that code you get the following monster... sorry, window: