Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Certamente, vou fornecer um exemplo simples de um aplicativo CRUD em Java Swing com a

funcionalidade de login. Neste exemplo, os dados do usuário e os dados da entidade “Person” são
tratados separadamente. Lembre-se de que este exemplo usa uma abordagem de armazenamento
temporário e não deve ser usado em um ambiente de produção real.

1. **Classe `User`:**

```java

Public class User {

Private String username;

Private String password;

Public User(String username, String password) {

This.username = username;

This.password = password;

Public String getUsername() {

Return username;

Public String getPassword() {

Return password;

```

2. **Classe `Person`:**

```java

Public class Person {

Private String name;

Private int age;


Public Person(String name, int age) {

This.name = name;

This.age = age;

Public String getName() {

Return name;

Public int getAge() {

Return age;

```

3. **Classe `UserRepository`:**

```java

Import java.util.ArrayList;

Import java.util.List;

Public class UserRepository {

Private static List<User> users = new ArrayList<>();

Public static void addUser(User user) {

Users.add(user);

Public static boolean validateUser(String username, String password) {

For (User user : users) {

If (user.getUsername().equals(username) && user.getPassword().equals(password)) {

Return true;
}

Return false;

```

4. **Classe `PersonRepository`:**

```java

Import java.util.ArrayList;

Import java.util.List;

Public class PersonRepository {

Private static List<Person> persons = new ArrayList<>();

Public static void addPerson(Person person) {

Persons.add(person);

Public static List<Person> getAllPersons() {

Return new ArrayList<>(persons);

Public static void updatePerson(int index, Person updatedPerson) {

Persons.set(index, updatedPerson);

Public static void deletePerson(int index) {

Persons.remove(index);

}
```

5. **Classe `LoginApp`:**

```java

Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Public class LoginApp extends Jframe {

Private JtextField usernameField = new JtextField();

Private JpasswordField passwordField = new JpasswordField();

Public LoginApp() {

setTitle(“Login”);

setSize(300, 150);

setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);

Jbutton loginButton = new Jbutton(“Login”);

loginButton.addActionListener(new ActionListener() {

@Override

Public void actionPerformed(ActionEvent e) {

Login();

});

Jpanel panel = new Jpanel();

Panel.setLayout(new GridLayout(3, 2));

Panel.add(new Jlabel(“Username:”));

Panel.add(usernameField);

Panel.add(new Jlabel(“Password:”));
Panel.add(passwordField);

Panel.add(new Jlabel()); // Spacer

Panel.add(loginButton);

Add(panel);

setVisible(true);

Private void login() {

String username = usernameField.getText();

String password = new String(passwordField.getPassword());

If (UserRepository.validateUser(username, password)) {

Dispose(); // Close login window

New CRUDApp();

} else {

JoptionPane.showMessageDialog(this, “Invalid username or password”, “Error”,


JoptionPane.ERROR_MESSAGE);

Public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

Public void run() {

New LoginApp();

});

```
6. **Classe `CRUDApp`:**

```java

Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Import java.util.List;

Public class CRUDApp extends Jframe {

Private DefaultListModel<String> listModel = new DefaultListModel<>();

Private Jlist<String> personJList = new Jlist<>(listModel);

Private JtextField nameTextField = new JtextField();

Private JtextField ageTextField = new JtextField();

Public CRUDApp() {

setTitle(“CRUD App”);

setSize(400, 300);

setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);

Jbutton addButton = new Jbutton(“Add”);

Jbutton updateButton = new Jbutton(“Update”);

Jbutton deleteButton = new Jbutton(“Delete”);

addButton.addActionListener(new ActionListener() {

@Override

Public void actionPerformed(ActionEvent e) {

addPerson();

});
updateButton.addActionListener(new ActionListener() {

@Override

Public void actionPerformed(ActionEvent e) {

updatePerson();

});

deleteButton.addActionListener(new ActionListener() {

@Override

Public void actionPerformed(ActionEvent e) {

deletePerson();

});

Jpanel inputPanel = new Jpanel();

inputPanel.add(new Jlabel(“Name: “));

inputPanel.add(nameTextField);

inputPanel.add(new Jlabel(“Age: “));

inputPanel.add(ageTextField);

Jpanel buttonPanel = new Jpanel();

buttonPanel.add(addButton);

buttonPanel.add(updateButton);

buttonPanel.add(deleteButton);

add(inputPanel, “North”);

add(new JscrollPane(personJList), “Center”);

add(buttonPanel, “South”);

loadPersons();

setVisible(true);
}

Private void addPerson() {

String name = nameTextField.getText();

Int age = Integer.parseInt(ageTextField.getText());

Person person = new Person(name, age);

PersonRepository.addPerson(person);

updateList();

clearFields();

Private void updatePerson() {

Int selectedIndex = personJList.getSelectedIndex();

If (selectedIndex != -1) {

String name = nameTextField.getText();

Int age = Integer.parseInt(ageTextField.getText());

Person updatedPerson = new Person(name, age);

PersonRepository.updatePerson(selectedIndex, updatedPerson);

updateList();

clearFields();

Private void deletePerson() {

Int selectedIndex = personJList.getSelectedIndex();

If (selectedIndex != -1) {

PersonRepository.deletePerson(selectedIndex);

updateList();

clearFields();
}

Private void updateList() {

listModel.clear();

List<Person> persons = PersonRepository.getAllPersons();

For (Person person : persons) {

listModel.addElement(person.getName() + “ – “ + person.getAge());

Private void clearFields() {

nameTextField.setText(“”);

ageTextField.setText(“”);

personJList.clearSelection();

Private void loadPersons() {

updateList();

```

Lembre-se de ajustar e expandir conforme necessário, especialmente para adicionar medidas de


segurança adequadas ao armazenamento e validação de dados do usuário.

You might also like