import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class CDraw extends Frame implements ActionListener {
CMeinJPanel m_malflaeche;
int m_Ypos, m_Xpos;
public static void main(String[] args) {
CDraw auswahl = new CDraw("Draw");
auswahl.pack();
auswahl.setSize(800, 600);
auswahl.show();
// auswahl.setResizable(false);
}
public CDraw(String titel) {
super(titel);
class CFensterLauscher extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
final MenuBar menue_leiste = new MenuBar();
Menu menu1 = new Menu("Datei");
MenuItem prog_item1 = new MenuItem("Beenden");
prog_item1.addActionListener(this);
menu1.add(prog_item1);
menu1.setFont(new Font("Serif", Font.BOLD, 14));
menue_leiste.add(menu1);
setMenuBar(menue_leiste);
m_malflaeche = new CMeinJPanel();
add(m_malflaeche);
addWindowListener(new CFensterLauscher());
}
class CMeinJPanel extends JPanel { // <<< neu
private Image img; // <<< neu
private Graphics graphics; // <<< neu
class CMeinMausAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
m_Xpos = e.getX();
m_Ypos = e.getY();
validate();
}
}
class CMeinMausMotionAdapter extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
String str;
m_Xpos = e.getX();
m_Ypos = e.getY();
setBackground(Color.WHITE);
graphics.fillOval(m_Xpos, m_Ypos, 20, 20);
repaint();
}
}
CMeinJPanel() {
addMouseListener(new CMeinMausAdapter());
addMouseMotionListener(new CMeinMausMotionAdapter());
setBackground(Color.WHITE);
recreateImage(); // <<< neu
}
public void paintComponent( Graphics g ){ // <<< neu
int width = getWidth();
int height = getHeight();
if( width > 0 && height > 0 &&
(img == null || img.getWidth( this ) != width || img.getHeight( this ) != height ))
recreateImage();
if( img != null && width > 0 && height > 0 )
g.drawImage( img, 0, 0, this );
}
private void recreateImage(){ // <<< neu
int width = getWidth();
int height = getHeight();
BufferedImage newImage = new BufferedImage( Math.max( 1, width),
Math.max( 1, height),
BufferedImage.TYPE_INT_RGB );
Graphics newGraphics = newImage.createGraphics();
if( graphics != null )
graphics.dispose();
if( width > 0 && height > 0 ){
newGraphics.setColor( Color.white );
newGraphics.fillRect( 0, 0, width, height );
}
newGraphics.setColor( Color.black );
if( img != null )
newGraphics.drawImage( img, 0, 0, this );
img = newImage;
graphics = newGraphics;
}
}
public void actionPerformed(ActionEvent e) {
String quelle = e.getActionCommand();
if (quelle.equals("Beenden")) {
System.exit(0);
}
}
}