Auf Thema antworten

Das Problem war ich hatte einen JFrame (swing) mit Graphics (awt) vermischt. Aus dem JFrame habe ich nun einfach ein Frame gemacht, wodurch das ganze nun funktioniert.


Mein funktionierender Code sieht nun so aus:

[code=Java]

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Frame;

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;


/**

 * Draw a triangle.

 *

 * @author -Subscription-

 */

public class Triangle extends Frame {

   

    /** Constructor. */

    public Triangle() {

        setGui();

    }


    /**

     * This method is doing the graphic stuff.

     */

    public void paint(Graphics g){

        // Just to test if the painting works

        System.out.println("Debug: Test if the paint method works.");

        g.setColor(Color.red);

        g.drawLine(0, 0, 500, 500);

    }

   


    /**

     * Creates the graphic user interface.

     */

    private void setGui() {

        setTitle("Sierpinski Triangle");

        setBounds(450, 100, 500, 500);

        setBackground(Color.WHITE);

        setLayout(new BorderLayout());

        addWindowListener( new WindowAdapter() {

              @Override

              public void windowClosing ( WindowEvent e ) { System.exit( 0 ); }

            } );

        setVisible(true);

    }


    /**

     * @param args

     */

    public static void main(String[] args) {

        new Triangle();

    }


}

[/code]


Eine weitere Methode die ich im Internet gefunden habe, bei der man JFrame benutzen kann und ohne extends arbeitet, funktioniert so:

[code=Java]

import java.awt.*;

import javax.swing.*;

import java.awt.image.BufferedImage;


class GetGraphics

{

  public static void main(String[] args)

  {

  JFrame frame=new JFrame();

  frame.setLayout(new FlowLayout());

  BufferedImage image=new BufferedImage(400,400,BufferedImage.TYPE_INT_ARGB);

  Graphics graphics=image.getGraphics();

 

  graphics.setColor(Color.red);

  graphics.drawOval(150,50,120,50);

  graphics.dispose();

  JLabel label=new JLabel(new ImageIcon(image));

  frame.add(label);

  frame.setTitle("Graphics");

  frame.setSize(200,150);

  frame.setVisible(true);

  }

}

[/code]

Gefunden auf: Java get Graphics



Oben