473,769 Members | 3,923 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting Java Applet to JFrame

8 New Member
Can anyone help me please? How do I convert these codes to launch from a JFrame instead of a Java Applet?



A simple program where the user can sketch curves and shapes in a
variety of colors on a variety of background colors. The user selects
a drawing color form a pop-up menu at the top of the
applet. If the user clicks "Set Background", the background
color is set to the current drawing color and the drawing
area is filled with that color. If the user clicks "Clear",
the drawing area is just filled with the current background color.

The user selects the shape to draw from another pop-up menu at the
top of the applet. The user can draw free-hand curves, straight
lines, and one of six different types of shapes.

The user's drawing is saved in an off-screen image, which is
used to refresh the screen when repainting. The picture is
lost if the applet changes size, however.

This file defines two classes, SimplePaint3,cl ass, and
class, SimplePaint3$Di splay.class.
*/


import java.awt.*;
import java.awt.event. *;
import javax.swing.*;

public class SimplePaint3 extends JApplet {

// The main applet class simply sets up the applet. Most of the
// work is done in the Display class.

JComboBox colorChoice, figureChoice; // Pop-up menus, defined as instance
// variables so that the Display
// class can see them.

public void init() {

setBackground(C olor.gray);
getContentPane( ).setBackground (Color.gray);

Display canvas = new Display(); // The drawing area.
getContentPane( ).add(canvas,Bo rderLayout.CENT ER);

JPanel buttonBar = new JPanel(); // A panel to hold the buttons.
buttonBar.setBa ckground(Color. gray);
getContentPane( ).add(buttonBar , BorderLayout.SO UTH);

JPanel choiceBar = new JPanel(); // A panel to hole the pop-up menus
choiceBar.setBa ckground(Color. gray);
getContentPane( ).add(choiceBar , BorderLayout.NO RTH);

JButton fill = new JButton("Set Background"); // The first button.
fill.addActionL istener(canvas) ;
buttonBar.add(f ill);

JButton clear = new JButton("Clear" ); // The second button.
clear.addAction Listener(canvas );
buttonBar.add(c lear);

colorChoice = new JComboBox(); // The pop-up menu of colors.
colorChoice.add Item("Black");
colorChoice.add Item("Red");
colorChoice.add Item("Green");
colorChoice.add Item("Blue");
colorChoice.add Item("Cyan");
colorChoice.add Item("Magenta") ;
colorChoice.add Item("Yellow");
colorChoice.add Item("White");
colorChoice.set Background(Colo r.white);
choiceBar.add(c olorChoice);

figureChoice = new JComboBox(); // The pop-up menu of shapes.
figureChoice.ad dItem("Curve");
figureChoice.ad dItem("Straight Line");
figureChoice.ad dItem("Rectangl e");
figureChoice.ad dItem("Oval");
figureChoice.ad dItem("RoundRec t");
figureChoice.ad dItem("Filled Rectangle");
figureChoice.ad dItem("Filled Oval");
figureChoice.ad dItem("Filled RoundRect");
figureChoice.se tBackground(Col or.white);
choiceBar.add(f igureChoice);

} // end init()

public Insets getInsets() {
// Specify how wide a border to leave around the edges of the applet.
return new Insets(3,3,3,3) ;
}



private class Display extends JPanel
implements MouseListener, MouseMotionList ener, ActionListener {

// Nested class Display represents the drawing surface of the
// applet. It lets the user use the mouse to draw colored curves
// and shapes. The current color is specified by the pop-up menu
// colorChoice. The current shape is specified by another pop-up menu,
// figureChoice. (These are instance variables in the main class.)
// The panel also listens for action events from buttons
// named "Clear" and "Set Background". The "Clear" button fills
// the panel with the current background color. The "Set Background"
// button sets the background color to the current drawing color and
// then clears. These buttons are set up in the main class.


private final static int
BLACK = 0,
RED = 1, // Some constants to make
GREEN = 2, // the code more readable.
BLUE = 3, // These numbers code for
CYAN = 4, // the different drawing colors.
MAGENTA = 5,
YELLOW = 6,
WHITE = 7;

private final static int
CURVE = 0,
LINE = 1,
RECT = 2, // Some constants that code
OVAL = 3, // for the different types of
ROUNDRECT = 4, // figure the program can draw.
FILLED_RECT = 5,
FILLED_OVAL = 6,
FILLED_ROUNDREC T = 7;


/* Some variables used for backing up the contents of the panel. */

Image OSI; // The off-screen image (created in checkOSI()).

int widthOfOSI, heightOfOSI; // Current width and height of OSI. These
// are checked against the size of the applet,
// to detect any change in the panel's size.
// If the size has changed, a new OSI is created.
// The picture in the off-screen image is lost
// when that happens.


/* The following variables are used when the user is sketching a
curve while dragging a mouse. */

private int mouseX, mouseY; // The location of the mouse.

private int prevX, prevY; // The previous location of the mouse.

private int startX, startY; // The starting position of the mouse.
// (Not used for drawing curves.)

private boolean dragging; // This is set to true when the user is drawing.

private int figure; // What type of figure is being drawn. This is
// specified by the figureChoice menu.

private Graphics dragGraphics; // A graphics context for the off-screen image,
// to be used while a drag is in progress.

private Color dragColor; // The color that is used for the figure that is
// being drawn.

Display() {
// Constructor. When this component is first created, it is set to
// listen for mouse events and mouse motion events from
// itself. The initial background color is white.
addMouseListene r(this);
addMouseMotionL istener(this);
setBackground(C olor.white);
}


private void drawFigure(Grap hics g, int shape, int x1, int y1, int x2, int y2) {
// This method is called to do ALL drawing in this applet!
// Draws a shape in the graphics context g.
// The shape paramter tells what kind of shape to draw. This
// can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
// FILLED_OVAL, or FILLED_ROUNDREC T. (Note that a CURVE is
// drawn by drawing multiple LINES, so the shape parameter is
// never equal to CURVE.) For a LINE, a line is drawn from
// the point (x1,y1) to (x2,y2). For other shapes, the
// points (x1,y1) and (x2,y2) give two corners of the shape
// (or of a rectangle that contains the shape).
if (shape == LINE) {
// For a line, just draw the line between the two points.
g.drawLine(x1,y 1,x2,y2);
return;
}
int x, y; // Top left corner of rectangle that contains the figure.
int w, h; // Width and height of rectangle that contains the figure.
if (x1 >= x2) { // x2 is left edge
x = x2;
w = x1 - x2;
}
else { // x1 is left edge
x = x1;
w = x2 - x1;
}
if (y1 >= y2) { // y2 is top edge
y = y2;
h = y1 - y2;
}
else { // y1 is top edge.
y = y1;
h = y2 - y1;
}
switch (shape) { // Draw the appropriate figure.
case RECT:
g.drawRect(x, y, w, h);
break;
case OVAL:
g.drawOval(x, y, w, h);
break;
case ROUNDRECT:
g.drawRoundRect (x, y, w, h, 20, 20);
break;
case FILLED_RECT:
g.fillRect(x, y, w, h);
break;
case FILLED_OVAL:
g.fillOval(x, y, w, h);
break;
case FILLED_ROUNDREC T:
g.fillRoundRect (x, y, w, h, 20, 20);
break;
}
}


private void repaintRect(int x1, int y1, int x2, int y2) {
// Call repaint on a rectangle that contains the points (x1,y1)
// and (x2,y2). (Add a 1-pixel border along right and bottom
// edges to allow for the pen overhang when drawing a line.)
int x, y; // top left corner of rectangle that contains the figure
int w, h; // width and height of rectangle that contains the figure
if (x2 >= x1) { // x1 is left edge
x = x1;
w = x2 - x1;
}
else { // x2 is left edge
x = x2;
w = x1 - x2;
}
if (y2 >= y1) { // y1 is top edge
y = y1;
h = y2 - y1;
}
else { // y2 is top edge.
y = y2;
h = y1 - y2;
}
repaint(x,y,w+1 ,h+1);
}


private void checkOSI() {
// This method is responsible for creating the off-screen image.
// It should be called before using the OSI. It will make a new OSI if
// the size of the panel changes.
if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().heigh t) {
// Create the OSI, or make a new one if panel size has changed.
OSI = null; // (If OSI already exists, this frees up the memory.)
OSI = createImage(get Size().width, getSize().heigh t);
widthOfOSI = getSize().width ;
heightOfOSI = getSize().heigh t;
Graphics OSG = OSI.getGraphics (); // Graphics context for drawing to OSI.
OSG.setColor(ge tBackground());
OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
OSG.dispose();
}
}


public void paintComponent( Graphics g) {
// Copy the off-screen image to the screen,
// after checking to make sure it exists. Then,
// if a shape other than CURVE is being drawn,
// draw it on top of the image from the OSI.
checkOSI();
g.drawImage(OSI , 0, 0, this);
if (dragging && figure != CURVE) {
g.setColor(drag Color);
drawFigure(g,fi gure,startX,sta rtY,mouseX,mous eY);
}
}


public void actionPerformed (ActionEvent evt) {
// Respond when the user clicks on a button. The
// command must be either "Clear" or "Set Background".
String command = evt.getActionCo mmand();
checkOSI();
if (command.equals ("Set Background")) {
// Set background color before clearing.
// Change the selected color so it is different
// from the background color.
setBackground(g etCurrentColor( ));
if (colorChoice.ge tSelectedIndex( ) == BLACK)
colorChoice.set SelectedIndex(W HITE);
else
colorChoice.set SelectedIndex(B LACK);
}
Graphics g = OSI.getGraphics ();
g.setColor(getB ackground());
g.fillRect(0,0, getSize().width ,getSize().heig ht);
g.dispose();
repaint();
}


private Color getCurrentColor () {
// Check the colorChoice menu to find the currently
// selected color, and return the appropriate color
// object.
int currentColor = colorChoice.get SelectedIndex() ;
switch (currentColor) {
case BLACK:
return Color.black;
case RED:
return Color.red;
case GREEN:
return Color.green;
case BLUE:
return Color.blue;
case CYAN:
return Color.cyan;
case MAGENTA:
return Color.magenta;
case YELLOW:
return Color.yellow;
default:
return Color.white;
}
}


public void mousePressed(Mo useEvent evt) {
// This is called when the user presses the mouse on the
// panel. This begins a draw operation in which the user
// sketches a curve or draws a shape. (Note that curves
// are handled differently from other shapes. For CURVE,
// a new segment of the curve is drawn each time the user
// moves the mouse. For the other shapes, a "rubber band
// cursor" is used. That is, the figure is drawn between
// the starting point and the current mouse location.)

if (dragging == true) // Ignore mouse presses that occur
return; // when user is already drawing a curve.
// (This can happen if the user presses
// two mouse buttons at the same time.)

prevX = startX = evt.getX(); // Save mouse coordinates.
prevY = startY = evt.getY();

figure = figureChoice.ge tSelectedIndex( );
dragColor = getCurrentColor ();
dragGraphics = OSI.getGraphics ();
dragGraphics.se tColor(dragColo r);

dragging = true; // Start drawing.

} // end mousePressed()


public void mouseReleased(M ouseEvent evt) {
// Called whenever the user releases the mouse button.
// If the user was drawing a shape, we make the shape
// permanent by drawing it to the off-screen image.
if (dragging == false)
return; // Nothing to do because the user isn't drawing.
dragging = false;
mouseX = evt.getX();
mouseY = evt.getY();
if (figure == CURVE) {
// A CURVE is drawn as a series of LINEs
drawFigure(drag Graphics,LINE,p revX,prevY,mous eX,mouseY);
repaintRect(pre vX,prevY,mouseX ,mouseY);
}
else if (figure == LINE) {
repaintRect(sta rtX,startY,prev X,prevY);
if (mouseX != startX || mouseY != startY) {
// Draw the line only if it has non-zero length.
drawFigure(drag Graphics,figure ,startX,startY, mouseX,mouseY);
repaintRect(sta rtX,startY,mous eX,mouseY);
}
}
else {
repaintRect(sta rtX,startY,prev X,prevY);
if (mouseX != startX && mouseY != startY) {
// Draw the shape only if both its height
// and width are both non-zero.
drawFigure(drag Graphics,figure ,startX,startY, mouseX,mouseY);
repaintRect(sta rtX,startY,mous eX,mouseY);
}
}
dragGraphics.di spose();
dragGraphics = null;
}


public void mouseDragged(Mo useEvent evt) {
// Called whenever the user moves the mouse while a mouse button
// is down. If the user is drawing a curve, draw a segment of
// the curve on the off-screen image, and repaint the part
// of the panel that contains the new line segment. Otherwise,
// just call repaint and let paintComponent( ) draw the shape on
// top of the picture in the off-screen image.

if (dragging == false)
return; // Nothing to do because the user isn't drawing.

mouseX = evt.getX(); // x-coordinate of mouse.
mouseY = evt.getY(); // y=coordinate of mouse.

if (figure == CURVE) {
// A CURVE is drawn as a series of LINEs.
drawFigure(drag Graphics,LINE,p revX,prevY,mous eX,mouseY);
repaintRect(pre vX,prevY,mouseX ,mouseY);
}
else {
// Repaint two rectangles: The one that contains the previous
// version of the figure, and the one that will contain the
// new version. The first repaint is necessary to restore
// the picture from the off-screen image in that rectangle.
repaintRect(sta rtX,startY,prev X,prevY);
repaintRect(sta rtX,startY,mous eX,mouseY);
}

prevX = mouseX; // Save coords for the next call to mouseDragged or mouseReleased.
prevY = mouseY;

} // end mouseDragged.


public void mouseEntered(Mo useEvent evt) { } // Some empty routines.
public void mouseExited(Mou seEvent evt) { } // (Required by the MouseListener
public void mouseClicked(Mo useEvent evt) { } // and MouseMotionList ener
public void mouseMoved(Mous eEvent evt) { } // interfaces).


} // end nested class Display


} // end class SimplePaint3
Jun 20 '07 #1
1 6639
r035198x
13,262 MVP
1.) Code tags code tags code tags code tags code tags code tags.
2.) You didn't really have to post all that code
3.) Go for it. You can paint on a Canvas, the constructor would do what's being in the init method e.t.c
Jun 20 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1527
by: wil smiths | last post by:
in applet, "jFrame" cannot be added into applet right? ( I tried it out , cannot work; so i'm using jPanel) in applet/application , there are 3 way program start to flow :: 1. void init() 2. void start() 3. create function inside constructor of class.
0
2702
by: Dominique | last post by:
I am trying to communicate to a prolog server from a java client, however even though the connection is successfully made every time I try to perform QueryExecute I get an error, either Socket closed or null etc. Can anyone help? I am using SICStus prolog. Currently my prolog server looks like: :- write('starting'),nl. :- use_module(library(sockets)). :- use_module(library(prologbeans)). :- use_module(library(charsio)).
0
1230
by: Peter | last post by:
Hi Windows application embed IE control embed applet <--- this is the way i know that emebd a java app into a windows app, but the disadvantage is slow, because applet take a longer time to load than a normal standalone java app. Is there any way to embed a JFrame/Java standalone application(with interface) into a windows app? thanks
1
9651
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej and I was wondering if anyone here would be able to give me some tips for young players such as myself, for learning the language. Is this the best Newsgroup for support with JAVA?
3
15143
by: PieMan2004 | last post by:
Hi, ive been looking for a solid java community to help me when im tearing out my hair :) Basically ive constructed a GUI that has to represent the same look and functions of the typical windows calculator. Ive made 4 classes 2 do this, my reasoning so it was easier to look through( when programming) rather than getting mixed up in my own code! My questions and problems: Ive been messing around with the windows look and feel,...
1
2825
by: twin2003 | last post by:
need help with inventory part 5 here is what I have to do Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item should display. the...
2
5821
by: niharkd | last post by:
Hi, I am trying to run the program below. IT compiles fine and also runs. However, once the jframe loads and the container loads, I dont see any rectangle being drawn in there. Can anyone please help? I am using jGrasp development environment with JDK 5. I am running this on a Windows XP w/ SP2 OS Thanks Nihar /*********************************************************************** Sample Program: Draw a rectangle on a frame window's...
4
4033
by: JNeko | last post by:
hello all, I have tried my hand at this for a couple hours but no luck. I am using JCreator. I used these two links for reference: http://www.tech-recipes.com/java_programming_tips1265.html http://forum.java.sun.com/thread.jspa?threadID=441336&start=15&tstart=0 Here is my situation: trying to turn a 3000 line main class into an applet, or create an applet that calls it. whatever works. in a nut shell, here is the structure:
3
4397
by: notaCons | last post by:
hello im quite newbies in Java Programing so any one can help me. i will be plz.... what am i trying here is try convert The JFrame to JApplet, but when i change the JFrame to JApplet 4 Error come out +++++++++++++++++++++++++error++++++++++++++++++++++++++++ CarRace.java:36: cannot find symbol symbol : method setIconImage(java.awt.Image) location: class CarRace this.setIconImage(carImage);
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.