www.pudn.com > stundenplan.rar > Fariseme.java


/*
 * Fariseme.java
 *
 * Created on 23. Mai 2005, 15:55
 */

/**
 *
 * @author Honger
 */
package stundenplan;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;

public class Fariseme extends JPanel 
                               implements ListSelectionListener {
    private JList list;
    private DefaultListModel listModel;

    private static final String addString = "Add";
    private static final String deleteString = "Delete";
    private static final String upString = "Move up";
    private static final String downString = "Move down";

    private JButton addButton;
    private JButton deleteButton;
    private JButton upButton;
    private JButton downButton;

    private JTextField nameField;
    private JTextArea log;
    static private String newline = "\n";
    
    private String name;
                               
    public Fariseme() {
        super(new BorderLayout());

        //Create and populate the list model.
        listModel = new DefaultListModel();
        listModel.addElement("");
         try{
         Class.forName("org.gjt.mm.mysql.Driver");
         Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","db_pw");
         Statement stmt=c.createStatement(); 
            String query = "select fachrichtungsemester from fariseme";
            ResultSet r = stmt.executeQuery(query); 
            while(r.next()){                          
            listModel.addElement(r.getString(1));
                           }
         }
         catch(Exception e)
         { // log.setText("Fehler: "+e);  
         }
        listModel.addListDataListener(new MyListDataListener());

        //Create the list and put it in a scroll pane.
        list = new JList(listModel);
        list.setSelectionMode(
            ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);

        //Create the list-modifying buttons.
        addButton = new JButton(addString);
        addButton.setActionCommand(addString);
        addButton.addActionListener(new AddButtonListener());

        deleteButton = new JButton(deleteString);
        deleteButton.setActionCommand(deleteString);
        deleteButton.addActionListener(
            new DeleteButtonListener());

        upButton = new JButton("Move up");
        upButton.setToolTipText("Move the currently selected list item higher.");
        upButton.setActionCommand(upString);
        upButton.addActionListener(new UpDownListener());

        downButton = new JButton("Move down");
        downButton.setToolTipText("Move the currently selected list item lower.");
        downButton.setActionCommand(downString);
        downButton.addActionListener(new UpDownListener());

        JPanel upDownPanel = new JPanel(new GridLayout(2, 1));
        upDownPanel.add(upButton);
        upDownPanel.add(downButton);

        //Create the text field for entering new names.
        nameField = new JTextField(15);
        nameField.addActionListener(new AddButtonListener());
        name = listModel.getElementAt(list.getSelectedIndex())
                               .toString();
        nameField.setText(name);
        //Create a control panel, using the default FlowLayout.
        JPanel buttonPane = new JPanel();
        buttonPane.add(nameField);
        buttonPane.add(addButton);
        buttonPane.add(deleteButton);
        buttonPane.add(upDownPanel);

        //Create the log for reporting list data events.
        log = new JTextArea(10, 20);
        JScrollPane logScrollPane = new JScrollPane(log);

        //Create a split pane for the log and the list.
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                        listScrollPane, logScrollPane);
        splitPane.setResizeWeight(0.5);
        
        //Put everything together.
        add(buttonPane, BorderLayout.PAGE_START);
        add(splitPane, BorderLayout.CENTER);
    }

    class MyListDataListener implements ListDataListener {
        public void contentsChanged(ListDataEvent e) {
            log.append("contentsChanged: " + e.getIndex0() +
                       ", " + e.getIndex1() + newline); 
            log.setCaretPosition(log.getDocument().getLength());
        }
        public void intervalAdded(ListDataEvent e) {
            log.append("intervalAdded: " + e.getIndex0() +
                       ", " + e.getIndex1() + newline); 
            log.setCaretPosition(log.getDocument().getLength());
        }
        public void intervalRemoved(ListDataEvent e) {
            log.append("intervalRemoved: " + e.getIndex0() +
                       ", " + e.getIndex1() + newline); 
            log.setCaretPosition(log.getDocument().getLength());
        }
    }

    class DeleteButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            /* 
             * This method can be called only if
             * there's a valid selection,
             * so go ahead and remove whatever's selected.
             */
            ListSelectionModel lsm = list.getSelectionModel();
            int firstSelected = lsm.getMinSelectionIndex();
            int lastSelected = lsm.getMaxSelectionIndex();
            listModel.removeRange(firstSelected, lastSelected);

            int size = listModel.size();

            if (size == 0) {
            //List is empty: disable delete, up, and down buttons.
                deleteButton.setEnabled(false);
                upButton.setEnabled(false);
                downButton.setEnabled(false);

            } else {
            //ausgewälte Daten aus Datenbank schmeißen
                try{
                    Class.forName("org.gjt.mm.mysql.Driver");
                    Connection c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","db_pw");
                    Statement stmt=c.createStatement();
                    String query = "delete from fariseme where fachrichtungsemester ='"+name+"'";
                    int done = stmt.executeUpdate(query);
                    log.setText(String.valueOf(done)+" rows werden geloescht!     ");
                    }
                catch(Exception ex)
                    {  log.setText("Fehler: "+ex);  
                    } 
            //Adjust the selection.
                if (firstSelected == listModel.getSize()) {
                //Removed item in last position.
                    firstSelected--;
                }               
                list.setSelectedIndex(firstSelected);
            }
        }
    }

    /** A listener shared by the text field and add button. */
    class AddButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (nameField.getText().equals("")) {
            //User didn't type in a name...
                Toolkit.getDefaultToolkit().beep();
                return;
            }

            int index = list.getSelectedIndex();
            int size = listModel.getSize();

            //If no selection or if item in last position is selected,
            //add the new one to end of list, and select new one.
            if (index == -1 || (index+1 == size)) {
                try{
                    Class.forName("org.gjt.mm.mysql.Driver");
                    Connection c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","db_pw");
                    Statement stmt=c.createStatement(); 
                    String query = "insert into fariseme (fachrichtungsemester) value ('"+nameField.getText()+"')";
                    int done = stmt.executeUpdate(query);
                    log.setText(String.valueOf(done)+" rows werden gespeichert!     ");
                    listModel.addElement(nameField.getText());
                    list.setSelectedIndex(size);
                    }
                catch(Exception ex)
                    {  log.setText("Fehler: "+ex);  
                    }
            //Otherwise insert the new one after the current selection,
            //and select new one.
            } else {
                try{
                    Class.forName("org.gjt.mm.mysql.Driver");
                    Connection c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","db_pw");
                    Statement stmt=c.createStatement(); 
                    String query = "insert into fariseme (fachrichtungsemester) value ('"+nameField.getText()+"')";
                    int done = stmt.executeUpdate(query);   
                    log.setText(String.valueOf(done)+" rows werden gespeichert!     ");
                    listModel.insertElementAt(nameField.getText(), index+1);
                    list.setSelectedIndex(index+1);
                    }
                catch(Exception ex)
                    {  log.setText("Fehler: "+ex);  
                    }                
            }
        }
    }

    //Listen for clicks on the up and down arrow buttons.
    class UpDownListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only when
            //there's a valid selection,
            //so go ahead and move the list item.
            int moveMe = list.getSelectedIndex();

            if (e.getActionCommand().equals(upString)) {
            //UP ARROW BUTTON
                if (moveMe != 0) {     
                //not already at top
                    swap(moveMe, moveMe-1);
                    list.setSelectedIndex(moveMe-1);
                    list.ensureIndexIsVisible(moveMe-1);
                }
            } else {
            //DOWN ARROW BUTTON
                if (moveMe != listModel.getSize()-1) {
                //not already at bottom
                    swap(moveMe, moveMe+1);
                    list.setSelectedIndex(moveMe+1);
                    list.ensureIndexIsVisible(moveMe+1);
                }
            }
        }
    }

    //Swap two elements in the list.
    private void swap(int a, int b) {
        Object aObject = listModel.getElementAt(a);
        Object bObject = listModel.getElementAt(b);
        listModel.set(a, bObject);
        listModel.set(b, aObject);
    }

    //Listener method for list selection changes.
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {

            if (list.getSelectedIndex() == -1) {
            //No selection: disable delete, up, and down buttons.
                deleteButton.setEnabled(false);
                upButton.setEnabled(false);
                downButton.setEnabled(false);
                nameField.setText("");

            } else if (list.getSelectedIndices().length > 1) {
            //Multiple selection: disable up and down buttons.
                deleteButton.setEnabled(true);
                upButton.setEnabled(false);
                downButton.setEnabled(false);

            } else {
            //Single selection: permit all operations.
                deleteButton.setEnabled(true);
                upButton.setEnabled(true);
                downButton.setEnabled(true);
                name = list.getSelectedValue().toString();
                nameField.setText(name);
            }
        }
    }

    /** 
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    public static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("Fachrichtung&Semesterzahl-Editor");
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new Fariseme();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        
        //Don't let the content pane get too small.
        //(Works if the Java look and feel provides
        //the window decorations.)
        newContentPane.setPreferredSize(
                new Dimension(500,600));

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
}