root/java/SuperPostak/src/cz/frantovo/superPostak/PanelPrijemcu.java @ 0:e76872ad5226

Revision 0:e76872ad5226, 13.8 KB (checked in by František Kučera <franta-hg@…>, 15 years ago)

Přidání SuperPošťáka? do Mercurialu (původně byl v Subversionu)
Postak – základ, knihovna
SuperPostak? – GUI nadstavba
SuperPostak?2 – pokus o implementaci aplikace jako modulu pro Netbeans, POZOR: není přidán do Mercurialu, možná později (pravděpodobně se ale nebude používat)

Line 
1package cz.frantovo.superPostak;
2
3import cz.frantovo.gui.tabulky.TableSorterModel;
4import cz.frantovo.postak.InternetAddressKomu;
5import cz.frantovo.postak.Postak;
6import java.awt.Cursor;
7import java.io.BufferedReader;
8import java.io.File;
9import java.io.FileReader;
10import java.io.FileWriter;
11import java.io.OutputStreamWriter;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.HashSet;
15import java.util.logging.Level;
16import java.util.logging.Logger;
17import javax.swing.DefaultListSelectionModel;
18import javax.swing.JFileChooser;
19import javax.swing.event.TableModelEvent;
20import javax.swing.event.TableModelListener;
21import javax.swing.table.TableModel;
22
23/**
24 *
25 * @author  fiki
26 */
27public class PanelPrijemcu extends javax.swing.JPanel {
28
29    private static Logger log = Logger.getLogger(PanelPrijemcu.class.getName());
30    private ModelTabulky data = new ModelTabulky();
31
32    /** Creates new form PanelPrijemcu */
33    public PanelPrijemcu() {
34        initComponents();
35        tabulka.setModel(data);
36        tabulka.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
37    }
38
39    public ArrayList<InternetAddressKomu> getAdresy() {
40        /** TODO: vracet kopii? */
41        return data.data;
42    }
43
44    /**
45     * @param prijemci pokud je null, nastaví prázdná kolekce.
46     */
47    public void setAdresy(Collection<InternetAddressKomu> adresy) {
48        data.data = new ArrayList<InternetAddressKomu>();
49        pridejAdresu(adresy);
50    }
51
52    public void pridejAdresu(Collection<InternetAddressKomu> adresy) {
53        if (adresy == null) {
54            log.log(Level.FINER, "Prázdná množina adres - nic nepřidáme");
55        } else {
56            data.data.addAll(adresy);
57            data.upozorniPosluchace();
58        }
59    }
60
61    /**
62     * Pokud je needitovatelný, nelze měnit data v tabuce
63     * a z tlačítek je povoleno pouze tlačítko pro uložení do souboru.
64     */
65    public void setEditovatelny(boolean editovatelny) {
66        otevrit.setEnabled(editovatelny);
67        pridat.setEnabled(editovatelny);
68        odebrat.setEnabled(editovatelny);
69        tabulka.setEnabled(editovatelny);
70    }
71
72    /** This method is called from within the constructor to
73     * initialize the form.
74     * WARNING: Do NOT modify this code. The content of this method is
75     * always regenerated by the Form Editor.
76     */
77    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
78    private void initComponents() {
79
80        jScrollPane1 = new javax.swing.JScrollPane();
81        tabulka = new cz.frantovo.gui.tabulky.JTable();
82        pridat = new javax.swing.JButton();
83        odebrat = new javax.swing.JButton();
84        ulozit = new javax.swing.JButton();
85        otevrit = new javax.swing.JButton();
86
87        tabulka.setModel(new javax.swing.table.DefaultTableModel(
88            new Object [][] {
89                {null, null, null, null},
90                {null, null, null, null},
91                {null, null, null, null},
92                {null, null, null, null}
93            },
94            new String [] {
95                "Title 1", "Title 2", "Title 3", "Title 4"
96            }
97        ));
98        jScrollPane1.setViewportView(tabulka);
99
100        pridat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/frantovo/superPostak/obrazky/vlozit.png"))); // NOI18N
101        pridat.setMnemonic('i');
102        pridat.setText("Přidat");
103        pridat.setToolTipText("<html>\nPřidá prázdný řádek pro vložení nového příjemce<br/>\nAby se napsaná změna projevila, je potřeba kliknout jinam do tabulky<br/>\n(tzn. ukončit režim editace buňky)<br/>\n</html>");
104        pridat.addActionListener(new java.awt.event.ActionListener() {
105            public void actionPerformed(java.awt.event.ActionEvent evt) {
106                pridatActionPerformed(evt);
107            }
108        });
109
110        odebrat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/frantovo/superPostak/obrazky/editdelete.png"))); // NOI18N
111        odebrat.setMnemonic('r');
112        odebrat.setText("Odebrat");
113        odebrat.setToolTipText("Odebere vybraného příjemce");
114        odebrat.addActionListener(new java.awt.event.ActionListener() {
115            public void actionPerformed(java.awt.event.ActionEvent evt) {
116                odebratActionPerformed(evt);
117            }
118        });
119
120        ulozit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/frantovo/superPostak/obrazky/ulozit.png"))); // NOI18N
121        ulozit.setToolTipText("Uložit seznam příjemců do souboru.");
122        ulozit.addActionListener(new java.awt.event.ActionListener() {
123            public void actionPerformed(java.awt.event.ActionEvent evt) {
124                ulozitActionPerformed(evt);
125            }
126        });
127
128        otevrit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/frantovo/superPostak/obrazky/otevrit.png"))); // NOI18N
129        otevrit.setToolTipText("<html>Přidat příjemce ze souboru.<br/>Na každém řádku se očekává jedna adresa.</html>");
130        otevrit.addActionListener(new java.awt.event.ActionListener() {
131            public void actionPerformed(java.awt.event.ActionEvent evt) {
132                otevritActionPerformed(evt);
133            }
134        });
135
136        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
137        this.setLayout(layout);
138        layout.setHorizontalGroup(
139            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
140            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
141                .addContainerGap(97, Short.MAX_VALUE)
142                .addComponent(otevrit)
143                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
144                .addComponent(ulozit)
145                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
146                .addComponent(odebrat)
147                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
148                .addComponent(pridat)
149                .addContainerGap())
150            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
151        );
152        layout.setVerticalGroup(
153            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
154            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
155                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
156                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
157                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
158                    .addComponent(pridat)
159                    .addComponent(odebrat)
160                    .addComponent(ulozit)
161                    .addComponent(otevrit))
162                .addContainerGap())
163        );
164    }// </editor-fold>//GEN-END:initComponents
165    private void pridatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pridatActionPerformed
166        data.pridejRadek();
167    }//GEN-LAST:event_pridatActionPerformed
168
169    private void odebratActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_odebratActionPerformed
170        int radkaV = tabulka.getSelectedRow();
171        int radka = ((TableSorterModel) tabulka.getModel()).modelIndex(radkaV);
172        if (radka > -1 && radka < data.getRowCount()) {
173            data.odeberRadek(radka);
174        }
175    }//GEN-LAST:event_odebratActionPerformed
176
177    private void ulozitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ulozitActionPerformed
178        JFileChooser dialog = new JFileChooser();
179        dialog.setMultiSelectionEnabled(false);
180        dialog.setDialogTitle("Uložit seznam do souboru");
181        int vysledek = dialog.showSaveDialog(this);
182        if (vysledek == JFileChooser.APPROVE_OPTION) {
183            File soubor = dialog.getSelectedFile();
184            try {
185                setCursor(new Cursor(Cursor.WAIT_CURSOR));
186                OutputStreamWriter zapisovac = new FileWriter(soubor);
187                int pocetDobrych = 0;
188                int pocetPreskocenych = 0;
189
190                for (InternetAddressKomu adresa : data.data) {
191                    /** TODO: různé formátování, případně jména */
192                    if (Postak.zkontrolujAdresu(adresa.getAddress())) {
193                        zapisovac.write(adresa.getAddress() + "\n");
194                        pocetDobrych++;
195                    } else {
196                        pocetPreskocenych++;
197                    }
198                }
199
200                zapisovac.close();
201                String preskocene = "";
202                if (pocetPreskocenych > 0) {
203                    preskocene = "\nPočet přeskočených: " + pocetPreskocenych + "\n(Přeskočené neodpovídaly regulárnímu výrazu.)";
204
205                }
206                SuperPostak.zobrazInformacniDialog(this, "Uložení seznamu", "Adresy příjemců byly úspěšně uloženy do souboru:\n" + soubor.getAbsolutePath() + "\nPočet uložených adres: " + pocetDobrych + preskocene, true);
207            } catch (Exception e) {
208                SuperPostak.zobrazChybovyDialog(this, "Uložení seznamu selhalo", "Adresy se nepodařilo uložit do souboru.", null, e, Level.WARNING, false);
209            } finally {
210                setCursor(Cursor.getDefaultCursor());
211            }
212        }
213    }//GEN-LAST:event_ulozitActionPerformed
214
215    private void otevritActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_otevritActionPerformed
216        JFileChooser dialog = new JFileChooser();
217        dialog.setMultiSelectionEnabled(false);
218        dialog.setDialogTitle("Načíst adresy ze souboru");
219        int vysledek = dialog.showOpenDialog(this);
220        if (vysledek == JFileChooser.APPROVE_OPTION) {
221            File soubor = dialog.getSelectedFile();
222            try {
223                setCursor(new Cursor(Cursor.WAIT_CURSOR));
224                BufferedReader ctenar = new BufferedReader(new FileReader(soubor));
225                int pocetDobrych = 0;
226                int pocetPreskocenych = 0;
227                String radka = ctenar.readLine();
228                ArrayList<InternetAddressKomu> adresy = new ArrayList<InternetAddressKomu>();
229
230                while (radka != null) {
231                    if (Postak.zkontrolujAdresu(radka)) {
232                        adresy.add(new InternetAddressKomu(radka, null));
233                        pocetDobrych++;
234
235                    } else {
236                        pocetPreskocenych++;
237                    }
238
239                    radka = ctenar.readLine();
240                }
241
242                setAdresy(adresy);
243                ctenar.close();
244                String preskocene = "";
245                if (pocetPreskocenych > 0) {
246                    preskocene = "\nPočet přeskočených: " + pocetPreskocenych + "\n(Přeskočené neodpovídaly regulárnímu výrazu.)";
247
248                }
249
250                SuperPostak.zobrazInformacniDialog(this, "Načtení adres", "Byl načten seznam adres ze souboru:\n" + soubor.getAbsolutePath() + "\nPočet načtených adres: " + pocetDobrych + preskocene, true);
251            } catch (Exception e) {
252                SuperPostak.zobrazChybovyDialog(this, "Načtení souboru selhalo", "Nepodařilo se načíst soubor s adresami.", null, e, Level.WARNING, false);
253            } finally {
254                setCursor(Cursor.getDefaultCursor());
255            }
256
257        }
258    }//GEN-LAST:event_otevritActionPerformed
259
260    // Variables declaration - do not modify//GEN-BEGIN:variables
261    private javax.swing.JScrollPane jScrollPane1;
262    private javax.swing.JButton odebrat;
263    private javax.swing.JButton otevrit;
264    private javax.swing.JButton pridat;
265    private cz.frantovo.gui.tabulky.JTable tabulka;
266    private javax.swing.JButton ulozit;
267    // End of variables declaration//GEN-END:variables
268    private class ModelTabulky implements TableModel {
269
270        private String[] sloupecky = {"Jméno", "e-mail"};
271        private ArrayList<InternetAddressKomu> data = new ArrayList<InternetAddressKomu>();
272        private HashSet<TableModelListener> posluchace = new HashSet<TableModelListener>();
273
274        public int getRowCount() {
275            return data.size();
276        }
277
278        public int getColumnCount() {
279            return sloupecky.length;
280        }
281
282        public String getColumnName(int n) {
283            return sloupecky[n];
284        }
285
286        public Class<?> getColumnClass(int n) {
287            return String.class;
288        }
289
290        public boolean isCellEditable(int m, int n) {
291            return true;
292        }
293
294        public Object getValueAt(int m, int n) {
295            if (n == 0) {
296                return data.get(m).getPersonal();
297            } else if (n == 1) {
298                return data.get(m).getAddress();
299            } else {
300                return null;
301            }
302        }
303
304        public void setValueAt(Object value, int m, int n) {
305            if (n == 0) {
306                try {
307                    data.get(m).setPersonal(String.valueOf(value.toString()));
308                } catch (Exception ex) {
309                    log.log(Level.SEVERE, "ModelTabulky.setValueAt(" + m + ", " + n + ")", ex);
310                }
311            } else if (n == 1) {
312                data.get(m).setAddress(String.valueOf(value.toString()));
313            }
314        }
315
316        public void addTableModelListener(TableModelListener l) {
317            posluchace.add(l);
318        }
319
320        public void removeTableModelListener(TableModelListener l) {
321            posluchace.remove(l);
322        }
323
324        public void pridejRadek() {
325            data.add(new InternetAddressKomu());
326
327            upozorniPosluchace();
328        }
329
330        public void odeberRadek(int m) {
331            data.remove(m);
332            upozorniPosluchace();
333        }
334
335        private void upozorniPosluchace() {
336            for (TableModelListener p : posluchace) {
337                p.tableChanged(new TableModelEvent(this));
338            }
339        }
340    }
341}
Note: See TracBrowser for help on using the browser.