Skip to content

Instantly share code, notes, and snippets.

@nicolabovolato
Last active February 7, 2023 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolabovolato/fbe40ff535d4503f8f03d264b943afe0 to your computer and use it in GitHub Desktop.
Save nicolabovolato/fbe40ff535d4503f8f03d264b943afe0 to your computer and use it in GitHub Desktop.
Rubrica Java Swing
package Model;
import java.io.Serializable;
public class Contatto implements Serializable {
private String nome;
private String cognome;
private String telefono;
public Contatto(String nome, String cognome, String telefono) {
this.nome = nome;
this.cognome = cognome;
this.telefono = telefono;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String[] toArray(){
return new String[] {nome, cognome, telefono};
}
}
package View;
import Controller.Controller;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ContattoDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JTextField nomeField;
private JTextField telefonoField;
private JTextField cognomeField;
private boolean buttonOKPressed = false;
public ContattoDialog(JFrame f, String title) {
setTitle(title);
initialize();
setLocationRelativeTo(f);
setVisible(true);
}
public ContattoDialog(JFrame f, String title, String nome, String cognome, String telefono) {
setTitle(title);
nomeField.setText(nome);
cognomeField.setText(cognome);
telefonoField.setText(telefono);
initialize();
setLocationRelativeTo(f);
setVisible(true);
}
private void initialize() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener((ActionEvent e) -> {
buttonOKPressed = true;
dispose();
});
buttonCancel.addActionListener((ActionEvent e) -> {
dispose();
});
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
}
public JButton getButtonOK() {
return buttonOK;
}
public boolean isButtonOKPressed() {
return buttonOKPressed;
}
public JTextField getNomeField() {
return nomeField;
}
public JTextField getTelefonoField() {
return telefonoField;
}
public JTextField getCognomeField() {
return cognomeField;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
final JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
contentPane.add(panel1, gbc);
buttonOK = new JButton();
buttonOK.setText("OK");
panel1.add(buttonOK);
buttonCancel = new JButton();
buttonCancel.setText("Annulla");
panel1.add(buttonCancel);
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
contentPane.add(panel2, gbc);
final JLabel label1 = new JLabel();
label1.setText("Nome");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
panel2.add(label1, gbc);
nomeField = new JTextField();
nomeField.setText("");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel2.add(nomeField, gbc);
final JLabel label2 = new JLabel();
label2.setText("Cognome");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
panel2.add(label2, gbc);
cognomeField = new JTextField();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel2.add(cognomeField, gbc);
final JLabel label3 = new JLabel();
label3.setText("Telefono");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
panel2.add(label3, gbc);
telefonoField = new JTextField();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel2.add(telefonoField, gbc);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
package Controller;
import Model.*;
import View.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller implements ActionListener {
private Finestra finestra;
private Rubrica rubrica;
public Controller(Finestra f, Rubrica r){
this.finestra = f;
this.rubrica = r;
//Aggiungo l'action Listener ai vari bottoni dell' app
finestra.getAggiungiButton().addActionListener(this);
finestra.getModificaButton().addActionListener(this);
finestra.getRimuoviButton().addActionListener(this);
finestra.getImportaButton().addActionListener(this);
finestra.getEsportaButton().addActionListener(this);
finestra.getTabellaRubrica().setModel(rubrica);
}
@Override
public void actionPerformed(ActionEvent e) {
String errore = "";
// Filtro il componente che ha chiamato actionPerformed(), in base a questo eseguo azioni diverse
if (e.getSource() == finestra.getAggiungiButton()) errore = aggiungiPersona();
else if (e.getSource() == finestra.getModificaButton()) errore = modificaPersona();
else if (e.getSource() == finestra.getRimuoviButton()) errore = rimuoviPersona();
else if(e.getSource() == finestra.getImportaButton()) errore = importaFile();
else if(e.getSource() == finestra.getEsportaButton()) errore = esportaFile();
// Se la stringa errore non è vuota mostro un dialog con l'errore
if(!errore.isEmpty()) JOptionPane.showMessageDialog(finestra.getFrame(), errore, "Avviso", JOptionPane.WARNING_MESSAGE);
}
private String aggiungiPersona(){
//Apro un dialog per aggiungere un contatto
ContattoDialog dialog = new ContattoDialog(finestra.getFrame(), "Nuovo Contatto");
if(!dialog.isButtonOKPressed()) return "";
String nome = dialog.getNomeField().getText().trim();
String cognome = dialog.getCognomeField().getText().trim();
String telefono = dialog.getTelefonoField().getText().trim();
if(nome.isEmpty()) return "Nome non può essere vuoto";
if(cognome.isEmpty()) return "Cognome non può essere vuoto";
if(telefono.isEmpty()) return "Telefono non può essere vuoto";
if(!telefono.matches("[0-9+]+")) return "Numero di telefono non valido";
if(rubrica.find(telefono)) return "Esiste già un contatto con con il numero " + telefono;
rubrica.add(new Contatto(nome, cognome, telefono));
return "";
}
private String modificaPersona(){
// Apro un dialog per modificare il contatto selezionato
if(finestra.getTabellaRubrica().getSelectedRow() < 0) return "Nessuna persona selezionata";
Contatto c = rubrica.elementAt(finestra.getTabellaRubrica().getSelectedRow());
ContattoDialog dialog = new ContattoDialog(finestra.getFrame(),"Modifica Contatto", c.getNome(), c.getCognome(), c.getTelefono());
if(!dialog.isButtonOKPressed()) return "";
String vecchioTelefono = rubrica.elementAt(finestra.getTabellaRubrica().getSelectedRow()).getTelefono();
String nome = dialog.getNomeField().getText().trim();
String cognome = dialog.getCognomeField().getText().trim();
String telefono = dialog.getTelefonoField().getText().trim();
if(nome.isEmpty()) return "Nome non può essere vuoto";
if(cognome.isEmpty()) return "Cognome non può essere vuoto";
if(telefono.isEmpty()) return "Telefono non può essere vuoto";
if(!telefono.matches("[0-9+]+")) return "Numero di telefono non valido";
if(rubrica.find(telefono)) return "Esiste già un contatto con con il numero " + telefono;
rubrica.edit(vecchioTelefono, new Contatto(nome, cognome, telefono));
return "";
}
private String rimuoviPersona(){
// Apro un dialog per rimuovere il contatto selezionato
if(finestra.getTabellaRubrica().getSelectedRow() < 0) return "Nessuna persona selezionata";
Contatto c = rubrica.elementAt(finestra.getTabellaRubrica().getSelectedRow());
int val = JOptionPane.showConfirmDialog(finestra.getFrame(), "Rimuovere "+ c.getNome() +" "+ c.getCognome() + " dalla rubrica?", "Rimuovi Contatto", JOptionPane.YES_NO_OPTION);
if(val != JOptionPane.YES_OPTION) return "";
String telefono = rubrica.elementAt(finestra.getTabellaRubrica().getSelectedRow()).getTelefono();
rubrica.remove(telefono);
return "";
}
private String importaFile(){
// Apro un dialog per selezionare un file
JFileChooser fc = new JFileChooser();
int val = fc.showOpenDialog(finestra.getFrame());
if(val == JFileChooser.APPROVE_OPTION){
if(!rubrica.importFromFile(fc.getSelectedFile())) return "Errore nella lettura del file";
}
return "";
}
private String esportaFile(){
// Apro un dialog per salvare un file
JFileChooser fc = new JFileChooser();
int val = fc.showSaveDialog(finestra.getFrame());
if(val == JFileChooser.APPROVE_OPTION){
if(!rubrica.exportToFile(fc.getSelectedFile())) return "Errore nella scrittura del file";
}
return "";
}
}
package Model;
import java.io.*;
import java.util.Vector;
public class FileOps {
public static void writeAll(File f, Vector<Contatto> rubrica) throws IOException {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(Contatto p : rubrica){
oos.writeObject(p);
oos.reset();
}
}
public static Vector<Contatto> readAll(File f) throws ClassNotFoundException, IOException{
Vector<Contatto> rubrica = new Vector<Contatto>();
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while(fis.available() != -1){
Contatto p = (Contatto) ois.readObject();
rubrica.add(p);
}
}
catch(EOFException e){}
return rubrica;
}
}
package View;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class Finestra {
private JPanel panel1;
private JButton aggiungiButton;
private JButton modificaButton;
private JButton rimuoviButton;
private JTable tabellaRubrica;
private JButton importaButton;
private JButton esportaButton;
private JFrame frame;
public Finestra() {
frame = new JFrame();
frame.setContentPane(this.panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JButton getAggiungiButton() {
return aggiungiButton;
}
public JButton getModificaButton() {
return modificaButton;
}
public JButton getRimuoviButton() {
return rimuoviButton;
}
public JButton getImportaButton() {
return importaButton;
}
public JButton getEsportaButton() {
return esportaButton;
}
public JTable getTabellaRubrica() {
return tabellaRubrica;
}
public JFrame getFrame() {
return frame;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout(0, 0));
final JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout(0, 0));
panel1.add(panel2, BorderLayout.NORTH);
final JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
panel2.add(panel3, BorderLayout.WEST);
final JLabel label1 = new JLabel();
Font label1Font = this.$$$getFont$$$(null, -1, 24, label1.getFont());
if (label1Font != null) label1.setFont(label1Font);
label1.setText("Rubrica");
panel3.add(label1);
final JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
panel2.add(panel4, BorderLayout.CENTER);
final JToolBar.Separator toolBar$Separator1 = new JToolBar.Separator();
panel4.add(toolBar$Separator1);
final JToolBar.Separator toolBar$Separator2 = new JToolBar.Separator();
panel4.add(toolBar$Separator2);
aggiungiButton = new JButton();
aggiungiButton.setText("Aggiungi");
panel4.add(aggiungiButton);
modificaButton = new JButton();
modificaButton.setText("Modifica");
panel4.add(modificaButton);
rimuoviButton = new JButton();
rimuoviButton.setText("Rimuovi");
panel4.add(rimuoviButton);
final JToolBar.Separator toolBar$Separator3 = new JToolBar.Separator();
panel4.add(toolBar$Separator3);
importaButton = new JButton();
importaButton.setText("Importa");
panel4.add(importaButton);
esportaButton = new JButton();
esportaButton.setText("Esporta");
panel4.add(esportaButton);
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setEnabled(true);
panel1.add(scrollPane1, BorderLayout.CENTER);
scrollPane1.setBorder(BorderFactory.createTitledBorder(null, "Contatti", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
tabellaRubrica = new JTable();
scrollPane1.setViewportView(tabellaRubrica);
}
/**
* @noinspection ALL
*/
private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
if (currentFont == null) return null;
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return panel1;
}
}
import Controller.Controller;
import Model.Rubrica;
import View.Finestra;
public class Main {
public static void main(String[] args) {
// Istanzio view e model, poi li collego istanziando controller
Finestra view = new Finestra();
Rubrica model = new Rubrica();
Controller controller = new Controller(view, model);
}
}
package Model;
import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.util.Vector;
public class Rubrica extends AbstractTableModel {
private Vector<Contatto> rubrica;
private String[] columnNames = {"Nome", "Cognome", "Telefono"};
public Rubrica(){
this.rubrica = new Vector<Contatto>();
}
public Rubrica(Vector<Contatto> rubrica){
this.rubrica = rubrica;
}
@Override
public int getRowCount() {
return rubrica.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rubrica.get(rowIndex).toArray()[columnIndex];
}
public boolean find(String telefono) {
for(Contatto c : rubrica){
if(c.getTelefono().equals(telefono)) return true;
}
return false;
}
public void add(Contatto c){
rubrica.add(c);
int index = rubrica.indexOf(c);
fireTableRowsInserted(index, index);
}
public void remove(String telefono){
for(Contatto c : rubrica){
if(c.getTelefono().equals(telefono)){
rubrica.remove(rubrica.indexOf(c));
int index = rubrica.indexOf(c);
fireTableRowsDeleted(index, index);
return;
}
}
}
public void edit(String telefono, Contatto newContatto){
for(Contatto c : rubrica){
if(c.getTelefono().equals(telefono)){
c.setNome(newContatto.getNome());
c.setCognome(newContatto.getCognome());
c.setTelefono(newContatto.getTelefono());
int index = rubrica.indexOf(c);
fireTableRowsUpdated(index, index);
return;
}
}
}
public Contatto elementAt(int index){
return rubrica.elementAt(index);
}
public boolean exportToFile(File file){
try{
FileOps.writeAll(file, rubrica);
fireTableDataChanged();
return true;
}
catch(Exception e){
return false;
}
}
public boolean importFromFile(File file){
try{
rubrica = FileOps.readAll(file);
fireTableDataChanged();
return true;
}
catch(Exception e){
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment