Klasse um daten zu einlesen

arhzz

Bekanntes Mitglied
Hallo leute!

Vor mir steht ein Problem denn ich nicht ganz lösen kann.Namlich soll ich aus eine txt datei Koordinaten einlesen um ein Bild zu bekommen, und dazu soll ich Klassen als auch Objekte verwenden. So lange habe ich dass hier:

Java:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.concurrent.*;
import java.lang.reflect.*;
/**
 * This class supports the output of graphical objects like points, lines,
 * circles and rectangles in a window.
 *
 *
 */
public final class Window {
    private final JPanel panel;
    private final Graphics2D graphics;
    private Window(JPanel panel, Graphics2D graphics) {
        this.panel = panel;
        this.graphics = graphics;
    }
    /**
     * Creates a window with a given width and height, and shows it on the screen.
     *
     * @param width  the width of the window
     * @param height the height of the window
     */
    public static Window create(int width, int height) {
        RunnableFuture<Window> initTask = new FutureTask<Window>(() -> {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = image.createGraphics();
            graphics.fillRect(0, 0, width, height);

            JFrame frame = new JFrame();
            JPanel panel = new JPanel() {

                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);

                    Graphics2D g2 = (Graphics2D) g.create();
                    g2.drawImage(image, 0, 0, width, height, null);
                    g2.dispose();
                }

                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(width, height);
                }
            };

            frame.setContentPane(panel);
            frame.setTitle("Window");
            frame.pack();
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            return new Window(panel, graphics);
        });

        SwingUtilities.invokeLater(initTask);
        try {
            return initTask.get();
        } catch (InterruptedException e) {
            return null;
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Clears the content of the window.
     */
    public void clear() {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.fillRect(0, 0, panel.getWidth(), panel.getHeight());
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Draws a point at a given position.
     *
     * @param x the x-coordinate for the point
     * @param y the y-coordinate for the point
     */
    public void drawPoint(int x, int y) {
        drawPoint(x, y, Color.BLACK);
    }

    /**
     * Draws a line between two given points.
     *
     * @param x1 the x-coordinate for the first point
     * @param y1 the y-coordinate for the first point
     * @param x2 the x-coordinate for the second point
     * @param y2 the y-coordinate for the second point
     */
    public void drawLine(int x1, int y1, int x2, int y2) {
        drawLine(x1, y1, x2, y2, Color.BLACK);
    }

    /**
     * Draws a rectangle at a top-left position, and with a specific width and
     * height.
     *
     * @param x the top-left x-coordinate for the rectangle
     * @param y the top-left y-coordinate for the rectangle
     * @param w the width for the rectangle
     * @param h the height for the rectangle
     */
    public void drawRectangle(int x, int y, int w, int h) {
        drawRectangle(x, y, w, h, Color.BLACK);
    }

    /**
     * Draws a circle at a given center position, and with a specific radius.
     *
     * @param x the center x-coordinate for the circle
     * @param y the center y-coordinate for the circle
     * @param r the radius for the circle
     */
    public void drawCircle(int x, int y, int r) {
        drawCircle(x, y, r, Color.BLACK);
    }

    /**
     * Draws a text at a given position.
     *
     * @param text the text to draw
     * @param x    the x-coordinate for the text
     * @param y    the y-coordinate for the text
     */
    public void drawText(String text, int x, int y) {
        drawText(text, x, y, Color.BLACK);
    }

    /**
     * Draws a point at a given position, and with a specific color.
     *
     * @param x     the x-coordinate for the point
     * @param y     the y-coordinate for the point
     * @param color the color for the point
     */
    public void drawPoint(int x, int y, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.fillRect(x - 1, y - 1, 3, 3);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Draws a line from between two given coordinates, and with a specific color.
     *
     * @param x1    the x-coordinate for the first point
     * @param y1    the y-coordinate for the first point
     * @param x2    the x-coordinate for the second point
     * @param y2    the y-coordinate for the second point
     * @param color the color for the line
     */
    public void drawLine(int x1, int y1, int x2, int y2, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.drawLine(x1, y1, x2, y2);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Draws a rectangle at a given top-left position, and with a specific width,
     * height, and color.
     *
     * @param x     the top-left x-coordinate for the rectangle
     * @param y     the top-left y-coordinate for the rectangle
     * @param w     the width for the rectangle
     * @param h     the height for the rectangle
     * @param color the color for the rectangle
     */
    public void drawRectangle(int x, int y, int w, int h, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(Color.BLACK);
                graphics.drawRect(x, y, w, h);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Draws a circle at a given center position, and with a specific radius and
     * color.
     *
     * @param x     the center x-coordinate for the circle
     * @param y     the center y-coordinate for the circle
     * @param r     the radius for the circle
     * @param color the color for the circle
     */
    public void drawCircle(int x, int y, int r, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.drawOval(x - r, y - r, 2 * r, 2 * r);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Draws a text at a given position, and with a specific color.
     *
     * @param text  the text to draw
     * @param x     the x-coordinate for the text
     * @param y     the y-coordinate for the text
     * @param color the color for the text
     */
    public void drawText(String text, int x, int y, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.drawString(text, x, y);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Fills a rectangle at a given top-left position, and with a specific width,
     * height, and color.
     *
     * @param x     the top-left x-coordinate for the rectangle
     * @param y     the top-left y-coordinate for the rectangle
     * @param w     the width for the rectangle
     * @param h     the height for the rectangle
     * @param color the color for the rectangle
     */
    public void fillRectangle(int x, int y, int w, int h, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.fillRect(x, y, w, h);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Fills a circle at a given center position, and with a specific radius and
     * color.
     *
     * @param x     the center x-coordinate for the circle
     * @param y     the center y-coordinate for the circle
     * @param r     the radius for the circle
     * @param color the color for the circle
     */
    public void fillCircle(int x, int y, int r, Color color) {
        try {
            SwingUtilities.invokeAndWait(() -> {
                graphics.setColor(color);
                graphics.fillOval(x - r, y - r, 2 * r, 2 * r);
                panel.repaint();
            });
        } catch (InterruptedException e) {
            return;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

class Point {
   final int x;
   final int y;
 

  Point(int x,int y) {
    this.x = x;
    this.y = y;
  }
     Point fromInput() {
    int x = In.readInt();
    int y = In.readInt();

    if (In.done()) return new Point(x,y);
    else return null;
  }

void draw(Window w){
    w.drawPoint(x,y);
}
}

class Line {
  final int x1;
  final int y1;
  final int x2;
  final int y2;

  Line(int x1,int y1,int x2,int y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
  }
    Line fromInput() {
    int x1 = In.readInt();
    int y1 = In.readInt();
    int x2 = In.readInt();
    int y2 = In.readInt();

    if (In.done()) return new Line(x1,y1,x2,y2);
    else return null;
  }
void draw(Window w){
    w.drawLine(x1, y1, x2, y2);
}
}

class Rectangle {
  final int x;
  final int y;
  final int w1;
  final int h;

  Rectangle(int x,int y,int w1,int h) {
    this.x = x;
    this.y = y;
    this.w1 = w1;
    this.h = h;
  }
    Rectangle fromInput() {
    int x = In.readInt();
    int y = In.readInt();
    int w1 = In.readInt();
    int h = In.readInt();

    if (In.done()) return new Rectangle(x,y,w1,h);
    else return null;
  }
void draw(Window w){
    w.drawRectangle(x,y,w1,h );
}
}

class Circle {
  final int x;
  final int y;
  final int r;
 
  Circle(int x,int y,int r) {
    this.x = x;
    this.y = y;
    this.r = r;
  }
    Circle fromInput() {
    int x = In.readInt();
    int y = In.readInt();
    int r = In.readInt();

    if (In.done()) return new Circle(x,y,r);
    else return null;
  }
void draw(Window w){
    w.drawCircle(x, y, r );
}
}

Jetzt ist die Frage,brauche ich noch eine Klasse in der ich die txt Datei offne und die Kooridnaten speichere oder nicht? Und wie kann ich die Kooridanten "übergen" zu den Circle,Line etc.. Klassen.Ich muss doch die fromInput methode benuten? Also ein Paar Hinweise wurden mir sehr hilfreich sein, Danke
 
Du brauchst vor allem mal eine Klasse mit einer main-Methode. Und ja, natürlich brauchst Du Code, der die Datei einliest (bzw. die fromInput-Methode aufruft). Je nachdem, wie die Datei aufgebaut ist, musst Du ggf. auch den Typ auswerten.
 
Und wie kann ich die Kooridanten "übergen" zu den Circle,Line etc.. Klassen.
Erstmal müsstest du wissen für welches Objekt ein Koordiaten-Tupel steht. Wenn du z.B. eine Zeile in der txt hast mit 4 Werten, dann könnte es u.a. sowohl eine Linie, als auch ein Rechteck sein. Du musst dir also sowieso noch einen Identifier überlegen innerhalb der txt um einen Typ für das Tupel festzulegen. Diesen Identifier kannst du dann auswerten und das entsprechende Objekt anlegen.
 
Erstmal müsstest du wissen für welches Objekt ein Koordiaten-Tupel steht. Wenn du z.B. eine Zeile in der txt hast mit 4 Werten, dann könnte es u.a. sowohl eine Linie, als auch ein Rechteck sein. Du musst dir also sowieso noch einen Identifier überlegen innerhalb der txt um einen Typ für das Tupel festzulegen. Diesen Identifier kannst du dann auswerten und das entsprechende Objekt anlegen.
Ja,dass habe ich vergessen zu sagen, am anfang jeder Zeile steht L für Linien R für Rectangle usw... Also ich dachte dass ich dass mit einem switch machen kann, aber mir ist immer nocht unklar wie ich den Compilre sage okay verwende diese methode um linien zu zeichnen, zuerst muss ich mit readInput die zeile einlesen, überprufen was es ist eine linie kreise... Aber wie sage ich ok es ist eine linie jetzt zeichne sie. Ich hoffe dass sie mich verstanden haben.
 
Dafür wäre es sinnvoll, wenn deine Elemente alle ein von dir erstelltest Interface implementieren. Nennen wir es "Drawable". Das Interface hat die Methode void draw(Window w), welche du bereits für all deinen Elementen implementiert hast. Dann kannst du in z.B. Window eine Liste von Drawables verwalten und diese Drawables beim Zeichnen iterieren. Sinngemäß:
Java:
class Linie implements Drawable {
  //...

  @Override
  public void draw (Window w) {
    // ...
  }
}

List<Drawable> drawables = new ArrayList<>();
// nun die Liste Befüllen mit Elementen aus der Datei
drawables.add(linie);
drawables.add(kreis);
// ...

// zeichnen
for (Drawable drawable : drawables) {
  drawable.draw(window);
}
 
J
Dafür wäre es sinnvoll, wenn deine Elemente alle ein von dir erstelltest Interface implementieren. Nennen wir es "Drawable". Das Interface hat die Methode void draw(Window w), welche du bereits für all deinen Elementen implementiert hast. Dann kannst du in z.B. Window eine Liste von Drawables verwalten und diese Drawables beim Zeichnen iterieren. Sinngemäß:
Java:
class Linie implements Drawable {
  //...

  @Override
  public void draw (Window w) {
    // ...
  }
}

List<Drawable> drawables = new ArrayList<>();
// nun die Liste Befüllen mit Elementen aus der Datei
drawables.add(linie);
drawables.add(kreis);
// ...

// zeichnen
for (Drawable drawable : drawables) {
  drawable.draw(window);
}
Leider haben wir List noch nicht gemacht, und deswegen kann ich sie nicht verwenden, wie kann es ohne Lists funktioniren?
 
J

Leider haben wir List noch nicht gemacht, und deswegen kann ich sie nicht verwenden, wie kann es ohne Lists funktioniren?
EDIT:

Okay also wir haben ein Hinweis bekommen

Java:
public class WindowDemonstration {

    public static void main(String[] args) {
        // Window Instanz erstellen
        Window w = Window.create(400, 400);
        // Text Instanz erstellen
        // In UE06 dann Point, Line, Rectangle, Circle
        Text t = new Text("Hallo, ich bin ein Window Text", 47, 100);
        // die draw-Methode von Text aufrufen
        t.draw(w);
    }

}

class Text {
    // Felder
    private final String text;
    private final int x, y;

    // Konstruktor
    Text(String text, int x, int y) {
        this.text = text;
        this.x = x;
        this.y = y;
    }

    // Objektmethode 'draw'
    void draw(Window w) {
        w.drawText(text, x, y);
    }
}
Also den Problem sollte man ungefähr so lösen. Ich habe ein Paar dinge probiert aber es geht nicht.Vielleicht ein bisschen hilfe?
Danke!
 
Aha und welche? Letztlich musst du die Datei tatsächlich nur zeilenweise einlesen und per Switch-Case den Konstruktor aufrufen sowie anschließend die draw Methode auf dem Objekt
Java:
static class Point   {               
    int x;
    int y;
 
    Point(int x, int y) {
        this.x = x;
        this.y = y;
 
 
    }   
   static Point fromInput() { 
       int x = In.readInt();
       int y = In.readInt();
 
    if (In.done()) return new Point(x, y);
        else return null;
   }
   public void drawMe(Window w) {      //<<<<<<< ADDED
      w.drawPoint(x,y); 
   }
}
 
static class Line   {               
    int x1;
    int y1;
    int x2;
    int y2;
 
    Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }   
   static Line fromInput() { 
       int x1 = In.readInt();
       int y1 = In.readInt();
       int x2 = In.readInt();
       int y2 = In.readInt();
 
    if (In.done()) return new Line(x1, y1, x2, y2);
        else return null;
   }
   public void draw(Window w) {
      w.drawLine(x1,y1,x2,y2); 
   }
}

static class Rectangle {
   char ch;
   int x;
   int y;
   int w1;
   int h;

  Rectangle(char ch,int x,int y,int w1,int h) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.w1 = w1;
    this.h = h;
  }
    static Rectangle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int w1 = In.readInt();
    int h = In.readInt();

    if (In.done()) return new Rectangle(ch,x,y,w1,h);
    else return null;
  }
void draw(Window w){
    w.drawRectangle(x,y,w1,h );
}
}

static class Circle {
   char ch;
   int x;
   int y;
   int r;
 
   Circle(char ch,int x,int y,int r) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.r = r;
  }
   static Circle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int r = In.readInt();

    if (In.done()) return new Circle(ch,x,y,r);
    else return null;
  }
void draw(Window w){
    w.drawCircle(x, y, r );
}
}
public static void main(String[] args){
    Window w = Window.create(300,300);
    In.open("shapes.txt");
    char ch = In.readChar();
    switch(ch){
        case 'L':
        Line l = Line.fromInput();
        l.draw(w);
        break;
        case 'R':
        Rectangle r = Rectangle.fromInput();
        r.draw(w);
        break;
        case 'C':
        Circle c = Circle.fromInput();
        c.draw(w);
        break;
    }
    
}

}
Aber nur das Fenster kommt aus,und kein Bild
 
Also du liest erstmal nur einen Character ein. Ist denn der erste Character in der Datei bereits L R oder C? Ich vermute, dass er das nicht ist, dann findet der SwitchCase auch garkeinen Treffer
Ja eigentlich sieht die Datei so aus;
300 300
L 0 200 300 200
L 150 100 200 50
L 200 50 250 100
R 150 100 100 100
R 185 160 30 40
R 170 120 20 20
L 180 120 180 140
L 170 130 190 130
R 210 120 20 20
L 220 120 220 140
L 210 130 230 130
C 50 50 10
L 30 50 40 50
L 35 35 42 42
L 50 30 50 40
L 65 35 58 42
L 60 50 70 50
L 58 58 65 65
L 50 60 50 70
L 42 58 35 65
Ich wurde sagen ja? aber die 300 300 konnten das Problem sein.
 
Window musst du vor der Schleife erstellen
Ja,dass habe ich gemacht,Danke
Java:
static class Point   {               
    int x;
    int y;
 
    Point(int x, int y) {
        this.x = x;
        this.y = y;
 
 
    }   
   static Point fromInput() { 
       int x = In.readInt();
       int y = In.readInt();
 
    if (In.done()) return new Point(x, y);
        else return null;
   }
   public void draw(Window w) {     
      w.drawPoint(x,y); 
   }
}
 
static class Line   {               
    int x1;
    int y1;
    int x2;
    int y2;
 
    Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }   
   static Line fromInput() { 
       int x1 = In.readInt();
       int y1 = In.readInt();
       int x2 = In.readInt();
       int y2 = In.readInt();
 
    if (In.done()) return new Line(x1, y1, x2, y2);
        else return null;
   }
   public void draw(Window w) {
      w.drawLine(x1,y1,x2,y2); 
   }
}

static class Rectangle {
   char ch;
   int x;
   int y;
   int w1;
   int h;

  Rectangle(char ch,int x,int y,int w1,int h) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.w1 = w1;
    this.h = h;
  }
    static Rectangle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int w1 = In.readInt();
    int h = In.readInt();

    if (In.done()) return new Rectangle(ch,x,y,w1,h);
    else return null;
  }
void draw(Window w){
    w.drawRectangle(x,y,w1,h );
}
}

static class Circle {
   char ch;
   int x;
   int y;
   int r;
 
   Circle(char ch,int x,int y,int r) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.r = r;
  }
   static Circle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int r = In.readInt();

    if (In.done()) return new Circle(ch,x,y,r);
    else return null;
  }
void draw(Window w){
    w.drawCircle(x, y, r );
}
}
public static void main(String[] args){
    In.open("shapes.txt");
    int width = In.readInt();
    int height = In.readInt();
    Window w = Window.create(width,height);
    do{
    char ch = In.readChar();
    switch(ch){
        case 'L':
        Line l = Line.fromInput();
        l.draw(w);
        break;
        case 'R':
        Rectangle r = Rectangle.fromInput();
        r.draw(w);
        break;
        case 'C':
        Circle c = Circle.fromInput();
        c.draw(w);
        break;
     }
    }while(In.done());
In.close();
}
}

Aber jetzt kommt der bild kommisch Raus, was kann das Problem sein?
 
Window musst du vor der Schleife erstellen
Ja,dass habe ich gemacht,Danke
Java:
static class Point   {               
    int x;
    int y;
 
    Point(int x, int y) {
        this.x = x;
        this.y = y;
 
 
    }   
   static Point fromInput() { 
       int x = In.readInt();
       int y = In.readInt();
 
    if (In.done()) return new Point(x, y);
        else return null;
   }
   public void draw(Window w) {     
      w.drawPoint(x,y); 
   }
}
 
static class Line   {               
    int x1;
    int y1;
    int x2;
    int y2;
 
    Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }   
   static Line fromInput() { 
       int x1 = In.readInt();
       int y1 = In.readInt();
       int x2 = In.readInt();
       int y2 = In.readInt();
 
    if (In.done()) return new Line(x1, y1, x2, y2);
        else return null;
   }
   public void draw(Window w) {
      w.drawLine(x1,y1,x2,y2); 
   }
}

static class Rectangle {
   char ch;
   int x;
   int y;
   int w1;
   int h;

  Rectangle(char ch,int x,int y,int w1,int h) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.w1 = w1;
    this.h = h;
  }
    static Rectangle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int w1 = In.readInt();
    int h = In.readInt();

    if (In.done()) return new Rectangle(ch,x,y,w1,h);
    else return null;
  }
void draw(Window w){
    w.drawRectangle(x,y,w1,h );
}
}

static class Circle {
   char ch;
   int x;
   int y;
   int r;
 
   Circle(char ch,int x,int y,int r) {
    this.ch = ch;
    this.x = x;
    this.y = y;
    this.r = r;
  }
   static Circle fromInput() {
    char ch = In.readChar();
    int x = In.readInt();
    int y = In.readInt();
    int r = In.readInt();

    if (In.done()) return new Circle(ch,x,y,r);
    else return null;
  }
void draw(Window w){
    w.drawCircle(x, y, r );
}
}
public static void main(String[] args){
    In.open("shapes.txt");
    int width = In.readInt();
    int height = In.readInt();
    Window w = Window.create(width,height);
    do{
    char ch = In.readChar();
    switch(ch){
        case 'L':
        Line l = Line.fromInput();
        l.draw(w);
        break;
        case 'R':
        Rectangle r = Rectangle.fromInput();
        r.draw(w);
        break;
        case 'C':
        Circle c = Circle.fromInput();
        c.draw(w);
        break;
     }
    }while(In.done());
In.close();
}
}

Aber jetzt kommt der bild kommisch Raus, was kann das Problem sein?
 
Ich denke das liegt an dem readChar von Circle und Rectangle, du nimmst der ersten Koordinate damit eine Ziffer weg. Nämlich bei "50" die "5" und als Resultat hängt der Kreis auf x = 0, was man im Bild ziemlich gut sieht.
 

Zurück
Oben