0% encontró este documento útil (0 votos)
504 vistas20 páginas

Tarea Java Window Builder

Este documento presenta dos ejercicios de Java sobre diseño de interfaces gráficas. El primer ejercicio pide crear un "imitador" donde los cambios en un lado de la interfaz se reflejen en el otro lado de manera unidireccional. El segundo ejercicio pide crear un generador de números aleatorios entre dos números seleccionados con JSpinner y mostrar el resultado en un JTextField al presionar un botón. El código Java proporcionado implementa la solución al primer ejercicio.

Cargado por

Junior Montero
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
504 vistas20 páginas

Tarea Java Window Builder

Este documento presenta dos ejercicios de Java sobre diseño de interfaces gráficas. El primer ejercicio pide crear un "imitador" donde los cambios en un lado de la interfaz se reflejen en el otro lado de manera unidireccional. El segundo ejercicio pide crear un generador de números aleatorios entre dos números seleccionados con JSpinner y mostrar el resultado en un JTextField al presionar un botón. El código Java proporcionado implementa la solución al primer ejercicio.

Cargado por

Junior Montero
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

JAVA -PROFESOR: ING.

FREIDY NUÑEZ

Presentación.

Nombre: Maximo Junior

Apellido: Montero Mercedes

Matricula: 2021-0284

Grupo: 11

TAREA JAVA TEMA DISEÑO.

Realizar los ejercicios usando los mismos diseños mostrados.

1- Vamos a crear un imitador, como si fuera un espejo. Tendremos dos pares de


conjunto de elementos separados (puedes usar un separador) y cuando nosotros
pinchamos en un elemento o escribimos en un campo, se debe cambiar el otro
lado.

Por ejemplo, si yo tengo un campo de texto y escribo en él, el campo de texto que
es su reflejo también recibirá ese texto.

Puedes usar los elementos que quieras, ejemplo: JTextField, JRadioButton,


JCheckBox, JTextArea, JSpinner, etc.

Solo puedes modificar de un lado, el otro conjunto no lo podéis modificar, es decir,


que no es bidireccional.
JAVA -PROFESOR: ING. FREIDY NUÑEZ

package Pruebas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import java.awt.Font; import
java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import
javax.swing.DefaultComboBoxMode
l; import javax.swing.JList;
import
javax.swing.AbstractListModel;
import javax.swing.JSpinner;
import
javax.swing.SpinnerNumberModel;
import
javax.swing.SwingConstants;
import
javax.swing.event.ChangeEvent;
import
javax.swing.event.ChangeListene
JAVA -PROFESOR: ING. FREIDY NUÑEZ

r; import
java.awt.event.ItemEvent; import
java.awt.event.ActionListener;
import
java.awt.event.ActionEvent;
public class Imitador implements
ChangeListener {
private JFrame frame;
JRadioButton RadioButton, RadioButton1, RadioButton2, RadioButton3,
RadioButton4,RadioButton5 ; private
JPanel panel_1;
JCheckBox CheckBox, CheckBox1, CheckBox2, CheckBox3, CheckBox4,
CheckBox5; JComboBox comboBox;
private JTextField textField;
private JSpinner spinner;
private JLabel lblNewLabel_1;
private JPanel panel_2; private
JPanel panel_3; private
JTextField textField_1; private
JComboBox comboBox_1; private
JSpinner spinner_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { public
void run() {
try {
Imitador window = new Imitador();
window.frame.setVisible(true); }
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/ public
Imitador() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() { frame = new JFrame();
frame.setTitle("Imitador"); frame.setSize(550, 450);
//frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
; frame.getContentPane().setLayout(null);
ButtonGroup grupo1= new ButtonGroup();
JAVA -PROFESOR: ING. FREIDY NUÑEZ
ButtonGroup grupo2= new ButtonGroup();
JPanel panel = new JPanel();
panel.setBounds(20, 51, 135, 114);
frame.getContentPane().add(panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
//original
JLabel lblNewLabel = new JLabel("Original");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblNewLabel.setBounds(10, 10, 106, 27);
frame.getContentPane().add(lblNewLabel);
//opcion 1,2,3
RadioButton = new JRadioButton("Opcion 1");
RadioButton.setFont(new Font("Tahoma", Font.PLAIN, 22));
RadioButton.addChangeListener(this); panel.add(RadioButton);
RadioButton1 = new JRadioButton("Opcion 2");
RadioButton1.setFont(new Font("Tahoma", Font.PLAIN, 22));
RadioButton1.addChangeListener(this); panel.add(RadioButton1);
RadioButton2 = new JRadioButton("Opcion 3");
RadioButton2.setFont(new Font("Tahoma", Font.PLAIN, 22));
RadioButton2.addChangeListener(this);
panel.add(RadioButton2); //grupo de
botones del 1,2,3
grupo1.add(RadioButton);
grupo1.add(RadioButton1);
grupo1.add(RadioButton2); //opcion
4,5,6 panel_1 = new JPanel();
panel_1.setBounds(165, 49, 119, 116);
frame.getContentPane().add(panel_1);
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
CheckBox = new JCheckBox("Opcion 4");
CheckBox.setFont(new Font("Tahoma", Font.PLAIN, 22));
CheckBox.addChangeListener(this); panel_1.add(CheckBox);
CheckBox1 = new JCheckBox("Opcion 5");
CheckBox1.setFont(new Font("Tahoma", Font.PLAIN, 22));
CheckBox1.addChangeListener(this); panel_1.add(CheckBox1);
CheckBox2 = new JCheckBox("Opcion 6");
CheckBox2.setFont(new Font("Tahoma", Font.PLAIN, 22));
CheckBox2.addChangeListener(this);
panel_1.add(CheckBox2); //ingresar texto
textField = new JTextField();
textField.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e) {
textField_1.setText(textField.getText());
} }); textField.setBounds(317, 51,
106, 27);
frame.getContentPane().add(textField);
textField.setColumns(10);
//combobox comboBox = new
JComboBox();
comboBox.addItemListener(new ItemListener() { public
void itemStateChanged(ItemEvent e) {
if(e.getStateChange()== ItemEvent.SELECTED) {
if(comboBox.getSelectedIndex()==0) {
comboBox.setSelectedIndex(0);
JAVA -PROFESOR: ING. FREIDY NUÑEZ

} if(comboBox.getSelectedIndex()==1)
{ comboBox.setSelectedIndex(1);
} if(comboBox.getSelectedIndex()==2)
{ comboBox.setSelectedIndex(2);
}
}
} });
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 18));
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Item 1",
"Item 2", "Item 3"})); comboBox.setBounds(317,
88, 106, 27);
frame.getContentPane().add(comboBox);
//spinner spinner = new JSpinner();
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
spinner_1.setValue(spinner.getValue());
} });
spinner.setFont(new Font("Tahoma", Font.PLAIN, 17));
spinner.setModel(new SpinnerNumberModel(0, 0, 20, 1));
spinner.setBounds(317, 125, 106, 27);
frame.getContentPane().add(spinner);
//reflejo
lblNewLabel_1 = new JLabel("Reflejo");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblNewLabel_1.setBounds(10, 175, 106, 27);
frame.getContentPane().add(lblNewLabel_1);
//opciones reflejos 1,2,3 panel_2 = new
JPanel(); panel_2.setBounds(20, 213, 135,
114); frame.getContentPane().add(panel_2);
RadioButton3 = new JRadioButton("Opcion 1");
RadioButton3.setEnabled(false);
RadioButton3.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_2.add(RadioButton3);
RadioButton4 = new JRadioButton("Opcion 2");
RadioButton4.setEnabled(false);
RadioButton4.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_2.add(RadioButton4);
RadioButton5 = new JRadioButton("Opcion 3");
RadioButton5.setEnabled(false);
RadioButton5.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_2.add(RadioButton5); // reflejo grupo de botones
del 1,2,3 grupo2.add(RadioButton3);
grupo2.add(RadioButton4); grupo2.add(RadioButton5);
//opciones reflejos 4,5,6 panel_3 = new JPanel();
panel_3.setBounds(165, 213, 119, 114);
frame.getContentPane().add(panel_3);
panel_3.setLayout(new BoxLayout(panel_3, BoxLayout.Y_AXIS));
CheckBox3 = new JCheckBox("Opcion 4");
CheckBox3.setEnabled(false);
CheckBox3.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_3.add(CheckBox3);
CheckBox4 = new JCheckBox("Opcion 5");
CheckBox4.setEnabled(false);
JAVA -PROFESOR: ING. FREIDY NUÑEZ
CheckBox4.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_3.add(CheckBox4);
CheckBox5 = new JCheckBox("Opcion 6");
CheckBox5.setEnabled(false);
CheckBox5.setFont(new Font("Tahoma", Font.PLAIN, 22));
panel_3.add(CheckBox5); //texto reflejo textField_1 =
new JTextField(); textField_1.setEnabled(false);
textField_1.setBounds(317, 213, 106, 27);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10); //combobox reflejo
comboBox_1 = new JComboBox();
comboBox_1.setEnabled(false);
comboBox_1.setFont(new Font("Tahoma", Font.PLAIN, 18));
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"Item 1",
"Item 2", "Item 3"}));
comboBox_1.setBounds(317, 250, 106, 27);
frame.getContentPane().add(comboBox_1);
//Spinner reflejo spinner_1
= new JSpinner();
spinner_1.setEnabled(false);
spinner_1.setModel(new SpinnerNumberModel(0, 0, 20, 1));
spinner_1.setFont(new Font("Tahoma", Font.PLAIN, 17));
spinner_1.setBounds(317, 287, 106, 27);
frame.getContentPane().add(spinner_1);
}
@Override
public void stateChanged(ChangeEvent e) {
if(RadioButton.isSelected()) { RadioButton3.setSelected(true);
} if(RadioButton1.isSelected())
{
RadioButton4.setSelected(true);
} if(RadioButton2.isSelected())
{
RadioButton5.setSelected(true);
} //checkbox
if(CheckBox.isSelected()) {
CheckBox3.setSelected(true);
}else {

CheckBox3.setSelected(false);
} if(CheckBox1.isSelected())
{
CheckBox4.setSelected(true);
}else {
CheckBox4.setSelected(false);
} if(CheckBox2.isSelected())
{
CheckBox5.setSelected(true);
}else {
CheckBox5.setSelected(false);
} //comboBox
if (comboBox.getSelectedItem()=="Item 1") {
comboBox_1.setSelectedItem("Item 1");
JAVA -PROFESOR: ING. FREIDY NUÑEZ

} if (comboBox.getSelectedItem()=="Item 2")
{ comboBox_1.setSelectedItem("Item 2");
} if (comboBox.getSelectedItem()=="Item 3")
{ comboBox_1.setSelectedItem("Item 3");
}
}
}

2- Crea un generador de números gráfico. Nosotros escribiremos seleccionaremos


dos números en unos JSpinner (contadores) y se nos mostrara en un JTextField,
el número generado entre esos dos números, al pulsar en el botón. El JTextField
no debe ser editable.

package Pruebas;
import java.awt.EventQueue; import
javax.swing.JFrame; import
javax.swing.JLabel; import
javax.swing.JScrollPane; import
javax.swing.JTextField; import
javax.swing.JButton; import
JAVA -PROFESOR: ING. FREIDY NUÑEZ
javax.swing.JSpinner; import
javax.swing.SpinnerNumberModel; import
java.awt.Font; import
javax.swing.event.ChangeListener; import
javax.swing.event.ChangeEvent; import
java.awt.event.ActionListener; import
java.awt.event.ActionEvent; public class
GeneradorNumeros { private JFrame frame;
private JTextField textField;
JSpinner spinner1, spinner2;
JButton Button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() { try {
GeneradorNumeros window = new GeneradorNumeros();
window.frame.setVisible(true); } catch (Exception
e) { e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GeneradorNumeros() { initialize();
}
//Generador de numeros
int generaNumeroAleatorio(int minimo, int maximo){
int num=(int)Math.floor(Math.random()*(minimo-(maximo+1))+(maximo+1));
return num;
}
/**
* Initialize the contents of the frame.
*/ private void
initialize(){ frame = new
JFrame();
frame.setTitle("Generador de números");
frame.setSize(314, 264); frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//componentes
JLabel lblNewLabel = new JLabel("N\u00FAmero 1");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel.setBounds(24, 35, 73, 35);
frame.getContentPane().add(lblNewLabel); JLabel
lblNewLabel_1 = new JLabel("N\u00FAmero 2");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel_1.setBounds(24, 80, 73, 35);
frame.getContentPane().add(lblNewLabel_1);
JAVA -PROFESOR: ING. FREIDY NUÑEZ

JLabel lblNewLabel_2 = new JLabel("N\u00FAmero generado");


lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel_2.setBounds(24, 132, 138, 28);
frame.getContentPane().add(lblNewLabel_2); textField = new
JTextField(); textField.setEditable(false);
textField.setBounds(172, 132, 97, 26);
frame.getContentPane().add(textField);
textField.setColumns(10); Button = new JButton("Generar");
Button.setBounds(94, 170, 85, 21);
frame.getContentPane().add(Button);
//spinners spinner1 = new
JSpinner();
spinner1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
}
});
spinner1.setBounds(173, 41, 96, 27);
frame.getContentPane().add(spinner1); spinner2 =
new JSpinner(); spinner2.addChangeListener(new
ChangeListener() { public void
stateChanged(ChangeEvent e) {
} });
spinner2.setModel(new SpinnerNumberModel(new Integer(0), null,
null, new Integer(1))); spinner2.setBounds(173, 86, 96, 27);
frame.getContentPane().add(spinner2); //listener
Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Asignacion de los spinner a variables int
numero1 = (int)spinner1.getValue(); int numero2
= (int)spinner2.getValue();
//generando numero aletorio
String
NumeroResult=String.valueOf(generaNumeroAleatorio(numero1,numero2));
//Asignando numero al jtextfield
textField.setText(NumeroResult);
}
});
}}

3- Crea una mini encuesta gráfica. Daremos una serie de opciones para que el
usuario elija. La encuesta preguntará lo siguiente:

 Elije un sistema operativo (solo una opción, JRadioButton)

 Windows
JAVA -PROFESOR: ING. FREIDY NUÑEZ
 Linux

 Mac
 Elije tu especialidad (pueden seleccionar ninguna o varias opciones,
JCheckBox)

 Programación

 Diseño gráfico

 Administración
 Horas dedicadas en el ordenador (usaremos un slider entre 0 y 10) Para
el slider, recomiendo usar un JLabel, que diga qué valor tiene el slider,
usar el evento stateChanged.y al final mostrar un mensaje similar al que
está debajo de la primera imagen.
JAVA -PROFESOR: ING. FREIDY NUÑEZ

package Pruebas; import


java.awt.EventQueue; import
javax.swing.JFrame; import
java.awt.BorderLayout; import
javax.swing.BoxLayout; import
javax.swing.ButtonGroup; import
javax.swing.JLabel; import
javax.swing.JOptionPane; import
javax.swing.SwingConstants; import
javax.swing.JPanel; import
javax.swing.JRadioButton; import
java.awt.Font; import
java.awt.event.ActionEvent; import
java.awt.event.ActionListener; import
javax.swing.JCheckBox; import
javax.swing.JSlider; import
javax.swing.JButton; import
javax.swing.event.ChangeListener; import
javax.swing.event.ChangeEvent; public
class MiniEncuesta { private JFrame
frame;
JRadioButton RButton1,RButton2,RButton3; private
JPanel panel_1;
private JCheckBox CheckBox, CheckBox_1,CheckBox_2;
private JButton Button;
private JLabel Label1,Label2,Label3,Label4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() { try {
JAVA -PROFESOR: ING. FREIDY NUÑEZ
MiniEncuesta window = new MiniEncuesta();
window.frame.setVisible(true); } catch
(Exception e) { e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/ public
MiniEncuesta() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() { frame
= new JFrame();
frame.setTitle("MiniEncuesta");
frame.setSize(250, 337);
frame.setResizable(false);
frame.setLocationRelativeTo(null)
;
frame.setDefaultCloseOperation(JF
rame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
null);
ButtonGroup grupo= new ButtonGroup();
//componentes
JPanel panel = new JPanel(); panel.setBounds(10, 10,
221, 85); frame.getContentPane().add(panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Label1 = new JLabel("Elegi un sistema operativo");
panel.add(Label1);
RButton1 = new JRadioButton("Wimdows"); panel.add(RButton1);
RButton2 = new JRadioButton("Linex"); panel.add(RButton2);
RButton3= new JRadioButton("Mac");
panel.add(RButton3);
grupo.add(RButton1);
grupo.add(RButton2);
grupo.add(RButton3); panel_1 = new
JPanel(); panel_1.setBounds(10, 105,
221, 85);
frame.getContentPane().add(panel_1);
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
Label2 = new JLabel("Elige tu especilidad"); panel_1.add(Label2);
//checksboxs
CheckBox = new JCheckBox("Programación");
panel_1.add(CheckBox);
CheckBox_1 = new JCheckBox("Diseño Gráfico");
panel_1.add(CheckBox_1);
CheckBox_2 = new JCheckBox("Administración");
panel_1.add(CheckBox_2);
//slider
JAVA -PROFESOR: ING. FREIDY NUÑEZ

Label3 = new JLabel("Horas que dedicas en el computador");


Label3.setBounds(10, 200, 221, 22);
frame.getContentPane().add(Label3);
JSlider slider = new JSlider();
slider.setValue(0); slider.setMaximum(10);
slider.setBounds(31, 223, 200, 22);
frame.getContentPane().add(slider);
//componentes
Button = new JButton("Generar"); Button.setBounds(83,
255, 85, 21); frame.getContentPane().add(Button);
Label4 = new JLabel("0");
Label4.setFont(new Font("Tahoma", Font.PLAIN, 15));
Label4.setBounds(10, 223, 26, 22);
frame.getContentPane().add(Label4);
slider.addChangeListener(new ChangeListener() { public
void stateChanged(ChangeEvent e) {
Label4.setText(String.valueOf(slider.getValue()));
}
});
//listener
Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { String
info="Tu sistema operativo preferido es: ";
JRadioButton [] RBut= {RButton1,RButton2,RButton3};
for(int i=0; i<RBut.length;i++){
if(RBut[i].isSelected()){ info+=RBut[i].getText();
}
}
JCheckBox[] CBox={CheckBox, CheckBox_1, CheckBox_2};

info+=", \ntus especialidades son ";

for(int i=0;i<CBox.length;i++){

if(CBox[i].isSelected()){
info+=CBox[i].getText()+"
";
}
}

JOptionPane.showMessageDialog(null, info, "Muestra de datos",


JOptionPane.INFORMATION_MESSAGE);
}});
}}

4- Crea una simple lista de películas. tendremos un JComboBox, donde


almacenaremos las películas, que vayamos almacenando en un campo de texto. Al pulsar
el botón Añadir la película que hayamos metido, se introducirá en el JComboBox
JAVA -PROFESOR: ING. FREIDY NUÑEZ

El diseño de estos ejercicios es decisión de ustedes.


5- Crear la clase Triángulo. Debe incluir los siguientes métodos que devuelven un valor
booleano:
a) esEscaleno

b) esIsósceles
c) esEquilátero
d) tieneAnguloRecto
Agregar el código necesario para probarla.
package Pruebas; import
java.awt.EventQueue; import
javax.swing.JFrame; import
javax.swing.JLabel; import
javax.swing.JOptionPane; import
javax.swing.JTextField; import
javax.swing.JButton; import
java.awt.event.ActionListener; import
java.awt.event.ActionEvent; import
java.awt.Font; public class
TrianguloMain { private JFrame frame;
public JTextField textField1,textField2, textField3;
JButton Button;
int NumMayor,NumMenor1,NumMenor2, NumMenorT;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() { try {
TrianguloMain window = new
TrianguloMain();
window.frame.setVisible(true);
JAVA -PROFESOR: ING. FREIDY NUÑEZ

} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TrianguloMain() { initialize();
}
/**
JAVA -PROFESOR: ING. FREIDY NUÑEZ *
Initialize the contents of the frame.
*/ private void initialize() { frame = new JFrame();
frame.setSize(417, 254); frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setTitle("Calculadora de tipos de triangulos");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//componentes graficos
JLabel lblNewLabel = new JLabel("Digite la medida de los "
+ "3 lados del triangulo");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN,
15));
lblNewLabel.setBounds(32, 11, 454, 28);
frame.getContentPane().add(lblNewLabel); JLabel
lblNewLabel_1 = new JLabel("Lado 1:");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN,
15)); lblNewLabel_1.setBounds(32, 49, 85, 19);
frame.getContentPane().add(lblNewLabel_1); JLabel
lblNewLabel_2 = new JLabel("Lado 2:");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN,
15)); lblNewLabel_2.setBounds(32, 86, 85, 19);
frame.getContentPane().add(lblNewLabel_2); JLabel
lblNewLabel_3 = new JLabel("Lado 3:");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN,
15)); lblNewLabel_3.setBounds(32, 123, 85,
16);
frame.getContentPane().add(lblNewLabel_3)
; textField1 = new JTextField();
textField1.setBounds(111, 51, 200, 19);
frame.getContentPane().add(textField1);
textField1.setColumns(10); textField2 =
new JTextField();
textField2.setBounds(111, 88, 200, 19);
frame.getContentPane().add(textField2);
textField2.setColumns(10); textField3 =
new JTextField();
textField3.setBounds(111, 122, 200, 19);
frame.getContentPane().add(textField3);
textField3.setColumns(10); Button = new
JButton("Obtener");
JAVA -PROFESOR: ING. FREIDY NUÑEZ
Button.setFont(new Font("Tahoma", Font.PLAIN, 15));
Button.setBounds(111, 166, 118, 28);
frame.getContentPane().add(Button);
//listener
Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { int
lado1=Integer.parseInt(textField1.getText()); int
lado2=Integer.parseInt(textField2.getText()); int
lado3=Integer.parseInt(textField3.getText());
if(esEscaleno(lado1,lado2,lado3)==true) { String
info="Es un triangulo: Escaleno";
JOptionPane.showMessageDialog(null, info,
"Resultado", JOptionPane.INFORMATION_MESSAGE);
} if(esIsósceles(lado1,lado2,lado3)==true)
{ String info="Es un triangulo:
Isósceles";
JOptionPane.showMessageDialog(null, info,
"Resultado", JOptionPane.INFORMATION_MESSAGE);
}
if(esEquilátero(lado1,lado2,lado3)==true) { String
info="Es un triangulo: Equilátero";
JOptionPane.showMessageDialog(null, info,
"Resultado", JOptionPane.INFORMATION_MESSAGE);
} if(tieneAnguloRecto(lado1,lado2,lado3)==true)
{ String info="Es un triangulo: Con angulo
recto";
JOptionPane.showMessageDialog(null, info,
"Resultado", JOptionPane.INFORMATION_MESSAGE);
}
textField1.setText("");
textField2.setText("");
textField3.setText("");
}
});
}
//metodos //escaleno
boolean esEscaleno(int lado1,int lado2, int lado3) {
if (lado1!=lado2 && lado1!=lado3 && lado2!=lado3) {
return true; }else { return false;
}}
//isosceles boolean esIsósceles(int lado1,int lado2,
int lado3) { if (lado1==lado2 && lado1!=lado3 &&
lado2!=lado3) { return true; }
if( lado1==lado3 && lado1!=lado2 && lado3!=lado2)
{ return true; }
if(lado2==lado3 && lado2!=lado1 && lado3!=lado1)
{ return true; } return false; } //equilatero
boolean esEquilátero (int lado1,int lado2, int lado3) {
if (lado1==lado2 && lado1==lado3 && lado2==lado3) {
return true; }else { return false;
}
} //AnguloRecto
boolean tieneAnguloRecto(int lado1,int lado2, int lado3) {
if(lado1>lado2 && lado1>lado3) {
JAVA -PROFESOR: ING. FREIDY NUÑEZ

NumMayor=lado1;
NumMenor1=lado2; NumMenor2=lado3;
} if(lado2>lado1 && lado2>lado3)
{
NumMayor=lado2;
NumMenor1=lado1;
NumMenor2=lado3;
}
if(lado3>lado1 && lado3>lado2) {
NumMayor=lado1;
NumMenor1=lado2; NumMenor2=lado3;
}
NumMayor=NumMayor*NumMayor;
NumMenor1=NumMenor1*NumMenor1;
NumMenor2=NumMenor2*NumMenor2;
NumMenorT=NumMenor1+NumMenor2;
if(NumMayor==NumMenorT) { return
true;
} return
false;
}
}

6. Un club tiene socios.


a) Crear la clase Socio con variables de instancia: nombre, número y variable de
Clase: PróximoNúmero.
b) Agregar los métodos de acceso y modificación
c) Inicializar en 1 el próximo número.
d) Crear un socio, mostrar sus datos
e) Crear otro socio, mostrar sus datos

package Pruebas; import


java.awt.EventQueue; import
javax.swing.JFrame; import
javax.swing.JLabel; import
java.awt.Font; import
javax.swing.JTextField; import
javax.swing.JSpinner; import
javax.swing.JButton; import
javax.swing.SpinnerNumberModel; import
java.awt.event.ActionListener; import
java.awt.event.ActionEvent; import
javax.swing.event.ChangeListener; import
javax.swing.event.ChangeEvent; import
JAVA -PROFESOR: ING. FREIDY NUÑEZ
javax.swing.JComboBox; import
javax.swing.DefaultComboBoxModel; import
java.awt.event.ItemListener; import
java.awt.event.ItemEvent; public class
MainClub { private JFrame frame;
JTextField textField1,textField2;
JLabel Label1,Label2,Label3;
JButton Button1,Button2; private
JComboBox comboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() { try {
MainClub window = new MainClub();
window.frame.setVisible(true); }
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/ public
MainClub() {
initialize();
}
/**
* Initialize the contents of the frame.
*/ private void initialize() { frame = new JFrame();
frame.setSize(223, 212); frame.setTitle("Club");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
; frame.getContentPane().setLayout(null);
//objetos
Socio s1= new Socio(); Socio s2= new
Socio(); s1.nombre= ("Robert Domingo");
s1.numero=("829-654-1593");
s2.nombre=("Erika Castro");
s2.numero=("849-654-5250"); Label1 = new
JLabel("Club de los socios");
Label1.setFont(new Font("Tahoma", Font.PLAIN, 20));
Label1.setBounds(10, 10, 198, 29);
frame.getContentPane().add(Label1);
Label2 = new JLabel("Nombre:");
Label2.setFont(new Font("Tahoma", Font.PLAIN, 16));
Label2.setBounds(10, 49, 85, 13);
frame.getContentPane().add(Label2);
Label3 = new JLabel("Numero: ");
Label3.setFont(new Font("Tahoma", Font.PLAIN, 16));
Label3.setBounds(10, 83, 85, 13);
JAVA -PROFESOR: ING. FREIDY NUÑEZ

frame.getContentPane().add(Label3); textField1 =
new JTextField(); textField1.setBounds(90, 49, 96,
19); frame.getContentPane().add(textField1);
textField1.setColumns(10); textField2 = new
JTextField(); textField2.setBounds(90, 82, 96, 19);
frame.getContentPane().add(textField2);
textField2.setColumns(10); Button1 = new
JButton("Acceso");
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
textField1.setText(""); textField2.setText("");
if(e.getStateChange()== ItemEvent.SELECTED) {
if(comboBox.getSelectedIndex()==1) {
s1.acceso(); }
if(comboBox.getSelectedIndex()==2) {
s2.acceso();
}
}
}
});
}
});
Button1.setBounds(88, 108, 98, 21);
frame.getContentPane().add(Button1);
Button2 = new JButton("Modificar");
Button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
textField1.setText(""); textField2.setText("");
if(e.getStateChange()== ItemEvent.SELECTED) {
if(comboBox.getSelectedIndex()==1) {
s1.modificacion(textField1.getText(),textField2.getText());
}
if(comboBox.getSelectedIndex()==2) {
s2.modificacion(textField1.getText(),textField2.getText());
}
}
}
});
}
});
Button2.setBounds(88, 134, 98, 21);
frame.getContentPane().add(Button2); comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Socios",
"Socio 1", "Socio 2"}));
comboBox.setBounds(10, 106, 68, 23);
frame.getContentPane().add(comboBox);
} //class socio
public class Socio {
//atributos
JAVA -PROFESOR: ING. FREIDY NUÑEZ
String nombre; String numero;
final static int proximoNumero=1;
//metodos void acceso() {
textField1.setText(this.nombre)
;
textField2.setText(this.numero)
;
}
void modificacion(String nombre,String numero)
{ this.nombre=nombre; this.numero=numero;
textField1.setText(nombre);
textField2.setText(numero);
}
}}

También podría gustarte