Zum Inhalt

Programmieren II

Herzlich willkommen zur Programmieren II-Veranstaltung! Wir haben in Programmieren I unter Verwendung der Programmiersprache Java bereits wesentliche Konzepte kennengelernt, die für das Verständnis moderner Programmierens notwendig sind. Diese Kenntnisse wollen wir nun erweitern und vertiefen. Wir werden Git kennenlernen, Exceptions, Wrapper-Klassen, Interfaces und Collections. Wir beschäftigen uns intensiv mit dem Testen von Programmen und erzeugen uns eigene Nutzeroberflächen. Hier einige Tipps, damit Sie die Veranstaltung erfolgreich durchführen und Sie dabei auch Spaß haben:

  1. Lösen Sie alle Übungsaufgaben selbständig! Es ist kein Problem, wenn Sie für das Bewältigen der Übungen etwas länger benötigen. Sollten Sie es gar nicht alleine schaffen, ist das auch kein Problem. Wichtig ist dann, dass Sie sich die Lösung anschauen und es erneut selbständig versuchen. Hören Sie nicht auf, bis Sie es geschafft haben!
  2. Sie können die Hausaufgaben zu zweit lösen. Achten Sie aber darauf, dass Sie Ihre gemeinsame Lösung vollständig verstanden haben und dass Sie sie danach auch alleine erstellen können. Sie können beim Lösen der Hausaufgaben beliebig kreativ sein! Die Aufgabenstellung gibt Ihnen Anhaltspunkte für eine eventuelle Lösung. Sie können es aber auch ganz anders machen!
  3. Die Klausurvorbereitung beginnt mit Beginn der Veranstaltung. Es ist nicht möglich, die Klausur am Ende des Semesters zu bestehen, wenn Sie nicht das ganze Semester über intensiv programmieren. Die Übungsaufgaben sind "kleine" Aufgaben, um das in der Vorlesung vermittelte Wissen direkt anzuwenden. Für die Lösung der Hausaufgaben ist bereits ein gewisses Abstraktionsniveau erforderlich, um zu erkennen, dass das in der Vorlesung vermittelte Wissen dafür ausreichend ist.
  4. Programmieren lernt man nur durch Programmieren. Sie müssen es tun. Das Lesen von Büchern oder das "Anschauen" von Code genügt nicht. Eine Sprache lernt man auch nur durch Sprechen. Sie müssen programmieren, programmieren, programmieren...
  5. Lassen Sie sich durch Fehler nicht verunsichern, sondern analysieren Sie Ihre Fehler. Bis zur Klausur sollten Sie alle Fehler einmal gemacht haben. Wenn Sie sich überlegen, warum das jeweils ein Fehler war, dann werden Sie diesen Fehler nicht wiederholen und haben durch die Reflektion eine Menge gelernt. Fehler zu machen (und darüber zu reflektieren) gehört zu den besten Lernmethoden des Programmierens.
  6. Haben Sie Spaß! Je mehr Sie das Programmieren lernen, je mehr Spaß werden Sie haben. Wir versuchen, dass Sie das ganze Semester über Spaß am Programmieren haben werden. Sollte es Ihnen zwischendurch keinen Spaß mehr machen, geben Sie mir sofort Bescheid!

Viel Erfolg! Und viel Spaß!

Organisatorisches

Der Plan zur Durchführung der Veranstaltung ist derzeit wie folgt:

  • Themen werden ausführlich in diesem Skript beschrieben und in den Vorlesungen eingeführt und verdeutlicht.
  • Solange Präsenzveranstaltungen möglich sind, werden wir die Veranstaltungen auch in Präsenz durchführen. Es werden keine Videos erstellt.
  • Das Skript wird für die jeweils kommende Woche freitags hochgeladen.
  • Mit dem Skript wird sowohl die Übung für die kommende Woche als auch die neue Aufgabe hochgeladen.
  • Die Übung (und die vergangene Aufgabe) werden dienstags (14-15.30 Uhr) bzw. donnerstags (14-15.30 Uhr) besprochen (Sie können frei wählen, welche der beiden Übungen Sie wählen).
  • Die Veranstaltung wird durch ein Tutorium unterstützt. Der Termin für das Tutorium wird noch bekanntgegeben.
  • Sollten Sie Wünsche haben, diesen Plan zu ändern, kommen Sie gerne auf mich zu

Zur erfolgreichen Durchführung der Veranstaltung sollten Sie die Aufgaben lösen und zu den jeweiligen Fristen auf Moodle hochladen. Zusätzlich sollten Sie für mindestens 5 fremde Lösungen Code-reviews erstellen. Es werden insgesamt wahrscheinlich 10 Aufgaben sein, die Sie selbständig lösen und hochladen. Sie können die Aufgaben auch zu zweit lösen. Sollte Ihre Lösung der Lösung entsprechen, die im Tutorium erarbeitet wurde, brauchen Sie diese Lösung nicht hochzuladen. Am Ende des Semesters schreiben wir eine Klausur (am Rechner). Diese Klausur wird bewertet und entspricht der Note für das gesamte "Programmieren"-Modul.

Unter Aufgaben sind die Aufgaben beschrieben, die Sie in jeder Woche ausführen sollen. Damit Sie dies erfolgreich erledigen können, ist jeweils angegeben, welche Themen Sie dafür durcharbeiten müssen. Das Durcharbeiten der jeweiligen Themen entspricht jeweils einer Vorlesung. Diese wird also selbständig durchgeführt.

Daneben gibt es jede Woche (zu jedem Thema) Übungen, die wir in den Übungszeiten besprechen. Diese dienen der Anwendung und der Festigung der erlangten Kenntnisse. Die Übungen sind kleine Aufgaben, an denen Sie das neue Wissen anwenden sollen. Die Übungen dienen der Befähigung, die (größeren) Aufgaben lösen zu können.

Für die Kommunikation untereinander verwenden wir Slack. Dort können Sie alle inhaltlichen und organisatorischen Fragen stellen. Ich fände es gut, wenn ich dort möglichst wenig Fragen - zumindest die inhaltlichen - beantworten müsste, sondern eine Art internes Diskussionsforum entsteht. Es ist sehr gewünscht, dort Fragen zu stellen und noch mehr gewünscht, diese von Ihnen dort beantwortet zu sehen. Damit wäre allen geholfen und ich kann besser erkennen, wo noch Nachhol- bzw. Erläuterungsbedarf bei den meisten besteht. Außerdem lernen Sie beim Beantworten der Fragen nochmals deutlich mehr. Das wäre super, wenn das klappt!

Grober Inhalt (kann sich noch ändern)

Wir beschäftigen uns dieses Semester mit weiteren Konzepten der Programmierung. Wir lernen weitere Datenstrukturen kennen (Collections), werden lernen, mit Exceptions umzugehen und implementieren Tests. Wir beschäftigen uns mit Grafischen Nutzeroberflächen (GUIs) und lernen, Nutzereignisse zu behandeln.

Nachfolgend der vorläufige Wochenplan (wird eventuell angepasst).

Woche Themen (Vorlesung) Übung Aufgabe Abgabe Aufgabe bis
1. 04.-08.04.2022 Organisatorisches, Wiederholung, Einstieg -  - -
1. 11.-15.04.2022 Wrapper-Klassen (boxing und unboxing) Übung 1 Aufgabe 1 25.04.2022
2. 18.-22.04.2022 Exceptions I Übung 2 Aufgabe 2 02.05.2022
3. 25.-29.04.2022 Aufgabe 2 besprochen Übung 3 Aufgabe 3 16.05.2022
4. 02.-06.05.2022 Exceptions II Übung 4 Aufgabe 4 23.05.2022
5. 09.-13.05.2022 Collections (List und Set) Übung 5 Aufgabe 5 30.05.2022
6. 16.-20.05.2022 Collections (Map) Übung 6  - -
7. 23.-27.05.2022 Abstrakte Klassen Übung 7 Aufgabe 6 06.06.2022
8. 30.-03.06.2022 Interfaces Übung 8 - 20.06.2022
9. 06.-10.06.2022 GUI Einführung - Aufgabe 7 27.06.2022
10. 13.-17.06.2022 JUnit und
Layout-Manager
Übung 10 Übung 9 Aufgabe 8 04.07.2022
12. 20.-24.06.2022 GUI Ereignisse Übung 11 Aufgabe 9 entfällt
13. 27.-01.07.2022 ActionListener Übung 12  - -
14. 04.-08.07.2022 Mausereignisse Übung 13  - -
15. 11.-15.07.2022 Klausurvorbereitung
keine Veranstaltungen!!
1 2 3  - -
20.07.2022 14:00 Uhr Klausur 1.PZ Labore 6. Etage C-Gebäude - -
26.09.2022 14:00 Uhr Klausur 2.PZ Labore 6. Etage C-Gebäude - -

Inhalte

04.-08.04.2022 - Einführung und Organisatorisches + Wiederholung
Quellcode aus der Vorlesung
package vorlesungen.vorlesung0406;

import java.util.Arrays;

import javax.swing.JOptionPane;

public class Vorlesung0406 {

    public static void print()
    {
        System.out.println("Endlich wieder Programmieren!");
    }

    public static void input()
    {
        int auswahl = JOptionPane.showConfirmDialog(null, "Weiter machen?", "Fenstertitel", JOptionPane.YES_NO_OPTION);

        if(auswahl == JOptionPane.YES_OPTION)
        {
            // YES geklickt
        }
        else if(auswahl == JOptionPane.NO_OPTION)
        {
            // No geklickt
        }

        String eingabe = JOptionPane.showInputDialog("Geben Sie eine Zahl ein : ");
        System.out.println("Ihre Eingabe war " + eingabe);
    }

    public static void testArrays()
    {
        int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        String s = Arrays.toString(a);
        System.out.println(s);
        int[] b = { 11, 12, 3, 14, 5, 6, 17, 8, 19 };

        for (int index = 0; index < b.length; index++) 
        {
            System.out.print(b[index] + " ");
            // b[index] = 5;
        }
        System.out.println();

        for(int element : b)
        {
            System.out.print(element + " ");
            element = 5;
        }
        System.out.println();

        Arrays.sort(b);
        System.out.println(Arrays.toString(b));


    }

    public static void main(String[] args) {
        Vorlesung0406.print();
        testArrays();
        input();
    }

}
11.-15.04.2022 - Wrapper-Klassen
Quellcode aus der Vorlesung
package vorlesungen.vorlesung1306;

import javax.swing.JOptionPane;

public class Vorlesung1304 
{

    static int divide(int nr1, int nr2)
    {
        return nr1 / nr2;
    }

    public static void main(String[] args) 
    {
        // Wrapper-Klassen 

        String eingabe = JOptionPane.showInputDialog("Geben Sie eine Zahl ein: ");

        // 1. Konstruktoren --> deprecated!!! nicht verwenden
        Integer i1 = new Integer(100); // int-Wert 
        Integer i2 = new Integer("100"); // Zahl als String

        Character c1 = new Character('a'); 
        // Character c2 = new Character("a");

        Integer max = Integer.MAX_VALUE; 
        System.out.println(max);

        // 2. valueOf() 
        Integer i3 = Integer.valueOf(100); 
        Integer i4 = Integer.valueOf("100");

        // 3. Auto-Boxing 
        Integer i5 = 100; 
        System.out.println(i5);

        Integer i6 = 1000; 
        Integer i7 = 1000; 
        Integer i8 = 1001;
        System.out.println(i6 == i7); 
        System.out.println(i8 >= i7);

        Integer i9 = Integer.valueOf("1000"); 
        int i10 = i9.intValue();

        int i11 = Integer.valueOf("1000");

        int nrInput = Integer.valueOf(eingabe); 
        System.out.println("Sie haben " + nrInput + " eingegeben");


        // Exceptions

        int nr1 = 7; 
        int nr2 = 0;
        try {
            int result = divide(nr1, nr2);
            System.out.printf("%4d / %4d = %3d %n", nr1, nr2, result);
        }
        catch(ArithmeticException e) 
        {
            System.out.println("Division durch 0 ist nicht definiert");
            // e.printStackTrace();
        }

        System.out.println("Programmende");
    }

}
18.-22.04.2022 - Exceptions I
Quellcode aus der Vorlesung - Klasse Vorlesung0420.java
package vorlesungen.vorlesung0420;

import javax.swing.JOptionPane;

public class Vorlesung0420 
{
    public static int divide(int a, int b)
    {
            return (a/b);
    }

    public static int getAtIndex(int[] arr, int index)
    {
            return arr[index];
    }

    public static void main(String[] args) 
    {
        int nr1 = 7;
        int nr2 = 0;

        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int index = 6;

        try 
        {
            int result = divide(nr1, nr2);
            System.out.printf("%d / %d = %d %n", nr1, nr2, result);
            int wert = getAtIndex(arr, index);
            System.out.println("Wert : " + wert);
        } 
        catch (ArithmeticException e) 
        {
            System.out.println("Divison durch 0 nicht definiert");
        }
        catch (ArrayIndexOutOfBoundsException e) 
        {
            System.out.println("Ungueltiger Index");
        }
        catch (Exception e) {

        }

        boolean eingabeOk = true;

        while(!eingabeOk)
        {
            String eingabe = JOptionPane.showInputDialog("Geben Sie eine Zahl ein :");

            try {
                int zahl = Integer.parseInt(eingabe);
                System.out.println("Ihre Zahl " + zahl);
                eingabeOk = true;
            } 
            catch (NumberFormatException e) 
            {
                System.out.println("Eingabe war keine Zahl!");
            }

        }

            try {
                Triangle t1 = new Triangle(3,4,0);
                t1.print();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());;
            }



        System.out.println("Programmende");

    }

}
Quellcode aus der Vorlesung - Klasse Triangle.java
package vorlesungen.vorlesung0427;

public class Triangle
{
    private int a;
    private int b;
    private int c;

    public Triangle(int a, int b, int c) throws IllegalArgumentException
    {
        if(a <= 0 ||b <= 0 ||c <= 0 )
        {
            throw new IllegalArgumentException("side lengths must be positive integers");
        }
        else if(a > (b+c) ||b > (a+c) ||c > (a+b) )
        {
            throw new IllegalArgumentException("no triangle ");
        }
        else
        {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    }

    public int circumference()
    {
        return this.a + this.b + this.c;
    }

    public double area()
    {
        double area = 0.0;
        double s = 0.5 * (this.a+this.b+this.c);
        area = Math.sqrt(s * (s-this.a) * (s-this.b) * (s-this.c));
        return area;
    }

    public boolean equilateral()
    {
        return this.a==this.b && this.b==this.c;
    }

    public boolean isosceles()
    {
        return this.a==this.b || this.b==this.c || this.c==this.a;
    }

    public void print()
    {
        System.out.println("Seiten          : a=" + this.a + ", b=" + this.b + ", c=" + this.c);
        System.out.println("Umfang          : " + this.circumference());
        System.out.println("Flaecheninhalt  : " + this.area());
        if(this.equilateral())
        {
            System.out.println("Das Dreieck ist gleichseitig.");
        }
        else
        {
            if(this.isosceles())
            {
                System.out.println("Das Dreieck ist gleichschenklig.");
            }
            else
            {
                System.out.println("Das Dreieck ist unregelmaessig.");
            }
        }
        if(this.isRightAngled())
        {
            System.out.println("Das Dreieck ist rechtwinklig.");
        }
        else
        {
            System.out.println("Das Dreieck ist nicht rechtwinklig.");
        }
        System.out.println();
    }

    public boolean sameCircumference(Triangle t)
    {
        return this.circumference()==t.circumference();
    }

    public boolean sidesAreEqual(Triangle t)
    {
        return (this.a==t.a && this.b==t.b && this.c==t.c) ||
                (this.a==t.b && this.b==t.c && this.c==t.a) ||
                (this.a==t.c && this.b==t.a && this.c==t.b);
    }

    public boolean isRightAngled()
    {
        return ((this.a*this.a == (this.b*this.b + this.c*this.c)) ||
                (this.b*this.b == (this.a*this.a + this.c*this.c)) ||
                (this.c*this.c == (this.b*this.b + this.a*this.a)));
    }

    public boolean isSmaller(Triangle t)
    {
        return this.area() < t.area();
    }

    public boolean isBigger(Triangle t)
    {
        return this.area() > t.area();
    }
}
25.-29.04.2022 - Exceptions II
02.-06.05.2022 - Aufzählungstypen und mehrdimensionale Arrays
Quellcode aus der Vorlesung - Klasse Vorlesung0504.java
package vorlesungen.vorlesung0504;

public class Vorlesung0504 {

    public static void test() throws IllegalSideLengthException, IllegalTriangleException
    {
        Triangle t1;


        t1 = new Triangle(3,4,8);
        t1.print();
    }

    public static void main(String[] args) 
    {

        try {
            test();
        } catch (IllegalSideLengthException | IllegalTriangleException e) {

            System.out.println(e.getMessage());
        }


        System.out.println("Programmende");


        Tag day = Tag.MONTAG;

        if(day == Tag.DIENSTAG)
        {

        }

        int[][] zda = new int[3][4];
        for(int row = 0; row < zda.length; row++)
        {
            for(int col = 0; col < zda[row].length; col++)
            {
                zda[row][col] = row * col;
            }
        }

        System.out.println("Laenge " + zda.length);

        for(int row = 0; row < zda.length; row++)
        {
            for(int col = 0; col < zda[row].length; col++)
            {
                System.out.printf("[%d][%d] ", row, col);
            }
            System.out.println();
        }
    }

}
Quellcode aus der Vorlesung - Klasse IllegalTriangleException.java
package vorlesungen.vorlesung0504;

public class IllegalTriangleException extends RuntimeException
{
    public IllegalTriangleException(String s)
    {
        super(s);
    }

    public IllegalTriangleException()
    {
        super("Each side has to be smaller than the sum of the other sides.");
    }
}
Quellcode aus der Vorlesung - Klasse IllegalSideLengthException.java
package vorlesungen.vorlesung0504;

public class IllegalSideLengthException extends RuntimeException
{
    public IllegalSideLengthException(String s)
    {
        super(s);
    }

    public IllegalSideLengthException()
    {
        super("Each side has to be greater than zero!");
    }
}
Quellcode aus der Vorlesung - Klasse Triangle.java
package vorlesungen.vorlesung00504;

public class Triangle
{
        private int a;
        private int b;
        private int c;

        public Triangle(int a, int b, int c) throws IllegalSideLengthException, IllegalTriangleException
        {
            if(a <= 0 ||b <= 0 ||c <= 0 )
            {
                throw new IllegalSideLengthException();
            }
            else if(a > (b+c) ||b > (a+c) ||c > (a+b) )
            {
                throw new IllegalTriangleException();
            }
            else
            {
                this.a = a;
                this.b = b;
                this.c = c;
            }
        }
}
Quellcode aus der Vorlesung - enum Tag.java
package vorlesungen.vorlesung0504;

public enum Tag {
    MONTAG, DIENSTAG, MITTWOCH, DONNERSTAG, FREITAG, SAMSTAG, SONNTAG
}
Quellcode aus der Vorlesung - enum Player.java
package vorlesungen.vorlesung0504;

public enum Player 
{
    RED, BLACK
}
09.-13.05.2022 - Collections Lists und Sets
Quellcode aus der Vorlesung - Klasse Vorlesung0511.java
package vorlesungen.vorlesung0511;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class Vorlesung0511 
{

    public static void main(String[] args) 
    {
        List<Integer> list1 = new ArrayList<>();
        List<String> list2 = new LinkedList<>();

        Set<String> set1 = new HashSet<>();
        Set<Integer> set2 = new TreeSet<>();

        String str1 = "erster";
        String str2 = "zweiter";
        String str3 = "dritter";
        String str4 = "zweiter";

        System.out.printf("%n%n----------- Elemente zu set1 hinzufuegen --------------%n%n");

        System.out.println("empty ? " + set1.isEmpty());
        System.out.println("hinzugefuegt ? " + set1.add(str1));
        System.out.println("hinzugefuegt ? " + set1.add(str2));
        System.out.println("hinzugefuegt ? " + set1.add(str3));
        System.out.println("hinzugefuegt ? " + set1.add(str4));
        System.out.println("empty ? " + set1.isEmpty());

        System.out.println("erster in set1 ? " + set1.contains("erster"));

        System.out.println("Laenge von set1 : " + set1.size());

        // set1.add(new Random());  // Fehler wg. Set<String>

        System.out.println("Laenge von set1 : " + set1.size());


        set2.add(3);        // hier Auto-Boxing!

        set1.add(Integer.toString(1));

        System.out.printf("%n%n----------- alle Elemente aus set1 ausgeben --------------%n%n");
        for(String element : set1)
        {
            System.out.println(element);
        }

        // set1.remove("dritter");      // wuerde gehen


        System.out.printf("%n%n----------- Iterator von set1 --------------%n%n");

        Iterator<String> it = set1.iterator();
        while(it.hasNext())
        {
            String next = it.next();
            if(next.equals("dritter"))
            {
                it.remove();        // loescht aus set1
            }
            System.out.println(next);
        }

        System.out.printf("%n%n----------- nochmal alle Elemente aus set1 ausgeben --------------%n%n");

        for(String element : set1)
        {
            System.out.println(element);
        }

        System.out.printf("%n%n----------- list1 --------------%n%n");

        list1.add(3);   // Integer 3 hinzufuegen - Auto-Boxing!
        list1.add(5);   // Integer 5 hinzufuegen - Auto-Boxing!

        for(Integer element : list1)
        {
            System.out.println(element);
        }

        System.out.println("Element an Index 1 :" + list1.get(1));
        // System.out.println(list1.get(2));

        list1.add(4);   // Integer 4 hinzufuegen - Auto-Boxing!

        for(Integer element : list1)
        {
            System.out.println(element);
        }

        list1.remove(1);    // Integer-Objekt 5  Index 1
        list1.remove(1);    // Integer-Objekt 4  Index 1

        System.out.println("size : " + list1.size());


        System.out.printf("%n%n----------- nur noch die 3 in list1 --------------%n%n");    
        for(Integer element : list1)
        {
            System.out.println(element);
        }

        System.out.println(list1.get(0));

    }

}
16.-20.05.2022 - Collections Maps
Quellcode aus der Vorlesung - Klasse Vorlesung0518.java
package vorlesungen.vorlesung0518;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class Vorlesung0518 
{
    public static void print(List<String> list)
    {
        for(String element : list)
        {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void print(Set<String> set)
    {
        for(String element : set)
        {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) 
    {
        Set<String> set1 = new TreeSet<>();
        set1.add("A");
        set1.add("F");
        set1.add("I");
        set1.add("C");

        Set<String> set2 = new TreeSet<>();
        set2.add("D");
        set2.add("G");
        set2.add("Z");
        set2.add("K");

        print(set1);
        print(set2);

        set1.addAll(set2);
        print(set1);

        set1.retainAll(set2);
        print(set1);

        System.out.println(set1.equals(set2));

        set1.add("H");
        System.out.println(set1.equals(set2));
        print(set1);

        set1.removeAll(set2);
        print(set1);


        Map<String, Double> myMap = new HashMap<>();
        myMap.put("s0512345", 1.7);
        myMap.put("s0587654", 1.3);
        myMap.put("s0512345", 2.3);

        Set<Map.Entry<String, Double>> dataSet = myMap.entrySet();

        for(Map.Entry<String, Double> entry : dataSet)
        {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        Set<String> keys = myMap.keySet();
        for(String key : keys)
        {
            System.out.println(key);
        }

        Collection<Double> values = myMap.values();
        for(Double value : values)
        {
            System.out.println(value);
        }

    }

}
23.-27.05.2022 - Abstrakte Klassen
Quellcode aus der Vorlesung - abstrakte Klasse Shape.java
package vorlesungen.vorlesung0525;

public abstract class Shape 
{
    public abstract double perimeter();

    public abstract double area();
}
Rectangle.java
package vorlesungen.vorlesung0525;

public class Rectangle extends Shape
{
    private int width, height;


    public Rectangle(int width, int height) 
    {
        this.width = width;
        this.height = height;
    }

    @Override
    public double perimeter() 
    {
        return 2 * (this.width + this.height);
    }

    @Override
    public double area() 
    {
        return this.height * this.width;
    }

}
Circle.java
package vorlesungen.vorlesung0525;

public class Circle extends Shape 
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    @Override
    public double perimeter() 
    {
        return Math.PI * 2 * this.radius;
    }

    @Override
    public double area() 
    {
        return Math.PI * this.radius * this.radius;
    }

}
Testklasse.java
package vorlesungen.vorlesung0525;

public class Testklasse 
{
    public static void printPerimeter(Shape s)
    {
        System.out.println("perimeter : " + s.perimeter() + "cm");
    }

    public static void printArea(Shape s)
    {
        System.out.println("area : " + s.area() + "cm^2");
    }

    public static double getSumPerimeters(Shape[] shapes)
    {
        double sumPerimeters = 0.0;
        for(Shape s : shapes)
        {
            sumPerimeters += s.perimeter();
        }
        return sumPerimeters;
    }

    public static void main(String[] args) 
    {
        Rectangle r1 = new Rectangle(10, 20);
        Shape r2 = new Rectangle(20,30);
        printPerimeter(new Rectangle(20,30));
        printPerimeter(r1);
        printPerimeter(r2);
        Shape[] shapes = new Shape[4];
        shapes[0] = new Rectangle(20,30);
        shapes[1] = new Circle(5.0);
        shapes[2] = new Rectangle(11, 22);
        shapes[3] = new Circle(15.0);

        System.out.println(getSumPerimeters(shapes));
    }
}
30.-03.06.2022 - Interfaces
Quellcode aus der Vorlesung - Testklasse.java
package vorlesungen.vorlesung0601;

public class Testklasse 
{
    public static void sort(Comparable[] unsorted)
    {
        for(int bubble=0; bubble<unsorted.length-1; bubble++)
        {
            for(int index = 0; index < unsorted.length-1-bubble; index++)
            {
                if(unsorted[index].compareTo((Rectangle)unsorted[index+1]) > 0)
                {
                    Comparable tmp = unsorted[index+1];
                    unsorted[index+1] = unsorted[index];
                    unsorted[index] = tmp;
                }
            }
        }
    }

    public static void main(String[] args) 
    {
        String s1 = "Hallo";
        String s2 = "Ballo";
        System.out.println(s1.compareTo(s2));

        Rectangle[] rects = new Rectangle[4];
        rects[0] = new Rectangle(33, 4);
        rects[1] = new Rectangle(4, 43);
        rects[2] = new Rectangle(3, 14);
        rects[3] = new Rectangle(23, 4);

        System.out.printf("%n----- unsortiert ------%n%n");
        for(Printable r : rects)
        {
            r.print();
        }

        /*
        if(rects instanceof Comparable[])
        {
            System.out.println("ja");
        }
        */

        sort(rects);

        System.out.printf("%n----- sortiert ? ------%n%n");

        for(Printable r : rects)
        {
            r.print();
        }

        System.out.printf("%n----- unsortiert ------%n%n"); 
        Circle[] circs = new Circle[4];
        circs[0] = new Circle(4.0);
        circs[1] = new Circle(3.0);
        circs[2] = new Circle(5.0);
        circs[3] = new Circle(2.0);

        for(Circle c : circs)
        {
            c.print();
        }

        sort(circs);

        System.out.printf("%n----- sortiert ? ------%n%n");
        for(Circle c : circs)
        {
            c.print();
        }
    }

}
Rectangle.java
package vorlesungen.vorlesung0601;

public class Rectangle extends Shape implements Comparable<Rectangle>, Printable
{
    private int width, height;


    public Rectangle(int width, int height) 
    {
        this.width = width;
        this.height = height;
    }

    @Override
    public double perimeter() 
    {
        return 2 * (this.width + this.height);
    }

    @Override
    public double area() 
    {
        return this.height * this.width;
    }

    @Override
    public int compareTo(Rectangle o) {

        return ((this.height + this.width) - (o.height + o.width));
    }

    @Override
    public void print() {
        System.out.printf("%2d x %2d = %7.2f %n", this.height, this.width, this.area());

    }

}
Circle.java
package vorlesungen.vorlesung0601;

public class Circle extends Shape implements Comparable<Circle>, Printable
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    @Override
    public double perimeter() 
    {
        return Math.PI * 2 * this.radius;
    }

    @Override
    public double area() 
    {
        return Math.PI * this.radius * this.radius;
    }

    @Override
    public void print() {
        System.out.printf(" r=%.2fcm, d=%.2fcm, a=%.2fcm %n", this.radius, this.perimeter(), this.area());

    }

    @Override
    public int compareTo(Circle o) 
    {
        if(this.radius > o.radius)
        {
            return 1;
        }
        else if(this.radius < o.radius)
        {
            return -1;
        }
        else 
        {
            return 0;
        }

    }

}
Printable.java
package vorlesungen.vorlesung0601;

public interface Printable {

    public void print();

}
06.-10.06.2022 - GUI Einführung
Quellcode aus der Vorlesung - MyFirstWindow.java
package vorlesungen.vorlesung0608;

import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.*;

public class MyFirstWindow extends JFrame
{

    public MyFirstWindow()
    {
        super();

        this.setTitle("My first window!");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel content = initContent();
        this.getContentPane().add(content);

        this.setLocation(300, 200);
        this.setSize(400, 300);
        this.setVisible(true);
    }

    public JPanel initContent()
    {
        JPanel main = new JPanel();

        main.setLayout(new FlowLayout(FlowLayout.LEFT, 120, 130));

        main.setBackground(Color.LIGHT_GRAY);

        JButton btn1 = new JButton("Button1");
        main.add(btn1);

        JButton btn2 = new JButton("Button2");
        main.add(btn2);

        JButton btn3 = new JButton("Button3");
        main.add(btn3);

        JButton btn4 = new JButton("Button4 mit viel Text");
        main.add(btn4);

        JButton btn5 = new JButton("1");
        main.add(btn5);

        JButton btn6 = new JButton();
        main.add(btn6);

        return main;
    }

}
Testklasse.java
package vorlesungen.vorlesung0608;

public class Testklasse {

    public static void main(String[] args) 
    {
        new MyFirstWindow();

    }

}
13.-17.06.2022 - Layout-Manager
Quellcode aus der Vorlesung - MySecondWindow.java
package vorlesungen.vorlesung0615;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.*;

public class MySecondWindow extends JFrame
{

    public MySecondWindow()
    {
        super();

        this.setTitle("My first window!");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel content = this.initContent();
        this.getContentPane().add(content);

        this.setLocation(300, 200);
        this.setSize(400, 300);
        this.setVisible(true);
    }

    public JPanel initContent()
    {
        JPanel main = new JPanel();

        main.setLayout(new BorderLayout(30, 30));

        main.setBackground(Color.BLUE);

        JPanel oben = new JPanel();
        oben.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        main.add(oben, BorderLayout.NORTH);

        JPanel mitte = new JPanel();
        mitte.setLayout(new GridLayout(6, 3, 10, 10));
        mitte.setBackground(Color.GREEN);
        main.add(mitte, BorderLayout.CENTER);

        JLabel lab1 = new JLabel("Name : ");
        oben.add(lab1);
        JTextField tf = new JTextField(20);
        oben.add(tf);

        JButton[] btnArr = new JButton[18];
        for (int i = 0; i < btnArr.length; i++) {
            btnArr[i] = new JButton((i+1)+"");
            mitte.add(btnArr[i]);
        }

        JPanel unten = new JPanel();
        unten.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));

        JButton okBtn = new JButton("Ok");
        unten.add(okBtn);

        JButton cnclBtn = new JButton("Cancel");
        unten.add(cnclBtn);

        JRadioButton rb = new JRadioButton();
        unten.add(rb);

        JCheckBox cb = new JCheckBox();
        unten.add(cb);

        JPanel links = new JPanel();
        JPanel rechts = new JPanel();

        main.add(links, BorderLayout.WEST);
        main.add(rechts, BorderLayout.EAST);

        main.add(unten, BorderLayout.SOUTH);
        /*
        JButton btn1 = new JButton("NORTH");
        main.add(btn1, BorderLayout.NORTH);

        JButton btn2 = new JButton("Button2");
        main.add(btn2, BorderLayout.WEST);

        JButton btn3 = new JButton("Button3");
        main.add(btn3, BorderLayout.EAST);

        JButton btn4 = new JButton("Button4 mit viel Text");
        main.add(btn4, BorderLayout.SOUTH);

        JButton btn5 = new JButton("1");
        main.add(btn5);

        JButton btn6 = new JButton();
        main.add(btn6);

        JButton btn7 = new JButton("Button 7");
        main.add(btn7, BorderLayout.CENTER);
        */

        return main;
    }

}
Testklasse.java
package vorlesungen.vorlesung0615;

public class Testklasse {

    public static void main(String[] args) 
    {
        new MySecondWindow();

    }

}
20.-24.06.2022 - GUI Ereignisse
  • siehe GUI Ereignisse
  • siehe Übung 11
  • siehe Aufgabe 8
  • siehe Video zu GUI Ereignisse - Vorlesung aus dem Vorjahr
  • Quellcode aus dem Video

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class Ereignisbehandlung extends JFrame implements ActionListener
    {
        Integer anzKlicks = 0;
        JLabel unten;
    
        public Ereignisbehandlung(){
            super();
            this.setTitle("Ereignisbehandlung");
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel content = this.initContent();
            this.getContentPane().add(content);
    
            this.setSize(200, 150);
            this.setLocation(200, 100);
            this.setVisible(true);
        }
    
        public JPanel initContent() {
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new BorderLayout());
    
            JPanel oben = new JPanel();
    
            JButton minus = new JButton("-");
            JButton plus = new JButton("+");
    
            oben.add(minus);
            oben.add(plus);
    
            plus.addActionListener(this);
            minus.addActionListener(this);
    
            this.unten = new JLabel(this.anzKlicks.toString());
            this.unten.setFont(new Font("Verdana", Font.BOLD, 48));
            this.unten.setHorizontalAlignment(JLabel.CENTER);
    
            mainPanel.add(oben, BorderLayout.NORTH);
            mainPanel.add(unten, BorderLayout.CENTER);
    
            return mainPanel;
        }
    
        public static void main(String[] args) {
            new Ereignisbehandlung();
        }
    
        @Override
        public void actionPerformed(ActionEvent e) 
        {   
            Object quelle = e.getSource();  // hat ActionEvent ausgeloest
            if(quelle instanceof JButton)
            {
                JButton button = (JButton)quelle;
                if(button.getText().equals("-"))
                {
                    this.anzKlicks--;
                    System.out.println("Minus-Button geklickt ... " + this.anzKlicks);
                }
                else if(button.getText().equals("+"))
                {
                    this.anzKlicks++;
                    System.out.println("Plus-Button geklickt ... " + this.anzKlicks);
                }
                this.unten.setText(this.anzKlicks.toString());
            }
        }
    
    }       
    
27.-01.07.2022 - ActionListener
  • siehe GUI Ereignisse
  • siehe Übung 11
  • siehe Aufgabe 8
  • Quellcode aus Vorlesung

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class Ereignisbehandlung extends JFrame
    {
        JLabel unten;
        Integer anzKlicks = 0;
    
        public Ereignisbehandlung()
        {
            super();
            setTitle("Ereignisbehandlung");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel mainPanel = init();
    
            this.getContentPane().add(mainPanel, BorderLayout.CENTER);
            setSize(200,150);
            setVisible(true);
        }
    
        private JPanel init()
        {
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
    
            JPanel oben = new JPanel();
            JButton minus = new JButton("-");
            minus.setActionCommand("minus");
            JButton plus = new JButton("+");
            plus.setActionCommand("plus");
    
    
            minus.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    Ereignisbehandlung.this.anzKlicks--;
                    Ereignisbehandlung.this.unten.setText(Ereignisbehandlung.this.anzKlicks.toString());
                }
    
            });
            plus.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    Ereignisbehandlung.this.anzKlicks++;
                    Ereignisbehandlung.this.unten.setText(Ereignisbehandlung.this.anzKlicks.toString());
    
                }
    
            });
    
            oben.add(minus);
            oben.add(plus);
    
            this.unten = new JLabel(this.anzKlicks.toString());
            unten.setFont(new Font("Verdana", Font.BOLD, 24));
            unten.setHorizontalAlignment(JLabel.CENTER);
    
            panel.add(oben, BorderLayout.NORTH);
            panel.add(unten, BorderLayout.CENTER);
    
            return panel;
        }
    
    
        class ActionHandler implements ActionListener {
    
            Integer anzKlicks;
    
            @Override
            public void actionPerformed(ActionEvent e) {
                Object quelle = e.getSource();
                if(quelle instanceof JButton)
                {
                    JButton button = (JButton) quelle;
                    if(button.getActionCommand().equals("plus"))
                    {
                        Ereignisbehandlung.this.anzKlicks++;
                    }
                    else if(button.getActionCommand().equals("minus"))
                    {
                        Ereignisbehandlung.this.anzKlicks--;
                    }
                }
                Ereignisbehandlung.this.unten.setText(anzKlicks.toString());
    
            }
    
        }
    
    
        public static void main(String[] args) 
        {
            new Ereignisbehandlung();
        }
    }
    
04.-08.07.2022 - MouseListener
  • siehe Mausereignisse
  • siehe Übung 12
  • siehe Aufgabe 8
  • Quellcode aus Vorlesung

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    package vorlesungen.vorlesung0706;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.Random;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class Mausereignisse extends JFrame implements MouseListener
    {
        private int size;
        private JPanel[][] panels;
        private JPanel panel;
    
        public Mausereignisse(int size)
        {
            super();
            this.size = size;
            this.setTitle("Mausereignisse");
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel mainPanel = initContent(size);
    
            this.getContentPane().add(mainPanel, BorderLayout.CENTER);
    
            this.setSize(400,400);
            this.setVisible(true);
        }
    
        private Color randomColor() 
        {
            Random r = new Random();
            int red = r.nextInt(256);
            int blue = r.nextInt(256);
            int green = r.nextInt(256);
    
            Color c = new Color(red, blue, green);
            return c;
        }
    
        private JPanel initContent(int size)
        {
            this.panel = new JPanel();
            this.panel.setLayout(new GridLayout(size, size));
            this.panel.addMouseListener(this);
    
            this.panels = new JPanel[size][size];
            for (int row = 0; row < panels.length; row++) 
            {
                for (int col = 0; col < panels[row].length; col++) 
                {
                    this.panels[row][col] = new JPanel();
                    this.panels[row][col].setLayout(new BorderLayout());
                    JLabel label = new JLabel(row + " " + col);
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setFont(new Font("Verdana", Font.BOLD, 24));
                    label.setForeground(Color.WHITE);
                    this.panels[row][col].add(label);
                    this.panels[row][col].setBackground(randomColor());
                    this.panels[row][col].addMouseListener(new MouseListener() {
    
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            System.out.println("einzelnes clicked");
                            Object src = e.getSource();
                            if(src instanceof JPanel) {
                                JPanel here = (JPanel)src;
                                here.setBackground(Mausereignisse.this.randomColor()); 
                            }
    
                        }
    
                        @Override
                        public void mousePressed(MouseEvent e) {
                            // TODO Auto-generated method stub
    
                        }
    
                        @Override
                        public void mouseReleased(MouseEvent e) {
                            // TODO Auto-generated method stub
    
                        }
    
                        @Override
                        public void mouseEntered(MouseEvent e) {
                            // TODO Auto-generated method stub
    
                        }
    
                        @Override
                        public void mouseExited(MouseEvent e) {
                            // TODO Auto-generated method stub
    
                        }
    
                    });
                    panel.add(this.panels[row][col]);
                }
            }
            return this.panel;
        }
    
        public static void main(String[] args) 
        {
            new Mausereignisse(4);
    
        }
    
        @Override
        public void mouseClicked(MouseEvent e) {
    
            int x = e.getX();
            int y = e.getY();
            int width = this.panel.getWidth();
            int height = this.panel.getHeight();
            int panelWidth = width / this.size;
            int panelHeight = height / this.size;
    
            int row = y / panelHeight;
            int col = x / panelWidth;
    
            System.out.println("mouse clicked [x=" + x + ", y=" + y + "]");
            System.out.println("width : " + width + ", height : " + height);
            System.out.println("row : " + row + " , col : " + col);
            this.panels[row][col].setBackground(randomColor());
        }
    
        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println("mouse pressed");
    
        }
    
        @Override
        public void mouseReleased(MouseEvent e) {
            System.out.println("mouse released");
    
        }
    
        @Override
        public void mouseEntered(MouseEvent e) {
            System.out.println("mouse entered");
            for (int row = 0; row < panels.length; row++) 
            {
                for (int col = 0; col < panels[row].length; col++) 
                {
                    this.panels[row][col].setBackground(randomColor());
                }
            }
    
        }
    
        @Override
        public void mouseExited(MouseEvent e) {
            System.out.println("mouse exited");
    
        }
    }