Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Usuario Invitado

#361
Java / Re: Error con char y métodos listas
16 Marzo 2015, 02:57 AM
Hasta donde tengo entendido sobre lo que deseas hacer, lo haría así:

Código (java) [Seleccionar]
package com.company.app.model.entities;

public class Employee {
private Short id;
private String names;
private String surnames;
private Double salary;

public Employee() {}

public Employee(Short id, String names, String surnames, Double salary) {
super();
this.id = id;
this.names = names;
this.surnames = surnames;
this.salary = salary;
}

public Short getId() {
return id;
}

public void setId(Short id) {
this.id = id;
}

public String getNames() {
return names;
}

public void setNames(String names) {
this.names = names;
}

public String getSurnames() {
return surnames;
}

public void setSurnames(String surnames) {
this.surnames = surnames;
}

public Double getSalary() {
return salary;
}

public void setSalary(Double salary) {
this.salary = salary;
}


}


Código (java) [Seleccionar]
package com.company.app.model.entities;

import java.util.ArrayList;

public class EmployeeList extends ArrayList<Employee> {
private static final long serialVersionUID = 2924861284507271931L;

public EmployeeList() {
super();
}

public boolean hasRepeatProperties(Employee employee) {
boolean hasRepeat = false;
for(Employee e : this) {
if(e.equals(employee))
continue;
if(compareProperties(e.getId(), employee.getId())) {
hasRepeat = true;
break;
}
else if(compareProperties(e.getNames(), employee.getNames())) {
hasRepeat = true;
break;
}
else if(compareProperties(e.getSurnames(), employee.getSurnames())) {
hasRepeat = true;
break;
}
else if(compareProperties(e.getSalary(), employee.getSalary())) {
hasRepeat = true;
break;
}
}

return hasRepeat;
}

private boolean compareProperties(Object first, Object second) {
boolean hasRepeat = false;
if(first instanceof String) {
hasRepeat = first.equals(second);
}
else if (first instanceof Short){
hasRepeat = ((Short) first).shortValue() == ((Short) second).shortValue();
}
else if (first instanceof Double) {
hasRepeat = ((Double) first).doubleValue() == ((Double) second).doubleValue();
}

return hasRepeat;
}

}


Código (java) [Seleccionar]
package com.company.app;

import java.util.Scanner;

import com.company.app.model.entities.Employee;
import com.company.app.model.entities.EmployeeList;

public class Main {

public static void main(String[] args) {
EmployeeList employeeList = new EmployeeList();
Scanner reader = new Scanner(System.in);
String option = "S";

do {
Employee employee = new Employee();
System.out.println("Ingrese el ID del nuevo empleado");
employee.setId(Short.valueOf(reader.nextLine()));
System.out.println("\nIngrese sus nombres:");
employee.setNames(reader.nextLine());
System.out.println("\nIngrese sus apellidos");
employee.setSurnames(reader.nextLine());
System.out.println("Ingrese su salario");
employee.setSalary(Double.valueOf(reader.nextLine()));
employeeList.add(employee);
System.out.println("\n¿Desea seguir agregando empleados? S/N");
option = reader.nextLine();
}
while(option.equalsIgnoreCase("s"));
reader.close();

for(Employee employee : employeeList) {
if(employeeList.hasRepeatProperties(employee))
continue;
System.out.println("ID del empleado: "+employee.getId());
System.out.println("Nombres: "+employee.getNames());
System.out.println("Apellidos: "+employee.getSurnames());
System.out.println("Salario: "+employee.getSalary());
}

}

}


Claro que está demás decir que tienes que manejar las excepciones que pueden ocurrir (NumberFormatException, InputMismatchException).
#362
Java / Re: Meter un Frame dentro de otro Frame
15 Marzo 2015, 18:27 PM
Yo siempre recomiendo aislar la lógica, el dominio de las vistas. Aplicar el patrón MVC para desacoplar tu aplicación te ahorrará muchos problemas.

Por ejemplo, supongamos que tienes tu Frame o JFrame (Dile con todo respeto a tu profesor que no enseñe tecnologías obsoletas):

MainWindow.java
Código (java) [Seleccionar]
package com.company.app.views;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.company.app.controllers.MainWindowController;
import com.company.app.model.entities.Population;

public class MainWindow extends JFrame {
private static final long serialVersionUID = -2973563217322489640L;
private JMenuItem iOpen;
private JMenuItem iExit;
private JMenuItem iNewProvince;
private JMenuItem iUpdateProvince;
private JMenuItem iNewPopulation;
private JMenuItem iUpdatePopulation;
private JMenuItem iAbout;
private JButton btnUpdatePrediction;
private JButton btnNewProvince;
private JButton btnNewPopulation;
private JList<String> provinceList;
private JList<Population> populationList;
private JLabel lblFooter;
private MainWindowController controller;

public MainWindow() {
super();
controller = new MainWindowController(this);
initComponents();
}

private void initComponents() {
this.setLayout(new BorderLayout(10,10));

JPanel top = new JPanel(new BorderLayout());
top.setLayout(new GridLayout(2,1,0,0));
top.add(addMenuBar());
top.add(addToolbar());
this.add(BorderLayout.NORTH, top);
JPanel center = new JPanel(new BorderLayout(10,10));
center.add(BorderLayout.WEST, addProvincesPanel());
center.add(BorderLayout.CENTER, addPredictionsPanel());
this.add(BorderLayout.CENTER, center);
this.add(BorderLayout.SOUTH, addFooterPanel());

this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame.setDefaultLookAndFeelDecorated(true);
this.setTitle("Sistema metereológico");
this.setSize(800,600);
try {
UIManager.setLookAndFeel(
        UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}

}

private JMenuBar addMenuBar() {
JMenuBar menubar = new JMenuBar();
menubar.setBackground(new Color(50,50,50));

JMenu menuFile = new JMenu("Archivo");
menuFile.setForeground(Color.WHITE);
iOpen = new JMenuItem("Abrir...");
iOpen.addActionListener(controller);
iExit = new JMenuItem("Salir");
iExit.addActionListener(controller);
menuFile.add(iOpen);
menuFile.add(iExit);

JMenu menuProvince = new JMenu("Provincias");
menuProvince.setForeground(Color.WHITE);
iNewProvince = new JMenuItem("Nueva provincia");
iNewProvince.addActionListener(controller);
iUpdateProvince = new JMenuItem("Actualizar provincia");
iUpdateProvince.addActionListener(controller);
menuProvince.add(iNewProvince);
menuProvince.add(iUpdateProvince);

JMenu menuPopulation = new JMenu("Poblaciones");
menuPopulation.setForeground(Color.WHITE);
iNewPopulation = new JMenuItem("Nueva población");
iNewPopulation.addActionListener(controller);
iUpdatePopulation = new JMenuItem("Actualizar población");
iUpdatePopulation.addActionListener(controller);
menuPopulation.add(iNewPopulation);
menuPopulation.add(iUpdatePopulation);

JMenu menuAbout = new JMenu("Ayuda");
menuAbout.setForeground(Color.WHITE);
iAbout = new JMenuItem("Acerca...");
iAbout.addActionListener(controller);
menuAbout.add(iAbout);

menubar.add(menuFile);
menubar.add(menuProvince);
menubar.add(menuPopulation);
menubar.add(menuAbout);

return menubar;
}

private JPanel addToolbar() {
JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.LEFT));
toolbar.setBackground(new Color(0,184,255));
toolbar.setSize(50,100);
btnUpdatePrediction = new JButton("Actualizar predicción");
btnUpdatePrediction.setFocusable(false);
btnUpdatePrediction.addActionListener(controller);
btnNewProvince = new JButton("Nueva provincia");
btnNewProvince.setFocusable(false);
btnNewProvince.addActionListener(controller);
btnNewPopulation = new JButton("Nueva población");
btnNewPopulation.setFocusable(false);
btnNewPopulation.addActionListener(controller);

toolbar.add(btnUpdatePrediction);
toolbar.add(btnNewProvince);
toolbar.add(btnNewPopulation);

return toolbar;
}

private JPanel addProvincesPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();

provinceList = new JList<>();
populationList = new JList<>();

constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
panel.add(new JLabel("Provincias"), constraints);

constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.BOTH;
panel.add(new JScrollPane(provinceList), constraints);


constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 1;
constraints.gridheight = 1;
panel.add(new JLabel("Poblaciones"), constraints);

constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.BOTH;
panel.add(new JScrollPane(populationList), constraints);

return panel;
}

private JPanel addPredictionsPanel() {
JPanel panel = new JPanel(new BorderLayout());
JLabel provinceName = new JLabel("Predicciones para ");
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
panel.add(BorderLayout.NORTH, provinceName);
panel.add(BorderLayout.CENTER, new JScrollPane(textArea));

return panel;
}

private JPanel addFooterPanel() {
JPanel panel = new JPanel();
panel.setBackground(new Color(80,80,80));
lblFooter = new JLabel("Sistema metereológico");
lblFooter.setForeground(new Color(200,200,200));
panel.add(lblFooter);

return panel;
}

}


MainWindowController.java

Código (java) [Seleccionar]
package com.company.app.controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.company.app.views.MainWindow;
import com.company.app.views.NewProvinceDialog;

public class MainWindowController implements ActionListener {
private MainWindow gui;

public MainWindowController(MainWindow gui) {
this.gui = gui;
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Nueva provincia")) {
NewProvinceDialog dialog = new NewProvinceDialog(gui);
dialog.setVisible(true);
}
}

}


NewProvinceDialog.java

Código (java) [Seleccionar]
package com.company.app.views;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class NewProvinceDialog extends JDialog {
private static final long serialVersionUID = -3369879094143739366L;
private JTextField txtProvince;
private JButton btnAddProvince;

public NewProvinceDialog(JFrame parent) {
super(parent);
initComponents(parent);
}

private void initComponents(JFrame parent) {
JPanel panel = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Nombre de la provincia:");
txtProvince = new JTextField();
btnAddProvince = new JButton("Agregar");

GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weighty = 1.0;
panel.add(label, constraints);

constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 3;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(txtProvince, constraints);

constraints = new GridBagConstraints();
constraints.gridx = 3;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.EAST;
panel.add(btnAddProvince, constraints);

this.add(panel);
this.setTitle("Agregar nueva provincia");
this.setSize(280,100);
this.setModal(true);
this.setLocationRelativeTo(parent);
this.setResizable(false);

}

}


Imágenes:





Sólo es cosa de jugar con los layouts y delegar responsabilidades correctamente. Cualquier duda, comentas.
#363
Java / Re: Meter un Frame dentro de otro Frame
14 Marzo 2015, 21:21 PM
Cuando tengas una duda, primero consulta la documentación. Para eso está, para que los programadores la consulten ante cualquier duda. Aquí tienes la documentación de GridLayout: GridLayout.

Como se puede observar tiene sobrecarga de constructores. El otro constructor acepta 4 parámetros, siendo los últimos el espaciado horizontal y el espaciado vertical. Juega con éstos valores a ver si consigues lo que deseas hacer.
#364
Java / Re: Error metodo main
13 Marzo 2015, 21:14 PM
Para eso puedes concatenar los caracteres así:

Código (java) [Seleccionar]
String key = "";
for(char c : u.calcularClave())
    key += c;
System.out.println("La clave es: "+key);


Saludos.
#365
Java / Re: Error metodo main
13 Marzo 2015, 21:01 PM
Te daré algunos consejos:

1) Utiliza nombres descriptivos a las variables.
2) Modulariza código. Ese proceso largo lo puedes hacer en varios pequeños.

Si no sigues éstos dos simples consejos, tu código se convertirá en una completa mezcla de palabras sin sentido. Es de vital importancia que sigas esos principios desde ahora.

Respecto a tu pregunta, te imprime la referencia del array. Lo que tienes que hacer es recorrer el array de vuelto en un for e ir imprimiendo carácter por carácter.

Código (java) [Seleccionar]
for(char c : u.calcularClave())
    System.out.print(c);
#366
Java / Re: Error metodo main
13 Marzo 2015, 20:42 PM
Vamos tío, si no pones el contenido de dicho método, ¿cómo esperas que te ayuden?
#367
Se puede transformar un XML con un schema. Aquí tienes un ejemplo:

Link: Transformar XML con XLST
#368
Creo que sí es posible pero solo será visible para el resto de clases que estén en el mismo fichero. También es posible crear una clase dentro de otra y se denominan clases Internas. Generalmente se usan para crear objetos que sirvan de ayuda a la clase madre sin tener que colocar dicha clase en un fichero y que sea visible para las demás clases.

Salu2.
#369
Java / Re: Meter un Frame dentro de otro Frame
13 Marzo 2015, 18:45 PM
Agrega un Panel en la parte izquierda, y a ese Panel le asignas el layout GridLayout. Lee la documentación de Oracle, tutoriales, para que veas ejemplos reales.
#370
¿Por qué no usas el API de Java para manejo de XML?. Te pongo un ejemplo:

User.java

Código (java) [Seleccionar]
package com.company.model.entities;

public class User {
private Integer id;
private Integer code;
private String name;

public User() {}

public User(Integer id, Integer code, String name) {
super();
this.id = id;
this.code = code;
this.name = name;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}


Product.java

Código (java) [Seleccionar]
package com.company.model.entities;

public class Product {
private Integer id;
private Long code;
private String description;

public Product() {}

public Product(Integer id, Long code, String description) {
super();
this.id = id;
this.code = code;
this.description = description;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Long getCode() {
return code;
}

public void setCode(Long code) {
this.code = code;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}


}


Report.java

Código (java) [Seleccionar]
package com.company.model.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.company.model.entities.Product;
import com.company.model.entities.User;

@XmlRootElement(name="report")
@XmlAccessorType(XmlAccessType.FIELD)
public class Report {
@XmlElement(name="user")
private List<User> users;
@XmlElement(name="product")
private List<Product> products;

public Report() {}

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}

public List<Product> getProducts() {
return products;
}

public void setProducts(List<Product> products) {
this.products = products;
}


}


ReportMarshaller.java

Código (java) [Seleccionar]
package com.company.model.jaxb;
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.company.model.jaxb.Report;


public class ReportMarshaller<T> {
private static JAXBContext jaxbContext;

public ReportMarshaller() throws JAXBException {
jaxbContext = JAXBContext.newInstance(Report.class);
}

public void marshal(Report report, File output) throws JAXBException {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(report, output);
}

public Report unmarshal(File input) throws JAXBException {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Report report = (Report) unmarshaller.unmarshal(input);
return report;
}

}


Main.java

Código (java) [Seleccionar]
package com.company.main;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.JAXBException;

import com.company.model.entities.Product;
import com.company.model.entities.User;
import com.company.model.jaxb.Report;
import com.company.model.jaxb.ReportMarshaller;

public class Main {

public static void main(String[] args) {
List<User> users = new ArrayList<>();
List<Product> products = new ArrayList<>();
Report report = new Report();
ReportMarshaller<Report> marshaller = null;

Collections.addAll(users,
new User(20, 001, "John Doe"),
new User(30, 002, "Homer Simpson"),
new User(40, 003, "Peter Griffin")
);
Collections.addAll(products,
new Product(10, 123456789123456789L, "Jabón antibacterial"),
new Product(20, 987654321987654321L, "Shampoo control caspa")
);
report.setUsers(users);
report.setProducts(products);

try {
marshaller = new ReportMarshaller<Report>();
marshaller.marshal(report, new File("D://test.xml"));
System.out.println("Leyendo el XML...");
System.out.println();
report = null;
report = marshaller.unmarshal(new File("D://test.xml"));
System.out.println("Usuarios:\n");
for(User user : report.getUsers()) {
System.out.println(user.getId());
System.out.println(user.getCode());
System.out.println(user.getName());
}
                       System.out.println("\nProductos:\n");
for(Product product : report.getProducts()) {
System.out.println(product.getId());
System.out.println(product.getCode());
System.out.println(product.getDescription());
}
} catch (JAXBException e) {
e.printStackTrace();
}

}

}






XML generado:

Código (XML) [Seleccionar]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<report>
   <user>
       <code>1</code>
       <id>20</id>
       <name>John Doe</name>
   </user>
   <user>
       <code>2</code>
       <id>30</id>
       <name>Homer Simpson</name>
   </user>
   <user>
       <code>3</code>
       <id>40</id>
       <name>Peter Griffin</name>
   </user>
   <product>
       <code>123456789123456789</code>
       <description>Jabón antibacterial</description>
       <id>10</id>
   </product>
   <product>
       <code>987654321987654321</code>
       <description>Shampoo control caspa</description>
       <id>20</id>
   </product>
</report>


Lectura del XML:

Leyendo el XML...

Usuarios:

20
1
John Doe
30
2
Homer Simpson
40
3
Peter Griffin

Productos:

10
123456789123456789
Jabón antibacterial
20
987654321987654321
Shampoo control caspa






El código es sencillo. El método marshal de Marshaller recibe dos parámetros:

1) El objeto anotado con XmlRootElement
2) Un objeto File de salida.

El método unmarshal recibe:

1) El objeto File que apunta al fichero XML a leer.

XmlRootElement indica que dicha clase es el primer nivel de la jerarquía XML. XmlElement indica que dicha propiedad o clase es un elemento dentro de la jerarquía (un tag).

Cualquier duda, comentas.