Universität Augsburg, Institut für Informatik Prof. Dr. Werner Kießling M. Endres, A. Huhn, T. Preisinger Sommersemester 2006 20. Juli. 2006 Lösungsblatt 11 Informatik II Aufgabe 1: Währungsrechner CurrencyConverter.java import import import import import import import java.awt.*; java.awt.event.*; java.io.*; java.net.*; java.text.NumberFormat; java.util.*; javax.swing.*; public class CurrencyConverter extends JFrame implements ActionListener { final Currency EUR = new Currency("EUR", 1.0); JComboBox cbCurrFrom, cbCurrTo; JTextField tfAmountFrom = new JTextField(10); JLabel lblAmountTo = new JLabel(); JButton btnConvert = new JButton("Umrechnen"); NumberFormat formatter = NumberFormat.getInstance(); public CurrencyConverter() { super("Währungsrechner"); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); // Komponenenten erzeugen Currency[] curr = getCurrencies(); cbCurrFrom = new JComboBox(curr); cbCurrTo = new JComboBox(curr); // ActionListener hinzufügen btnConvert.addActionListener(this); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Oberfläche zusammenstellen JComponent cp = (JComponent) getContentPane(); cp.setLayout(new GridBagLayout()); cp.add(tfAmountFrom, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); cp.add(cbCurrFrom, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 5), 0, 0)); cp.add(new JLabel("in"), new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); cp.add(cbCurrTo, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); cp.add(btnConvert, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0)); 1 cp.add(new JLabel("Ergebnis:"), new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); cp.add(lblAmountTo, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0)); pack(); } public static void main(String[] args) { new CurrencyConverter().setVisible(true); } public Currency[] getCurrencies() { // Ohne Stream Currency[] result = new Currency[] { EUR, new Currency("USD", 1.279), new Currency("CHF", 1.5674), new Currency("GBP", 0.6933) }; // Mit Stream Vector<Currency> curr = new Vector<Currency>(); curr.add(EUR); try { URL url = new URL( "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"); URLConnection con = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String line; while ((line = in.readLine()) != null) { StringTokenizer tokens = new StringTokenizer(line, "’"); int count = tokens.countTokens(); // 1. Token: <Cube currency= String first = tokens.nextToken(); if (first.endsWith("<Cube currency=") && count == 5) { // 2. Token: Währungsname String name = tokens.nextToken(); // 3. Token: rate= tokens.nextElement(); // 4. Token: Umrechnungsfaktor double factor = Double.parseDouble(tokens.nextToken()); curr.add(new Currency(name, factor)); } } in.close(); result = new Currency[curr.size()]; curr.copyInto(result); } catch (IOException ioe) {;} return result; } public void actionPerformed(ActionEvent e) { double amount = 0; try { amount = Double.parseDouble(tfAmountFrom.getText().replace(’,’, ’.’)); // Umrechnung immer Quell-Währung zu Euro und dann // Euro zu Zielwährung 2 double toEUR = ((Currency) cbCurrFrom.getSelectedItem()).getToEUR(); double toResult = ((Currency) cbCurrTo.getSelectedItem()).getToEUR(); double result = amount / toEUR * toResult; lblAmountTo.setText(formatter.format(result)); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Keine Zahl!", "Fehler", JOptionPane.ERROR_MESSAGE); } } class Currency { // Währungs-Kürzel final String name; // Umrechnung zu 1,00 EUR double rateEUR; public Currency(String name, double rateEUR) { this.name = name; this.rateEUR = rateEUR; } public String getName() { return name; } public double getToEUR() { return rateEUR; } public String toString() { return name; } } } Aufgabe 2: Datei-Explorer FileExplorer.java import import import import import import import java.awt.*; java.io.File; java.util.*; javax.swing.*; javax.swing.border.EmptyBorder; javax.swing.event.*; javax.swing.tree.*; public class FileExplorer extends JFrame { JTree tree; JTextArea JCheckBox JCheckBox JCheckBox JCheckBox JCheckBox list = new JTextArea(); chFile = new JCheckBox("Datei"); chDir = new JCheckBox("Verzeichnis"); chHidden = new JCheckBox("versteckt"); chReadable = new JCheckBox("lesbar"); chReadOnly = new JCheckBox("schreibgeschützt"); public FileExplorer(File file) { super("File Explorer"); setDefaultCloseOperation(EXIT_ON_CLOSE); tree = new JTree(new DirectoryTreeNode(file)); //tree = new JTree(new DirectoryTreeNode(new File("C:\\"))); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { TreePath path = tree.getSelectionPath(); DirectoryTreeNode selection = (DirectoryTreeNode) path.getLastPathComponent(); 3 if (selection.isLeaf()) list.setText(""); else { // Verzeichnis: enthaltene Dateien in der Liste anzeigen StringBuffer sb = new StringBuffer(); Enumeration<DirectoryTreeNode> elements = selection.children(); while (elements.hasMoreElements()) { sb.append(elements.nextElement().toString()); sb.append(’\n’); } list.setText(sb.toString()); } // CheckBoxen markieren File curFile = selection.getFile(); chHidden.setSelected(curFile.isHidden()); chFile.setSelected(curFile.isFile()); chDir.setSelected(curFile.isDirectory()); chReadOnly.setSelected(curFile.canWrite()); chReadable.setSelected(curFile.canRead()); } }); ButtonGroup bg = new ButtonGroup(); bg.add(chFile); bg.add(chDir); chHidden.setEnabled(false); chReadable.setEnabled(false); chReadOnly.setEnabled(false); chFile.setEnabled(false); chDir.setEnabled(false); list.setEditable(false); JComponent cp = (JComponent) getContentPane(); cp.setBorder(new EmptyBorder(5,5,5,5)); cp.add(new JScrollPane(tree), BorderLayout.LINE_START); JPanel pnlRight = new JPanel(new BorderLayout()); JPanel pnlAttributes = new JPanel(); pnlAttributes.setLayout(new GridLayout(0, 1)); pnlAttributes.add(chHidden); pnlAttributes.add(chReadable); pnlAttributes.add(chReadOnly); pnlAttributes.add(new JLabel(" Typ: ")); pnlAttributes.add(chFile); pnlAttributes.add(chDir); pnlAttributes.add(new JLabel(" Inhalt: ")); pnlRight.add(pnlAttributes, BorderLayout.PAGE_START); pnlRight.add(new JScrollPane(list), BorderLayout.CENTER); cp.setLayout(new BorderLayout()); cp.add(new JScrollPane(tree), BorderLayout.LINE_START); cp.add(pnlRight, BorderLayout.CENTER); pack(); } public static void main(String[] args) { new FileExplorer(new File(".")).setVisible(true); } 4 class DirectoryTreeNode implements TreeNode { File file; public DirectoryTreeNode(File file) { this.file = file; } public File getFile() { return file; } // Enthaltene Datei an bestimmter Stelle zurückgeben public DirectoryTreeNode getChildAt(int childIndex) { return new DirectoryTreeNode(file.listFiles()[childIndex]); } // Anzahl enthaltener Dateien public int getChildCount() { File[] children = file.listFiles(); return children != null ? children.length : 0; } // Übergeordnetes Verzeichnis zurückliefern public DirectoryTreeNode getParent() { return new DirectoryTreeNode(file.getParentFile()); } public int getIndex(TreeNode node) { // Knoten suchen if (!(node instanceof DirectoryTreeNode)) { // falscher Typ des Knotens return -1; } File obj = ((DirectoryTreeNode) node).getFile(); for (int i = 0; i < file.listFiles().length; i++) { if (file.equals(obj)) return i; } return -1; } // Verzeichnisse können "Kinder" haben public boolean getAllowsChildren() { return file.isDirectory(); } // Eine einfache Datei ist ein Blatt public boolean isLeaf() { return file.isFile(); } public Enumeration<DirectoryTreeNode> children() { Vector<DirectoryTreeNode> dir = new Vector<DirectoryTreeNode>(); for (File elem : file.listFiles()) { dir.add(new DirectoryTreeNode(elem)); } return dir.elements(); } public String toString() { return file.getName(); } } } 5