import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import ETextField;
public class AwtCalc extends java.applet.Applet implements ActionListener
{
private Button[] buttons = new Button[19];
private String[] buttonText = { " 1 ", " 2 ", " 3 ", " + ", " - ",
" 4 ", " 5 ", " 6 ", " x ", " / ",
" 7 ", " 8 ", " 9 ", "^ ", "sqrt",
" C ", " 0 ", " . ", " = "};
private ETextField result; // Calculator display screen
private String input = ""; // stores user input
private Label label;
private Color forecolor, // Calculator foreground color
backcolor, // Calculator background color
fieldcolor; // the display screen's color
private Font font,
buttonfont;
private int oper = 0, // stores the integer constants representing
oldoper = 0, // the operators
newoper = 0;
private double answer,
num1 = 0.0,
num2 = 0.0,
num3 = 0.0;
private final int ADD=1, // integer constants representing operators
SUB = 2,
MULT = 3,
DIVI = 4,
POW = 5,
SQRT = 6;
private boolean firstpress = true, //determines first button press
morenums = false, //"" if more numbers are being pressed
equals = false, //"" if equal button has been pressed
clearscreen = false, //clears screen
decnumber = false, //"" if a user entered a float
doubleclick = false; //"" if mouse was doubleclicked
public void init() {
font = new Font( "Courier", Font.ITALIC, 10 );
buttonfont = new Font( "Courier", Font.PLAIN, 12 );
setBackground( Color.lightGray );
//initialize colors
result = new ETextField( 125, 18 );
label = new Label( "AWT Calculator" );
setLayout( new FlowLayout() );
add( result );
add( label );
//initialize and add buttons
for ( int i = 0; i < 19; i++ ) {
buttons[i] = new Button( buttonText[i] );
buttons[i].setFont( buttonfont );
buttons[i].addActionListener( this );
if ( i <= 2 )
add( buttons[i] );
else if ( i >= 3 && i <= 7)
add( buttons[i] );
else if ( i >=8 && i <= 12 )
add( buttons[i] );
else if ( i >= 13 && i <= 17 )
add( buttons[i] );
else
add( buttons[i] );
if ( i == 2 )
add( new Label( " " ) );
else if ( i == 7 )
add( new Label( " " ) );
else if ( i == 12 )
add( new Label( " " ) );
else if ( i == 17 )
add( new Label( " " ) );
}
buttons[15].setForeground( Color.red );
result.setBackground( Color.white );
label.setFont( font );
}
//==============================================================================
// Interface method that determines which button was pressed then determines
// the appropriate action.
//==============================================================================
public void actionPerformed( ActionEvent e )
{
// "if" block is not entered if the button is an operator
if ( e.getSource() != buttons[3] && e.getSource() != buttons[4]
&& e.getSource() != buttons[8] && e.getSource() != buttons[9]
&& e.getSource() != buttons[13] && e.getSource() != buttons[14]
&& e.getSource() != buttons[15] && e.getSource() != buttons[18] ) {
if ( clearscreen ) { // clears screen if user enters number before an
clearScreen(); // operator after pressing equals
clearscreen = false;
}
if ( e.getSource() == buttons[0] ) {
input += "1"; // concoctenate "1" to input
result.setText( input );
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[1] ) {
input += "2"; // concoctenate "2" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[2] ) {
input += "3"; // concoctenate "3" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[5] ) {
input += "4"; // concoctenate "4" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[6] ) {
input += "5"; // concoctenate "5" to input
showAnswer( input );
} // end if
else if ( e.getSource() == buttons[7] ) {
input += "6"; // concoctenate "6" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[10] ) {
input += "7"; // concoctenate "7" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[11] ) {
input += "8"; // concoctenate "8" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[12] ) {
input += "9"; // concoctenate "9" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[16] ) {
input += "0"; // concoctenate "0" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[17] ) {
if ( decnumber == false ) {
decnumber = true;
input += ".0"; // concoctenate "." to input
showAnswer( input );
}
}
} // end if
// check if user entered the addition operator
if ( e.getSource() == buttons[3] ) {
clearscreen = false;
decnumber = false;
oper = ADD; // oper is set to addition
clickCheck( input ); // checks if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end if
// check if user entered the subtraction operator
else if (e.getSource() == buttons[4] ) {
clearscreen = false;
decnumber = false;
oper = SUB; // oper is set to subtraction
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the multiplication operator
else if (e.getSource() == buttons[8] ) {
clearscreen = false;
decnumber = false;
oper = MULT; // oper is set to multiplication
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} //end else if
// check if user entered the divide operator
else if (e.getSource() == buttons[9] ) {
clearscreen = false;
decnumber = false;
oper = DIVI; // oper is set to divide
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the exponential operator
else if ( e.getSource() == buttons[13] ) {
clearscreen = false;
decnumber = false;
oper = POW; // oper is set to exponential
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the square root operator
else if ( e.getSource() == buttons[14] ) {
clearscreen = false;
oper = SQRT; // oper is set to square root
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the clear operator
if (e.getSource() == buttons[15] ) {
clearScreen();
} // end if
// check if user entered the equal operator
if (e.getSource() == buttons[18] ) {
equals = true;
clearscreen = true;
clickCheck( input ); //check if user double-clicked
if ( doubleclick == false )
processNumbers(); //continue to process numbers if
input = Double.toString( answer ); //if no double-click
} // end if
} // end actionPerformed()
//==============================================================================
//Method processNumbers is where processes the numbers inputed by the user
//==============================================================================
public void processNumbers() {
// the program enters this "if" block when an operator is pressed for the
// first time
if ( firstpress ) {
if ( equals ) {
num1 = answer; //answer is stored in num1 if user enters equal operator
equals = false; // equals is set to false to allow additional input
} // end if
else
num1 = Double.valueOf( input ).doubleValue(); // converts a string number to double
oldoper = oper; // store current operator to oldoper
// if operator is square root, calculation and output is done immediately
if ( oper == SQRT ) {
answer = calculate( oldoper, num1, 0.0 );
showAnswer( Double.toString( answer ) );
morenums = true;
}
firstpress = false; // no longer the first operator
} // end if
// "if" block is entered if now more than two numbers are being entered to
// be calculated
else if ( !morenums ) {
num2 = Double.valueOf( input ).doubleValue(); //converts second num to double
answer = calculate( oldoper, num1, num2 ); //calculate num1 and num2 with
showAnswer( Double.toString( answer) ); //the past operator
newoper = oper; //store current operator to
//new oper
if ( !equals )
morenums = true; //tells program that more than two numbers have
else { //entered
morenums = false; //if equal operator is pressed, firstpress
firstpress = true; //returns to true
} // end else
} // end if
// if more than two numbers are being inputted to calculate, this "if" block
// is accessed
else if (morenums) {
if ( equals ) {
newoper = oper;
morenums = false;
firstpress = true; // if equals is pressed set firstpress to false
} // end if
num3 = Double.valueOf( input ).doubleValue();
answer = calculate( newoper, answer, num3 );
showAnswer( Double.toString(answer) );
newoper = oper;
} // end else if
} // end processNumbers()
//==============================================================================
//Method calculate determines which operator was entered and calculates
//two numbers depending on the operator pressed
//==============================================================================
public double calculate( int oper, double number1, double number2 )
{
double answer = 0.0;
switch( oper ) {
case ADD:
answer = number1 + number2;
break;
case SUB:
answer = number1 - number2;
break;
case MULT:
answer = number1 * number2;
break;
case DIVI:
answer = number1 / number2;
break;
case POW:
answer = Math.pow( number1, number2 );
break;
case SQRT:
answer = Math.sqrt( number1 );
break;
} // end switch
return answer;
} // end calculate()
//==============================================================================
//Method showAnswer outputs the results in the calculators displays screen
//==============================================================================
public void showAnswer( String s )
{
double answer;
answer = Double.valueOf(s).doubleValue();
if ( decnumber )
result.setText( Double.toString(answer) );
else
result.setText( s ); //all output are displayed as integers at start
} // end showAnswer
//==============================================================================
//Method clickCheck determines if the user double clicked and returns a boolean
//value. If doubleclick is true, the program ignores the input
//==============================================================================
public boolean clickCheck( String s ) {
if ( s == "" )
doubleclick = true;
else
doubleclick = false;
return doubleclick;
}
//==============================================================================
//Method clearScreen clears calculator display screen and sets variables to
//default.
//==============================================================================
public void clearScreen()
{
oper = 0; // reinitialize variables to default
input = "";
answer = 0;
decnumber = false;
morenums = false;
firstpress = true;
equals = false;
showAnswer( Integer.toString( (int)answer) );
}
public void paint( Graphics g )
{
//draw border
g.drawRect( 0, 0, size().width - 1, size().height - 1 );
g.drawLine( 0, 0, 0, size().height );
}
} // end program
Showing posts with label code. Show all posts
Showing posts with label code. Show all posts
Saturday, 23 July 2011
createting calculator on JAVA using awt classes
Sunday, 26 June 2011
codeing for note pad of java at netbeans
001 | import javax.swing.*; |
002 | import java.awt.*; |
003 | import java.awt.event.*; |
004 | import java.util.Scanner; |
005 | import java.io.*; |
006 |
007 | public class Notepad extends JFrame implements ActionListener { |
008 | private TextArea textArea = new TextArea( "" , 0 , 0 , TextArea.SCROLLBARS_VERTICAL_ONLY); |
009 | private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item |
010 | private Menu file = new Menu(); // our File menu |
011 | // what's going in File? let's see... |
012 | private MenuItem openFile = new MenuItem(); // an open option |
013 | private MenuItem saveFile = new MenuItem(); // a save option |
014 | private MenuItem close = new MenuItem(); // and a close option! |
015 | |
016 | public Notepad() { |
017 | this .setSize( 500 , 300 ); // set the initial size of the window |
018 | this .setTitle( "Java Notepad Tutorial" ); // set the title of the window |
019 | setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed) |
020 | this .textArea.setFont( new Font( "Century Gothic" , Font.BOLD, 12 )); // set a default font for the TextArea |
021 | // this is why we didn't have to worry about the size of the TextArea! |
022 | this .getContentPane().setLayout( new BorderLayout()); // the BorderLayout bit makes it fill it automatically |
023 | this .getContentPane().add(textArea); |
024 |
025 | // add our menu bar into the GUI |
026 | this .setMenuBar( this .menuBar); |
027 | this .menuBar.add( this .file); // we'll configure this later |
028 | |
029 | // first off, the design of the menuBar itself. Pretty simple, all we need to do |
030 | // is add a couple of menus, which will be populated later on |
031 | this .file.setLabel( "File" ); |
032 | |
033 | // now it's time to work with the menu. I'm only going to add a basic File menu |
034 | // but you could add more! |
035 | |
036 | // now we can start working on the content of the menu~ this gets a little repetitive, |
037 | // so please bare with me! |
038 | |
039 | // time for the repetitive stuff. let's add the "Open" option |
040 | this .openFile.setLabel( "Open" ); // set the label of the menu item |
041 | this .openFile.addActionListener( this ); // add an action listener (so we know when it's been clicked |
042 | this .openFile.setShortcut( new MenuShortcut(KeyEvent.VK_O, false )); // set a keyboard shortcut |
043 | this .file.add( this .openFile); // add it to the "File" menu |
044 | |
045 | // and the save... |
046 | this .saveFile.setLabel( "Save" ); |
047 | this .saveFile.addActionListener( this ); |
048 | this .saveFile.setShortcut( new MenuShortcut(KeyEvent.VK_S, false )); |
049 | this .file.add( this .saveFile); |
050 | |
051 | // and finally, the close option |
052 | this .close.setLabel( "Close" ); |
053 | // along with our "CTRL+F4" shortcut to close the window, we also have |
054 | // the default closer, as stated at the beginning of this tutorial. |
055 | // this means that we actually have TWO shortcuts to close: |
056 | // 1) the default close operation (example, Alt+F4 on Windows) |
057 | // 2) CTRL+F4, which we are about to define now: (this one will appear in the label) |
058 | this .close.setShortcut( new MenuShortcut(KeyEvent.VK_F4, false )); |
059 | this .close.addActionListener( this ); |
060 | this .file.add( this .close); |
061 | } |
062 | |
063 | public void actionPerformed (ActionEvent e) { |
064 | // if the source of the event was our "close" option |
065 | if (e.getSource() == this .close) |
066 | this .dispose(); // dispose all resources and close the application |
067 | |
068 | // if the source was the "open" option |
069 | else if (e.getSource() == this .openFile) { |
070 | JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open) |
071 | int option = open.showOpenDialog( this ); // get the option that the user selected (approve or cancel) |
072 | // NOTE: because we are OPENing a file, we call showOpenDialog~ |
073 | // if the user clicked OK, we have "APPROVE_OPTION" |
074 | // so we want to open the file |
075 | if (option == JFileChooser.APPROVE_OPTION) { |
076 | this .textArea.setText( "" ); // clear the TextArea before applying the file contents |
077 | try { |
078 | // create a scanner to read the file (getSelectedFile().getPath() will get the path to the file) |
079 | Scanner scan = new Scanner( new FileReader(open.getSelectedFile().getPath())); |
080 | while (scan.hasNext()) // while there's still something to read |
081 | this .textArea.append(scan.nextLine() + "\n" ); // append the line to the TextArea |
082 | } catch (Exception ex) { // catch any exceptions, and... |
083 | // ...write to the debug console |
084 | System.out.println(ex.getMessage()); |
085 | } |
086 | } |
087 | } |
088 | |
089 | // and lastly, if the source of the event was the "save" option |
090 | else if (e.getSource() == this .saveFile) { |
091 | JFileChooser save = new JFileChooser(); // again, open a file chooser |
092 | int option = save.showSaveDialog( this ); // similar to the open file, only this time we call |
093 | // showSaveDialog instead of showOpenDialog |
094 | // if the user clicked OK (and not cancel) |
095 | if (option == JFileChooser.APPROVE_OPTION) { |
096 | try { |
097 | // create a buffered writer to write to a file |
098 | BufferedWriter out = new BufferedWriter( new FileWriter(save.getSelectedFile().getPath())); |
099 | out.write( this .textArea.getText()); // write the contents of the TextArea to the file |
100 | out.close(); // close the file stream |
101 | } catch (Exception ex) { // again, catch any exceptions and... |
102 | // ...write to the debug console |
103 | System.out.println(ex.getMessage()); |
104 | } |
105 | } |
106 | } |
107 | } |
108 | // the main method, for actually creating our notepad and setting it to visible. |
109 | public static void main(String args[]) { |
110 | Notepad app = new Notepad(); |
111 | app.setVisible( true ); |
112 | } |
113 | } |
Friday, 22 April 2011
jmenu+separator+submenu on java
package menutest;
import javax.swing.JApplet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class NewJApplet extends JApplet {
public void init()
{
JMenuBar mb = new JMenuBar();
JMenu filemenu = new JMenu("Display");
JMenu pullrightmenu = new JMenu("pull right");
filemenu.add("Welcome");
filemenu.addSeparator();
filemenu.add(pullrightmenu); //add submenu
filemenu.add("Exit");
pullrightmenu.add(new JCheckBoxMenuItem("Good Morning!"));
pullrightmenu.add(new JCheckBoxMenuItem("Good Afternoon!"));
pullrightmenu.add(new JCheckBoxMenuItem("Good night!"));
mb.add(filemenu);
setJMenuBar(mb);
}
}
import javax.swing.JApplet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class NewJApplet extends JApplet {
public void init()
{
JMenuBar mb = new JMenuBar();
JMenu filemenu = new JMenu("Display");
JMenu pullrightmenu = new JMenu("pull right");
filemenu.add("Welcome");
filemenu.addSeparator();
filemenu.add(pullrightmenu); //add submenu
filemenu.add("Exit");
pullrightmenu.add(new JCheckBoxMenuItem("Good Morning!"));
pullrightmenu.add(new JCheckBoxMenuItem("Good Afternoon!"));
pullrightmenu.add(new JCheckBoxMenuItem("Good night!"));
mb.add(filemenu);
setJMenuBar(mb);
}
}
menu bar on java
package menubar;
import javax.swing.JApplet;
import javax.swing.JMenuBar;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
public class NewJApplet extends JApplet
{
public void init()
{
JMenuBar mb= new JMenuBar();
JMenu file= new JMenu("File");
JMenu view= new JMenu("view");
JMenu editor= new JMenu("editor");
JMenu imp= new JMenu("import object");
file.add("New project");
file.addSeparator();
file.add(imp);
file.add("New File");
view.add(editor);
view.add("Browser");
editor.add(new JCheckBoxMenuItem("Source"));
imp.add(new JCheckBoxMenuItem("eclipse"));
mb.add(file);
mb.add(view);
setJMenuBar(mb);
}
}
tool tip text on java
JAVA MAIN FILE
--------------------------
package apples;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
tuna obj = new tuna();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(275, 180);
obj.setVisible(true);
}
}
JAVA FILE
----------------
package apples;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class tuna extends JFrame
{
private JLabel item1;
public tuna()
{
super("The Title Bar");
setLayout(new FlowLayout());
item1 = new JLabel("This is a sentnce");
item1.setToolTipText("You have hovred over it");
add(item1);
}
}
--------------------------
package apples;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
tuna obj = new tuna();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(275, 180);
obj.setVisible(true);
}
}
JAVA FILE
----------------
package apples;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class tuna extends JFrame
{
private JLabel item1;
public tuna()
{
super("The Title Bar");
setLayout(new FlowLayout());
item1 = new JLabel("This is a sentnce");
item1.setToolTipText("You have hovred over it");
add(item1);
}
}
radio button on java
JAVA MAIN FILE
-----------------
package radio;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
boss obj = new boss();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(300, 300);
obj.setVisible(true);
}
}
JAVA CLASS FILE
-------------------
package radio;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class boss extends JFrame
{
private JTextField tf;
private Font pf;
private Font bf;
private Font itf;
private Font bif;
private JRadioButton pb;
private JRadioButton bb;
private JRadioButton ib;
private JRadioButton bib;
private ButtonGroup group;
public boss()
{
super("title");
setLayout(new FlowLayout());
tf = new JTextField("Try on me", 25);
tf.setEditable(false);
add(tf);
pb = new JRadioButton("plain", true);
bb = new JRadioButton("bold", false);
ib = new JRadioButton("italic", false);
bib = new JRadioButton("bold and italic", false);
add(pb);
add(bb);
add(ib);
add(bib);
group = new ButtonGroup();
group.add(pb);
group.add(bb);
group.add(ib);
group.add(bib);
pf = new Font("Serif", Font.PLAIN, 14);
bf = new Font("Serif", Font.BOLD, 14);
itf = new Font("Serif", Font.ITALIC, 14);
bif = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
tf.setFont(pf);
pb.addItemListener(new HandlerClass(pf));
bb.addItemListener(new HandlerClass(bf));
ib.addItemListener(new HandlerClass(itf));
bib.addItemListener(new HandlerClass(bif));
}
private class HandlerClass implements ItemListener
{
public Font font;
//set font object get variable font
public HandlerClass(Font f)
{
font = f;
}
//sets the font to the font object that was passed in
public void itemStateChanged(ItemEvent ie)
{
tf.setFont(font);
}
}
}
-----------------
package radio;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
boss obj = new boss();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(300, 300);
obj.setVisible(true);
}
}
JAVA CLASS FILE
-------------------
package radio;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class boss extends JFrame
{
private JTextField tf;
private Font pf;
private Font bf;
private Font itf;
private Font bif;
private JRadioButton pb;
private JRadioButton bb;
private JRadioButton ib;
private JRadioButton bib;
private ButtonGroup group;
public boss()
{
super("title");
setLayout(new FlowLayout());
tf = new JTextField("Try on me", 25);
tf.setEditable(false);
add(tf);
pb = new JRadioButton("plain", true);
bb = new JRadioButton("bold", false);
ib = new JRadioButton("italic", false);
bib = new JRadioButton("bold and italic", false);
add(pb);
add(bb);
add(ib);
add(bib);
group = new ButtonGroup();
group.add(pb);
group.add(bb);
group.add(ib);
group.add(bib);
pf = new Font("Serif", Font.PLAIN, 14);
bf = new Font("Serif", Font.BOLD, 14);
itf = new Font("Serif", Font.ITALIC, 14);
bif = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
tf.setFont(pf);
pb.addItemListener(new HandlerClass(pf));
bb.addItemListener(new HandlerClass(bf));
ib.addItemListener(new HandlerClass(itf));
bib.addItemListener(new HandlerClass(bif));
}
private class HandlerClass implements ItemListener
{
public Font font;
//set font object get variable font
public HandlerClass(Font f)
{
font = f;
}
//sets the font to the font object that was passed in
public void itemStateChanged(ItemEvent ie)
{
tf.setFont(font);
}
}
}
imgage icon on java
package menuitems;
import javax.swing.*;
import java.awt.*;
import javax.swing.JApplet;
public class NewJApplet extends JApplet
{
public void init()
{
Container contentpane = getContentPane();
Icon newicon = new ImageIcon("new1.gif", "New Document");
Icon openicon = new ImageIcon("two.jpg", "Open an existing Document");
JMenuBar mb = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem newitem = new JMenuItem("New", newicon);
JMenuItem openitem = new JMenuItem("Open", openicon);
JMenuItem saveitem = new JMenuItem("Save");
JMenuItem saveasitem = new JMenuItem("Save as..");
JMenuItem exititem = new JMenuItem("Exit", 'x');
filemenu.add(newitem);
filemenu.add(openitem);
filemenu.add(saveitem);
filemenu.add(saveasitem);
filemenu.addSeparator();
filemenu.add(exititem);
mb.add(filemenu);
setJMenuBar(mb);
}
}
import javax.swing.*;
import java.awt.*;
import javax.swing.JApplet;
public class NewJApplet extends JApplet
{
public void init()
{
Container contentpane = getContentPane();
Icon newicon = new ImageIcon("new1.gif", "New Document");
Icon openicon = new ImageIcon("two.jpg", "Open an existing Document");
JMenuBar mb = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem newitem = new JMenuItem("New", newicon);
JMenuItem openitem = new JMenuItem("Open", openicon);
JMenuItem saveitem = new JMenuItem("Save");
JMenuItem saveasitem = new JMenuItem("Save as..");
JMenuItem exititem = new JMenuItem("Exit", 'x');
filemenu.add(newitem);
filemenu.add(openitem);
filemenu.add(saveitem);
filemenu.add(saveasitem);
filemenu.addSeparator();
filemenu.add(exititem);
mb.add(filemenu);
setJMenuBar(mb);
}
}
roll over imeges on java
JAVA MAIN FILE
-----------------
package jbutton;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
button obj = new button();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(400, 400);
obj.setVisible(true);
}
}
JAVA CLASS FILE
-------------------
package jbutton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class button extends JFrame
{
private JButton reg;
private JButton custom;
public button()
{
super("the title");
setLayout(new FlowLayout());
reg = new JButton("reg button");
add(reg);
//Icon b = new ImageIcon(getClass.getResource("a.png"));
//Icon x = new ImageIcon(getClass.getResource("b.png"));
//custom = new JButton("Custom", b);
custom = new JButton("Custom");
//custom.setRolloverIcon(x);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null, String.format("%s", ae.getActionCommand()), "Is my title title", JOptionPane.PLAIN_MESSAGE);
}
}
}
-----------------
package jbutton;
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
button obj = new button();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(400, 400);
obj.setVisible(true);
}
}
JAVA CLASS FILE
-------------------
package jbutton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class button extends JFrame
{
private JButton reg;
private JButton custom;
public button()
{
super("the title");
setLayout(new FlowLayout());
reg = new JButton("reg button");
add(reg);
//Icon b = new ImageIcon(getClass.getResource("a.png"));
//Icon x = new ImageIcon(getClass.getResource("b.png"));
//custom = new JButton("Custom", b);
custom = new JButton("Custom");
//custom.setRolloverIcon(x);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null, String.format("%s", ae.getActionCommand()), "Is my title title", JOptionPane.PLAIN_MESSAGE);
}
}
}
create file on java
package free;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
final Formatter x;
try
{
x = new Formatter("Custom.docx");
System.out.println("You created a file.");
}
catch(Exception e)
{
System.out.println("You get an error");
}
}
}
import java.util.*;
public class Main
{
public static void main(String[] args)
{
final Formatter x;
try
{
x = new Formatter("Custom.docx");
System.out.println("You created a file.");
}
catch(Exception e)
{
System.out.println("You get an error");
}
}
}
check file on java
package check;
import java.io.File;
public class Main {
public static void main(String[] args)
{
File obj = new File("E:\\go\\hideandseek.txt");
if(obj.exists())
{
System.out.println(obj.getName() + " File exists.");
}
else
{
System.out.println(obj.getName() + " File DOES NOT exist.");
}
}
}
import java.io.File;
public class Main {
public static void main(String[] args)
{
File obj = new File("E:\\go\\hideandseek.txt");
if(obj.exists())
{
System.out.println(obj.getName() + " File exists.");
}
else
{
System.out.println(obj.getName() + " File DOES NOT exist.");
}
}
}
Monday, 11 April 2011
RGB mixser on JAVA
import java.applet.*;Back to JAVA-RGB-Mixer
import java.awt.*;
import java.net.*;
class Slider
{
public boolean over, drag, down;
private Rectangle r=new Rectangle();
private Graphics g;
public Color color;
public int x, y, y1, y2, pos, pos_old, height, value;
public Slider(int x, int y, Color color)
{
height=104;
this.x=x;
this.y=y;
pos=y+height/2;
this.color=color;
r.x=x-10;
r.y=pos-5;
r.width=22;
r.height=10;
}
public void reportMouseMove(int x, int y)
{
if(r.inside(x,y))
over=true;
else
over=false;
}
public void reportMouseDown(int x, int y)
{
if(r.inside(x,y))
{
down=true;
y1=y;
pos_old=pos;
}
}
public void reportMouseUp(int x, int y)
{
down=false;
}
public void reportMouseDrag(int x, int y)
{
if(down)
{
drag=true;
y2=y-y1;
pos=y2+pos_old;
if(pos<this.y+2)pos=this.y+2;
if(pos>this.y+height)pos=this.y+height;
r.move(r.x,pos-5);
}
else
drag=false;
}
private void drawSlider()
{
//the slot
g.setColor(Color.darkGray);
g.drawLine(x,y,x,y+height);
g.setColor(Color.gray);
g.drawLine(x-1,y,x-1,y+height);
g.setColor(Color.lightGray.brighter());
g.drawLine(x+1,y,x+1,y+height);
//draw the scale
g.setColor(Color.gray);
for(int i=y+1; i<y+104; i++)
{
if(i%2==0)
{
g.drawLine(x-10,i,x-5,i);
g.drawLine(x+10,i,x+5,i);
}
}
//the slider knob
g.setColor(Color.lightGray);
g.fill3DRect(x-10,pos-6,22,12,true);
g.fill3DRect(x-9,pos-5,20,10,true);
g.setColor(color);
g.fillRect(x-8,pos-1,18,2);
//the value
value=255-(((pos-y-2)/2)*5);
String valuestring=""+value;
//measure the size of the string to center it
Font font=new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fm = g.getFontMetrics(font);
int stringWidth=fm.stringWidth(valuestring);
g.setFont(font);
g.setColor(Color.black);
g.drawString(valuestring, x-stringWidth/2, y-10);
}
public void paint(Graphics gr)
{
g=gr;
drawSlider();
}
public int getVal()
{
return value;
}
}
public class RGBMixer extends Applet
{
Image Buffer;
Graphics gBuffer;
URL url;
int h=35;
Slider sl1=new Slider(180,h,Color.red);
Slider sl2=new Slider(210,h,Color.green);
Slider sl3=new Slider(240,h,Color.blue);
//the hotlink
Rectangle r=new Rectangle(165,150,87,10);
boolean overLink;
public void update(Graphics g)
{
paint(g);
}
public void init()
{
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
try{url=new URL("http://www.programming.de/");}
catch(MalformedURLException mal){}
}
public void drawStuff() {
gBuffer.setColor(Color.lightGray);
gBuffer.fillRect(0,0,size().width,size().height);
gBuffer.draw3DRect(0,0,size().width-1,size().height-1,true);
gBuffer.draw3DRect(4,4,size().width-9,size().height-9,false);
gBuffer.draw3DRect(5,5,size().width-11,size().height-11,true);
gBuffer.draw3DRect(18,38,133,98,false);
sl1.paint(gBuffer);
sl2.paint(gBuffer);
sl3.paint(gBuffer);
Color mixColor=
new Color(sl1.getVal(),sl2.getVal(),sl3.getVal());
gBuffer.setColor(mixColor);
gBuffer.fillRect(20,40,130,95);
String red,green,blue;
red=sl1.getVal()<20?"0"+Integer.toHexString(sl1.getVal()):Integer.toHexString(sl1.getVal());
green=sl2.getVal()<20?"0"+Integer.toHexString(sl2.getVal()):Integer.toHexString(sl2.getVal());
blue=sl3.getVal()<20?"0"+Integer.toHexString(sl3.getVal()):Integer.toHexString(sl3.getVal());
String hex="color=\"#"+red+green+blue+"\"";
Font font=new Font("Helvetica", Font.PLAIN, 12);
gBuffer.setFont(font);
gBuffer.setColor(Color.black);
gBuffer.drawString(hex,45,25);
Font smallFont=new Font("Helvetica", Font.PLAIN, 9);
gBuffer.setFont(smallFont);
gBuffer.setColor(Color.gray);
gBuffer.drawString("©2001 by Johannes Wallroth",20,157);
gBuffer.setColor(Color.blue);
gBuffer.drawString("www.programming.de",165,157);
gBuffer.drawLine(165,158,251,158);
}
public boolean mouseMove(Event evt,int x,int y)
{
sl1.reportMouseMove(x, y);
sl2.reportMouseMove(x, y);
sl3.reportMouseMove(x, y);
if(r.inside(x,y))
overLink=true;
else
overLink=false;
Component ParentComponent = getParent();
while ( ParentComponent != null &&
!(ParentComponent instanceof Frame))
ParentComponent = ParentComponent.getParent();
Frame BrowserFrame = (Frame) ParentComponent;
if(overLink)
BrowserFrame.setCursor(Frame.HAND_CURSOR);
else
BrowserFrame.setCursor(Frame.DEFAULT_CURSOR);
repaint();
return true;
}
public boolean mouseDrag(Event evt,int x,int y)
{
sl1.reportMouseDrag(x, y);
sl2.reportMouseDrag(x, y);
sl3.reportMouseDrag(x, y);
repaint();
return true;
}
public boolean mouseDown(Event evt,int x,int y)
{
sl1.reportMouseDown(x, y);
sl2.reportMouseDown(x, y);
sl3.reportMouseDown(x, y);
if(overLink)
getAppletContext().showDocument(url,"_blank");
repaint();
return true;
}
public boolean mouseUp(Event evt,int x,int y)
{
sl1.reportMouseUp(x, y);
sl2.reportMouseUp(x, y);
sl3.reportMouseUp(x, y);
repaint();
return true;
}
public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
createting calculator on JAVA using awt classes
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import ETextField;
public class AwtCalc extends java.applet.Applet implements ActionListener
{
private Button[] buttons = new Button[19];
private String[] buttonText = { " 1 ", " 2 ", " 3 ", " + ", " - ",
" 4 ", " 5 ", " 6 ", " x ", " / ",
" 7 ", " 8 ", " 9 ", "^ ", "sqrt",
" C ", " 0 ", " . ", " = "};
private ETextField result; // Calculator display screen
private String input = ""; // stores user input
private Label label;
private Color forecolor, // Calculator foreground color
backcolor, // Calculator background color
fieldcolor; // the display screen's color
private Font font,
buttonfont;
private int oper = 0, // stores the integer constants representing
oldoper = 0, // the operators
newoper = 0;
private double answer,
num1 = 0.0,
num2 = 0.0,
num3 = 0.0;
private final int ADD=1, // integer constants representing operators
SUB = 2,
MULT = 3,
DIVI = 4,
POW = 5,
SQRT = 6;
private boolean firstpress = true, //determines first button press
morenums = false, //"" if more numbers are being pressed
equals = false, //"" if equal button has been pressed
clearscreen = false, //clears screen
decnumber = false, //"" if a user entered a float
doubleclick = false; //"" if mouse was doubleclicked
public void init() {
font = new Font( "Courier", Font.ITALIC, 10 );
buttonfont = new Font( "Courier", Font.PLAIN, 12 );
setBackground( Color.lightGray );
//initialize colors
result = new ETextField( 125, 18 );
label = new Label( "AWT Calculator" );
setLayout( new FlowLayout() );
add( result );
add( label );
//initialize and add buttons
for ( int i = 0; i < 19; i++ ) {
buttons[i] = new Button( buttonText[i] );
buttons[i].setFont( buttonfont );
buttons[i].addActionListener( this );
if ( i <= 2 )
add( buttons[i] );
else if ( i >= 3 && i <= 7)
add( buttons[i] );
else if ( i >=8 && i <= 12 )
add( buttons[i] );
else if ( i >= 13 && i <= 17 )
add( buttons[i] );
else
add( buttons[i] );
if ( i == 2 )
add( new Label( " " ) );
else if ( i == 7 )
add( new Label( " " ) );
else if ( i == 12 )
add( new Label( " " ) );
else if ( i == 17 )
add( new Label( " " ) );
}
buttons[15].setForeground( Color.red );
result.setBackground( Color.white );
label.setFont( font );
}
//==============================================================================
// Interface method that determines which button was pressed then determines
// the appropriate action.
//==============================================================================
public void actionPerformed( ActionEvent e )
{
// "if" block is not entered if the button is an operator
if ( e.getSource() != buttons[3] && e.getSource() != buttons[4]
&& e.getSource() != buttons[8] && e.getSource() != buttons[9]
&& e.getSource() != buttons[13] && e.getSource() != buttons[14]
&& e.getSource() != buttons[15] && e.getSource() != buttons[18] ) {
if ( clearscreen ) { // clears screen if user enters number before an
clearScreen(); // operator after pressing equals
clearscreen = false;
}
if ( e.getSource() == buttons[0] ) {
input += "1"; // concoctenate "1" to input
result.setText( input );
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[1] ) {
input += "2"; // concoctenate "2" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[2] ) {
input += "3"; // concoctenate "3" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[5] ) {
input += "4"; // concoctenate "4" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[6] ) {
input += "5"; // concoctenate "5" to input
showAnswer( input );
} // end if
else if ( e.getSource() == buttons[7] ) {
input += "6"; // concoctenate "6" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[10] ) {
input += "7"; // concoctenate "7" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[11] ) {
input += "8"; // concoctenate "8" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[12] ) {
input += "9"; // concoctenate "9" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[16] ) {
input += "0"; // concoctenate "0" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[17] ) {
if ( decnumber == false ) {
decnumber = true;
input += ".0"; // concoctenate "." to input
showAnswer( input );
}
}
} // end if
// check if user entered the addition operator
if ( e.getSource() == buttons[3] ) {
clearscreen = false;
decnumber = false;
oper = ADD; // oper is set to addition
clickCheck( input ); // checks if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end if
// check if user entered the subtraction operator
else if (e.getSource() == buttons[4] ) {
clearscreen = false;
decnumber = false;
oper = SUB; // oper is set to subtraction
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the multiplication operator
else if (e.getSource() == buttons[8] ) {
clearscreen = false;
decnumber = false;
oper = MULT; // oper is set to multiplication
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} //end else if
// check if user entered the divide operator
else if (e.getSource() == buttons[9] ) {
clearscreen = false;
decnumber = false;
oper = DIVI; // oper is set to divide
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the exponential operator
else if ( e.getSource() == buttons[13] ) {
clearscreen = false;
decnumber = false;
oper = POW; // oper is set to exponential
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the square root operator
else if ( e.getSource() == buttons[14] ) {
clearscreen = false;
oper = SQRT; // oper is set to square root
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the clear operator
if (e.getSource() == buttons[15] ) {
clearScreen();
} // end if
// check if user entered the equal operator
if (e.getSource() == buttons[18] ) {
equals = true;
clearscreen = true;
clickCheck( input ); //check if user double-clicked
if ( doubleclick == false )
processNumbers(); //continue to process numbers if
input = Double.toString( answer ); //if no double-click
} // end if
} // end actionPerformed()
//==============================================================================
//Method processNumbers is where processes the numbers inputed by the user
//==============================================================================
public void processNumbers() {
// the program enters this "if" block when an operator is pressed for the
// first time
if ( firstpress ) {
if ( equals ) {
num1 = answer; //answer is stored in num1 if user enters equal operator
equals = false; // equals is set to false to allow additional input
} // end if
else
num1 = Double.valueOf( input ).doubleValue(); // converts a string number to double
oldoper = oper; // store current operator to oldoper
// if operator is square root, calculation and output is done immediately
if ( oper == SQRT ) {
answer = calculate( oldoper, num1, 0.0 );
showAnswer( Double.toString( answer ) );
morenums = true;
}
firstpress = false; // no longer the first operator
} // end if
// "if" block is entered if now more than two numbers are being entered to
// be calculated
else if ( !morenums ) {
num2 = Double.valueOf( input ).doubleValue(); //converts second num to double
answer = calculate( oldoper, num1, num2 ); //calculate num1 and num2 with
showAnswer( Double.toString( answer) ); //the past operator
newoper = oper; //store current operator to
//new oper
if ( !equals )
morenums = true; //tells program that more than two numbers have
else { //entered
morenums = false; //if equal operator is pressed, firstpress
firstpress = true; //returns to true
} // end else
} // end if
// if more than two numbers are being inputted to calculate, this "if" block
// is accessed
else if (morenums) {
if ( equals ) {
newoper = oper;
morenums = false;
firstpress = true; // if equals is pressed set firstpress to false
} // end if
num3 = Double.valueOf( input ).doubleValue();
answer = calculate( newoper, answer, num3 );
showAnswer( Double.toString(answer) );
newoper = oper;
} // end else if
} // end processNumbers()
//==============================================================================
//Method calculate determines which operator was entered and calculates
//two numbers depending on the operator pressed
//==============================================================================
public double calculate( int oper, double number1, double number2 )
{
double answer = 0.0;
switch( oper ) {
case ADD:
answer = number1 + number2;
break;
case SUB:
answer = number1 - number2;
break;
case MULT:
answer = number1 * number2;
break;
case DIVI:
answer = number1 / number2;
break;
case POW:
answer = Math.pow( number1, number2 );
break;
case SQRT:
answer = Math.sqrt( number1 );
break;
} // end switch
return answer;
} // end calculate()
//==============================================================================
//Method showAnswer outputs the results in the calculators displays screen
//==============================================================================
public void showAnswer( String s )
{
double answer;
answer = Double.valueOf(s).doubleValue();
if ( decnumber )
result.setText( Double.toString(answer) );
else
result.setText( s ); //all output are displayed as integers at start
} // end showAnswer
//==============================================================================
//Method clickCheck determines if the user double clicked and returns a boolean
//value. If doubleclick is true, the program ignores the input
//==============================================================================
public boolean clickCheck( String s ) {
if ( s == "" )
doubleclick = true;
else
doubleclick = false;
return doubleclick;
}
//==============================================================================
//Method clearScreen clears calculator display screen and sets variables to
//default.
//==============================================================================
public void clearScreen()
{
oper = 0; // reinitialize variables to default
input = "";
answer = 0;
decnumber = false;
morenums = false;
firstpress = true;
equals = false;
showAnswer( Integer.toString( (int)answer) );
}
public void paint( Graphics g )
{
//draw border
g.drawRect( 0, 0, size().width - 1, size().height - 1 );
g.drawLine( 0, 0, 0, size().height );
}
} // end program
Subscribe to:
Posts (Atom)