Thursday, 30 March 2017

Simple Swing Applet Example

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 
//
//  ScribbleApplet.java
//  ScribbleApplet
//
//  Created by tditchen on 11/21/04.
//  Copyright (c) 2004 Todd Ditchendorf. No rights reserved!
//
//

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.BasicStroke;
import java.awt.RenderingHints;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;

public class ScribbleApplet extends JApplet {

	public volatile boolean initFlag = true;
	public volatile boolean clearFlag = true;
	JPanel p;
	
	public void init() {
		setLAF();
		initGUI();
    }
	
	public void start() {
		
	}
	
	private void initGUI() {
		p = new ScribblePanel();
		JButton b = new JButton("Clear");
		b.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent evt) {
				clearFlag = true;
				p.repaint();	
			}
		});
		getContentPane().add(p,BorderLayout.CENTER);
		getContentPane().add(b,BorderLayout.SOUTH);
	}
	
	class ScribblePanel extends JPanel {
	
		Stroke stroke;
		Rectangle innerArea;
		int startX,startY,endX,endY;
		
		public ScribblePanel() {
			super();
			stroke = new BasicStroke(2.0f);
			setBackground(Color.white);
			setForeground(Color.black);
			setPreferredSize(new Dimension(800,600));
			setBorder(BorderFactory.createLineBorder(Color.lightGray,1));
			repaint();
			
			addMouseListener(new MouseAdapter() {
				public void mousePressed(final MouseEvent evt) {
					initFlag = false;
					startX = evt.getX();
					startY = evt.getY();
				}
			});
			
			addMouseMotionListener(new MouseMotionAdapter() {
				public void mouseDragged(final MouseEvent evt) {
					endX = evt.getX();
					endY = evt.getY();
					repaint();
				}
			});
		}

		public void paintComponent(final Graphics g) {
			Graphics2D g2 = (Graphics2D)g;
			if (clearFlag || initFlag) {
				innerArea = SwingUtilities.calculateInnerArea(this,innerArea);
				g2.setColor(getBackground());
				g2.fill(innerArea);
				clearFlag = false;
				g.setColor(getForeground());
			}
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
								RenderingHints.VALUE_ANTIALIAS_ON);
			g2.setStroke(stroke);
			g2.drawLine(startX,startY,endX,endY);
			startX = endX;
			startY = endY;
		}
	
	}
	
	private void setLAF() {
		String laf = UIManager.getSystemLookAndFeelClassName();
		try {
			UIManager.setLookAndFeel(laf);
		} catch (Exception exc) {
			System.err.println ("Error loading " + laf + ": " + exc);
		}
	}

}