Re: How to convert java applet to java application

J

Jenny

Hi,

Could you try the code? It does not work.


Hi,

Is that possible to convert a Java Applet Code to a Java
Application
Code
without doing big modification to my existing Java applet code? Please give
me some guides...

Thank you!

No problem. Just add the following code (with your class name
modifications) to your class that extends Applet:

public static void main(String args[])
{
YourAppletClassName applet = new YourAppletClassName();
Frame frame = new Frame("Needs a Title");
frame.addWindowListener(new windowListener());

// set the layout and add the applet
frame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints
();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.anchor = GridBagConstraints.CENTER;
constraints.fill = GridBagConstraints.BOTH;
frame.add(applet, constraints);
frame.pack();
frame.setSize(850, 575);
frame.validate();

// Center the window
Dimension screenSize = Toolkit.getDefaultToolkit
().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width -
frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}


Sent via Deja.com http://www.deja.com/
Before you buy.
 
R

Rusty Angus

Roughly, you got to change "container" from JApplet to JFrame and you have
to set the size of a JFrame and set it to visible. Also there is no JApplet
life cycle methods like init() and start() methods but the Java application
main(String[] args) method.

--
Rusty Angus




Jenny said:
Hi,

Could you try the code? It does not work.


Hi,

Is that possible to convert a Java Applet Code to a Java
Application
Code
without doing big modification to my existing Java applet code? Please give
me some guides...

Thank you!

No problem. Just add the following code (with your class name
modifications) to your class that extends Applet:

public static void main(String args[])
{
YourAppletClassName applet = new YourAppletClassName();
Frame frame = new Frame("Needs a Title");
frame.addWindowListener(new windowListener());

// set the layout and add the applet
frame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints
();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.anchor = GridBagConstraints.CENTER;
constraints.fill = GridBagConstraints.BOTH;
frame.add(applet, constraints);
frame.pack();
frame.setSize(850, 575);
frame.validate();

// Center the window
Dimension screenSize = Toolkit.getDefaultToolkit
().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width -
frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}


Sent via Deja.com http://www.deja.com/
Before you buy.
 
J

John English

Jenny said:
Hi,

Could you try the code? It does not work.

You also need to remember to call init(), start(), stop() and
destroy() for the applet (or at least, those of them that you
have overridden in your applet class), the same way an applet
container would.

Here's an example taken from some code that I wrote many moons
ago (using AWT):

public class MyApplet extends Applet {
public void init () { ... }
public void start() { ... }
public void stop () { ... }

public static void main (String args[]) {
final MyApplet app = new MyApplet();
app.init();
app.start();
Frame f = new Frame("Title");
f.addWindowListener (
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
app.stop();
app.destroy();
System.exit(0);
}
}
);
f.setSize (WIDTH, HEIGHT);
f.add("Center", app);
f.show();
}
}

-----------------------------------------------------------------
John English | mailto:[email protected]
Senior Lecturer | http://www.it.bton.ac.uk/staff/je
School of Computing & MIS | ** NON-PROFIT CD FOR CS STUDENTS **
University of Brighton | -- see http://burks.bton.ac.uk
-----------------------------------------------------------------
 
Joined
May 19, 2008
Messages
2
Reaction score
0
I too need JAppet to be JFrame

For class I was told to change my JApplet to JFrame
I have one week to figure this out, any help would be appreciated.
Code:
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import java.awt.Color.*;  

public class Mortgage20test extends JApplet {
	private String[] terms={"7","15","30"};                                                                   //3 predetermined loans for a 7, 15 and 30 year loan
	private double[] rates={0.0535,0.055,0.0575};                                                    // the interest rate for the 7, 15, and 30 year loan.
	private JLabel amountLabel=new JLabel("Input The Amount of Loan, no commas");          //the text showing the user what area to input the amount of loan
	private JTextField amount=new JTextField();                                                      //this is the area to actually input the loan amount
	private JLabel termLabel=new JLabel("Enter Years of Loan to Pay On, or use the dropdown: ");      //this is the Text shouwing user to input years of loan one wished to obtain
                private JTextField term=new JTextField();                                                           //this is where one would input the amount of years
	private JLabel rateLabel=new JLabel("Select / Input Your Interest rate, eg .055 for 5.5%: ");       //this is the text showing the user to input or select interest rate
	private JTextField rate=new JTextField();                                                            //this is the actual area to input the interest rate one wishes to have
	private JComboBox termList = new JComboBox(terms);                                  //combo box of 3 each pre=determined terms of loans, 7, 15, and 30 year
	private JLabel payLabel=new JLabel("Your Monthly Payment Will Be: ");        //this is the text showing a user that this area will be for the monthly payment.
	private JLabel payment=new JLabel();                                                                //this is the area that will show the user what the payment will be.
	private JButton seven=new JButton("7 years @ 5.35%");
	private JButton fifteen=new JButton("15 years @ 5.55%");
	private JButton thirty=new JButton("30 years @ 5.75%");	
	private JButton calculate=new JButton("Calculate");                                          //this button will start the calculations of the items that have been inputted
	private JButton clear=new JButton("Clear");                                                       //this button will clear the areas for one to start a new calculation
	private JButton exit=new JButton("Exit");                                                            //this button will exit the item
	private JButton print=new JButton("Print");                                                         //added print button 23 June 08, inop at this time
	private JTextArea paymentSchedule=new JTextArea();                                   //this is the frame to show the payment schedule information to the user
	private JScrollPane schedulePane=new JScrollPane(paymentSchedule);     //payment schedule frame, the area to show the payment information
	private Container cp = getContentPane();


	public void init() {
		                                                                                                             // Term list
		termList.setSelectedIndex(0);
		termList.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JComboBox cb = (JComboBox)e.getSource();
				                                                                          // combo box, source drop down box for pre determined 7, 15, and 30 year loan
        		String termYear = (String)cb.getSelectedItem();
        		term.setText(termYear);
        		int index=0;
        		switch (Integer.parseInt(termYear)) {
        			case 7: index=0; break;
        			case 15: index=1; break;
        			case 30: index=2; break;
        		}
        		rate.setText(rates[index]+"");
			}
		});

		                                                                                                                                                                    // The Buttons
		calculate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					                                                                                                                // calculate the payment to be paid monthly
					double p=Double.parseDouble(amount.getText());
					double r=Double.parseDouble(rate.getText())/12;
					double n=Integer.parseInt(term.getText())*12;
					double monthlyPayment=p*Math.pow(1+r,n)*r/(Math.pow(1+r,n)-1);
					DecimalFormat df = new DecimalFormat("$###,###.00");                
					payment.setText(df.format(monthlyPayment));
					                                                                                                                // calculate the details of the loan, principal, interest, balance, etc.
					double principal=p;
					int month;
					StringBuffer buffer=new StringBuffer();
					buffer.append("Month\tAmount\tInterest\tBalance\n");
					for (int i=0; i<n; i++) {
						month=i+1;
						double interest=principal*r;
						double balance=principal+interest-monthlyPayment;
						buffer.append(month+"\t");
						buffer.append(new String(df.format(principal))+"\t");
						buffer.append(new String(df.format(interest))+"\t");
						buffer.append(new String(df.format(balance))+"\n");
						principal=balance;
					}
					paymentSchedule.setText(buffer.toString());
				} catch(Exception ex) {
					System.out.println(ex);
				}
			}
		});
		clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				amount.setText("");
				payment.setText("");
				paymentSchedule.setText("");
			}
		});
		exit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(1);
			}
		});

		JPanel upScreen=new JPanel();                                            //setting up the frame, or pane to display to the user
		upScreen.setLayout(new GridLayout(5,2));
		upScreen.add(amountLabel); upScreen.add(amount);
		upScreen.add(termLabel); upScreen.add(term);
		upScreen.add(new Label()); upScreen.add(termList);
		upScreen.add(rateLabel); upScreen.add(rate);
		upScreen.add(payLabel); upScreen.add(payment);
		JPanel buttons=new JPanel();                                                               //button for a new panel
		buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));    //laying out the box areas
		buttons.add(seven); buttons.add(fifteen); buttons.add(thirty); buttons.add(calculate); buttons.add(clear); buttons.add(exit); 
		seven.setBackground (new Color (255, 255, 255));                       
		seven.setForeground (new Color (255, 0, 0));  
		fifteen.setBackground (new Color (255, 0, 0));                       
		fifteen.setForeground (new Color (255, 255, 255));    
		thirty.setBackground (new Color (0, 0, 0));                       
		thirty.setForeground (new Color (255, 0, 0));                              

		JPanel up=new JPanel();
		up.setLayout(new BoxLayout(up, BoxLayout.Y_AXIS));           //laying out the box areas
		up.add(upScreen); up.add(buttons);
		cp.add(BorderLayout.NORTH, up);                                           //informing where to place the borders shown inside the frame
		cp.add(BorderLayout.CENTER, schedulePane);                    //showing another border, in the pane or frame of where the payment schedule will be shown.
	}

	public static void main(String[] args) {
		JApplet applet = new Mortgage20test();
		JFrame frame = new JFrame("Mortgage Calculator");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(true);                                                       //if I set this to false the user cannot resize the window (or popup) to fit their needs
		frame.getContentPane().add(applet);
		frame.setSize(700,500);                                                         //the full total size of a preset frame  or popup window that the user will be using if the user does not resize it.
		applet.init();
		applet.start();
		frame.setVisible(true);
	}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top