HTML-Formular in Swing-Benutzerinterface

Aus Byte-Welt Wiki
Wechseln zu: Navigation, Suche

Das HTML Formular ist eine interessante Alternative zu einem reinen Swing Formular.

FormularDemo.jpg

Die Klasse "HTMLFormular" musst du nicht bis in alle Einzelheiten verstehen. Du kannst sie unverändert übernehmen. Ihr Zweck ist lediglich, die Klasse JEditorPane so zu erweitern, dass sie ein Html Script verstehen und verarbeiten kann.

In der Klasse "FormularDemo" wird das "HTMLFormular" über einen "PropertyChangeListener" überwacht. Die Methode "propertyChange" wird aufgerufen, wenn der "submit" Button im Formular betätigt wird.

Die Klasse "FormData" enthält die eigentlichen Daten des Formulars, sowie Methoden zum Speichern und Laden der Daten (save/load). Die Demo speichert die Daten nach jeder Änderung und ladet sie wieder nach einen Neustart.

Zur eigentlichen "Html" Sprache findest du sicher mehrere Tutorials im Netz. Zum Beispiel hier: http://www.htmlcodetutorial.com/

/*
 * FormularDemo.java
 *
 * Das HTML Formular ist eine interessante Alternative zu einem reinen Swing Formular.
 */
import java.beans.*;
import java.util.*;
import javax.swing.*;
 
public class FormularDemo extends JFrame {
 
    private String dataPath = "data.txt";
    private String encoding = "UTF-8";
    private HTMLFormular formular;
    private final static String ID = "Id";
    private final static String VORNAME = "Vorname";
    private final static String NACHNAME = "Nachname";
    private final static String GESCHLECHT = "Geschlecht";
    private final static String BEMERKUNG = "Bemerkung";
    private FormData data;
    private String form;
 
    public FormularDemo() {
        super("Html Formular");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        formular = new HTMLFormular(encoding);
        FormData dataLoaded = (FormData) FormData.load(dataPath);
        if (dataLoaded == null) {
            data = new FormData();
        } else {
            data = dataLoaded;
        }
        form = "<form>"
                + "    <table>";
        if (data.isIdLocked()) {
            form += "        <tr>"
                    + "            <td>"
                    + "            </td>"
                    + "            <td>"
                    + "                Id = " + data.getId()
                    + "            </td>"
                    + "        </tr>";
        } else {
            form += "        <tr>"
                    + "            <td>"
                    + "                " + ID + ":"
                    + "            </td>"
                    + "            <td>"
                    + "                <input name='" + ID + "' type='text' value='" + data.getId() + "'>"
                    + "            </td>"
                    + "        </tr>";
        }
        form += "        <tr>"
                + "            <td>"
                + "                " + VORNAME + ":"
                + "            </td>"
                + "            <td>"
                + "                <input name='" + VORNAME + "' type='text' value='" + data.getVorname() + "'>"
                + "            </td>"
                + "        </tr>";
        form += "        <tr>"
                + "            <td>" + NACHNAME + ":"
                + "            </td>"
                + "            <td>"
                + "                <input name='" + NACHNAME + "' type='text' value='" + data.getNachname() + "'>"
                + "            </td>"
                + "        </tr>";
        form += "        <tr>"
                + "            <td>"
                + "                " + GESCHLECHT + ":"
                + "            </td>"
                + "            <td>"
                + "                <select name='" + GESCHLECHT + "'>"
                + "                    <option" + (data.getGeschlecht().trim().equals("Männlich") ? " selected" : "") + ">"
                + "                        Männlich"
                + "                    </option>"
                + "                    <option" + (data.getGeschlecht().trim().equals("Weiblich") ? " selected" : "") + ">"
                + "                        Weiblich"
                + "                    </option>"
                + "                </select>"
                + "            </td>"
                + "        </tr>";
        form += "        <tr>"
                + "            <td>"
                + "                " + BEMERKUNG + ":"
                + "            </td>"
                + "            <td>"
                + "                <textarea name='" + BEMERKUNG + "' rows=5 cols=60 >" + data.getBemerkung()
                + "                </textarea>"
                + "            </td>"
                + "        </tr>";
        form += "        <tr>"
                + "            <td>"
                + "            </td>"
                + "            <td>"
                + "                <hr>"
                + "            </td>"
                + "        </tr>";
        form += "        <tr>"
                + "            <td>"
                + "            </td>"
                + "            <td>"
                + "                <input type='submit'>"
                + "            </td>"
                + "        </tr>";
        form += "    </table>"
                + "</form>";
        formular.setText(form);
        formular.addPropertyChangeListener("data", new PropertyChangeListener() {
 
            public void propertyChange(final PropertyChangeEvent evt) {
                Map<String, String> result = formular.getResult();
                if (!data.isIdLocked()) {
                    data.setId(result.get(ID));
                    data.setIdLocked(true);
                }
                data.setVorname(result.get(VORNAME));
                data.setNachname(result.get(NACHNAME));
                data.setGeschlecht(result.get(GESCHLECHT));
                data.setBemerkung(result.get(BEMERKUNG));
                FormData.save(data, dataPath);
                showData();
            }
        });
        getContentPane().add(new JScrollPane(formular));
        setSize(700, 320);
        setLocationRelativeTo(null);
    }
 
    private void showData() {
        JOptionPane.showMessageDialog(null,
                ID + ": " + data.getId() + "\n"
                + VORNAME + ": " + data.getVorname() + "\n"
                + NACHNAME + ": " + data.getNachname() + "\n"
                + GESCHLECHT + ": " + data.getGeschlecht() + "\n"
                + BEMERKUNG + ": " + data.getBemerkung());
    }
 
    public static void main(final String args[]) {
        Runnable gui = new Runnable() {
 
            public void run() {
                new FormularDemo().setVisible(true);
            }
        };
        SwingUtilities.invokeLater(gui);
    }
}
/*
 * FormData.java
 */
import java.beans.*;
import java.io.*;
import java.util.logging.*;
 
public class FormData {
 
    private String id = "";
    private boolean idLocked;
    private String vorname = "";
    private String nachname = "";
    private String geschlecht = "";
    private String bemerkung = "";
 
    public FormData() {
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(final String id) {
        this.id = id;
    }
 
    public boolean isIdLocked() {
        return idLocked;
    }
 
    public void setIdLocked(final boolean idLocked) {
        this.idLocked = idLocked;
    }
 
    public String getBemerkung() {
        return bemerkung;
    }
 
    public void setBemerkung(final String bemerkung) {
        this.bemerkung = bemerkung;
    }
 
    public String getGeschlecht() {
        return geschlecht;
    }
 
    public void setGeschlecht(final String geschlecht) {
        this.geschlecht = geschlecht;
    }
 
    public String getNachname() {
        return nachname;
    }
 
    public void setNachname(final String nachname) {
        this.nachname = nachname;
    }
 
    public String getVorname() {
        return vorname;
    }
 
    public void setVorname(final String vorname) {
        this.vorname = vorname;
    }
 
    public static void save(final Object obj, final String filename) {
        try {
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(filename)));
            encoder.writeObject(obj);
            encoder.close();
        } catch (final FileNotFoundException ex) {
            Logger.getLogger(FormData.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    public static Object load(final String filename) {
        Object obj = null;
        try {
            XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
            obj = decoder.readObject();
            decoder.close();
        } catch (final FileNotFoundException ex) {
        }
        return obj;
    }
 
    @Override
    @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject")
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FormData other = (FormData) obj;
        if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
            return false;
        }
        return true;
    }
 
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 71 * hash + (this.id != null ? this.id.hashCode() : 0);
        return hash;
    }
}
/*
 * HTMLFormular.java
 */
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
 
public class HTMLFormular extends JEditorPane {
 
    private String encoding;
    private Map<String, String> resultMap;
 
    public HTMLFormular() {
        this("UTF-8");
    }
 
    public HTMLFormular(final String encoding) {
        this.encoding = encoding;
        setEditable(false);
        setEditorKit(new HTMLEditorKit() {
 
            @Override
            public ViewFactory getViewFactory() {
                return new HTMLEditorKit.HTMLFactory() {
 
                    @Override
                    public View create(final Element elem) {
                        Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
                        if (o instanceof HTML.Tag) {
                            HTML.Tag kind = (HTML.Tag) o;
                            if (kind == HTML.Tag.INPUT) {
                                return new FormView(elem) {
 
                                    @Override
                                    protected void submitData(final String data) {
                                        try {
                                            setData(data);
                                        } catch (UnsupportedEncodingException ex) {
                                            Logger.getLogger(HTMLFormular.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                    }
                                };
                            }
                        }
                        return super.create(elem);
                    }
                };
            }
        });
    }
 
    private void setData(final String data) throws UnsupportedEncodingException {
        resultMap = new HashMap<String, String>(16);
        StringTokenizer st = new StringTokenizer(data, "&");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            String key = null;
            String value = null;
            key = URLDecoder.decode(token.substring(0, token.indexOf('=')), encoding);
            value = URLDecoder.decode(token.substring(token.indexOf('=') + 1, token.length()), encoding);
            resultMap.put(key, value);
        }
        firePropertyChange("data", null, data);
    }
 
    @SuppressWarnings("ReturnOfCollectionOrArrayField")
    public Map<String, String> getResult() {
        return resultMap;
    }
}