Anda di halaman 1dari 26

MAIN FRAME:

/* * This class is a collection of all the programs created in sem 1, working. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author ariellablank */ public class MainFrame extends JFrame{ JMenuBar programMenu; JMenu mathMenu, algorithmMenu, graphicMenu, swapper; JMenuItem drawing, bounce, fact, harmonic, bubbleSort, x_to_y, grade, reverseString, b_to_d, swap_Int, swap_Char ; private private private private private private private private private private private private BouncingBall bouncing; JGui_MousePanel mouse_draw; Grade grades; menuHandler h; Factorial factorial; BubbleSort_GUI bbls; HarmonicNumber harmon; SwapInt int_swap; SwapString string_swap; power pow; ReverseString reverse; BinaryToDecimal bi_to_dem;

public MainFrame() /*here we create the main frame and create a container. We then create a main menu called "program menu", and add this to the container, and place it in the north. Here we declare the two methods: addMenuItems() and addAction() that we later create. We set the size and make it visible. */ { super("Come, look at our programs that we learned in first semester!"); Container c= getContentPane();

programMenu= new JMenuBar(); c.add(programMenu, BorderLayout.NORTH); addMenuItems(); addAction();

setSize(500,500); setVisible(true); } void addMenuItems() /* Here we create the three main Menu buttons: math, algorithms, and graphics. We then assign sub-menus to each of these categories, so grade, harmonics, factorial, binary to decimal and vice versa conversions are all math, drawing is graphics, and swap is algorithm. */ { /*here: create math, algorithm, and graphics menus*/ mathMenu= new JMenu("Math!"); programMenu.add(mathMenu); algorithmMenu= new JMenu("Algorithms!"); programMenu.add(algorithmMenu); graphicMenu= new JMenu("Graphics!"); programMenu.add(graphicMenu); /*here we assign all the math items to the mathMenu*/ fact= new JMenuItem("Factorials!"); mathMenu.add(fact); harmonic= new JMenuItem("N Harmonic!"); mathMenu.add(harmonic); x_to_y= new JMenuItem("X^Y!"); mathMenu.add(x_to_y); b_to_d= new JMenuItem("Binary to Decimal!"); mathMenu.add(b_to_d); /*here we assign all the algorithm items to the algorithmMenu*/ swapper= new JMenu("Swap!");

algorithmMenu.add(swapper); swap_Int= new JMenuItem("Swap Integer!"); swapper.add(swap_Int); swap_Char= new JMenuItem("Swap Characters!"); swapper.add(swap_Char); bubbleSort= new JMenuItem("Bubble Sort!"); algorithmMenu.add(bubbleSort); grade= new JMenuItem("Display Letter Grade!"); algorithmMenu.add(grade); reverseString= new JMenuItem("Reverse a String!"); algorithmMenu.add(reverseString); /*here we assign all of the graphic items to the graphicmenu*/ drawing = new JMenuItem("Mouse Drawing!"); graphicMenu.add(drawing); bounce= new JMenuItem("Bouncing Ball!"); graphicMenu.add(bounce);

} void addAction() { h= new menuHandler(); /*here we add action listeners to all of our items*/ drawing.addActionListener(h); x_to_y.addActionListener(h); grade.addActionListener(h); bounce.addActionListener(h); fact.addActionListener(h); harmonic.addActionListener(h); bubbleSort.addActionListener(h); swap_Int.addActionListener(h); swap_Char.addActionListener(h); reverseString.addActionListener(h); b_to_d.addActionListener(h); } class menuHandler implements ActionListener { /* Here we tell our program how to "listen" and "perform" in reaction to all the actions of the user, and tell it what to do. We call the methods

that need to act according to what buttons are pressed. We first create and action event e, and then for each instance, we tell the program what the input is and what method to use in response to that input. */ public void actionPerformed(ActionEvent e) { if(e.getSource()==drawing) { mouse_draw= new JGui_MousePanel(); } else if(e.getSource()== x_to_y) { power p= new power(); } else if(e.getSource()== grade) { grades= new Grade(); } else if(e.getSource()== fact) { factorial= new Factorial(); } else if(e.getSource()== harmonic) { harmon= new HarmonicNumber(); } else if(e.getSource()== x_to_y) { pow= new power(); } else if(e.getSource()== b_to_d) { bi_to_dem= new BinaryToDecimal(); } else if(e.getSource()== swap_Int) { int_swap= new SwapInt(); } else if(e.getSource()== swap_Char) { string_swap=new SwapString(); } else if(e.getSource()== reverseString) { reverse= new ReverseString(); } else if(e.getSource()== drawing) {

mouse_draw= new JGui_MousePanel(); } else if(e.getSource()== bounce) { bouncing= new BouncingBall(); } else if(e.getSource()== bubbleSort) { bbls= new BubbleSort_GUI(); } } } public static void main(String args[]) { MainFrame M= new MainFrame(); M.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

MATH:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author jonathanwu */ public class BinaryToDecimal extends JFrame{ JTextField txt1, txt2; JButton btn1, btn2; BinaryToDecimal() { super("Binary To Decimal"); setLayout(new FlowLayout()); //----------Input and Output Text Fields--------------------// txt1= new JTextField("Enter Number Here"); txt2= new JTextField("The Result Value displayed here "); txt2.setEditable(false); add(txt1); add(txt2);

//----------------------------------------------------------// //----------Decimal To Binary Components--------------------// btn1= new JButton("Binary --> Decimal"); btn2= new JButton("Decimal --> Binary"); add(btn1); add(btn2); //------------------------------------------------------// //-----------Adding Action Listeners-------------// Action a= new Action(); btn1.addActionListener(a); btn2.addActionListener(a); //-----------------------------------------------// setSize(500,500); setVisible(true); } public String BinToInt(int i) { String result; result = Integer.toBinaryString(i);// method in the Integer class that converts Integer values to Binary return result; } public String IntToBin(String str) { long num = Long.parseLong(str); long rem; while(num > 0) { rem = num % 10; num = num / 10; if(rem != 0 && rem != 1)// checks to see if input is binary { JOptionPane.showMessageDialog(null,"This is not a binary number. /n Please Try again"); } } int i= Integer.parseInt(str,2); String s= "" +i; return s; } class Action implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==btn1)

{ txt2.setText(BinToInt(Integer.parseInt(txt1.getText()))); } else if(e.getSource()==btn2) { txt2.setText(IntToBin(txt1.getText())); } } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author jonathan wu */ public class power extends JFrame{ JTextField X, Y; JLabel answer; double ans; JButton calculate; /* here we create text fields for both the x and y inputs. * we tell these text fields what to display, and then we create a label that * will eventually display the answer, and also a button that, when pressed, * sends the numbers to be evaluated so that x^y can be calculated. We * tell the button do display "calculate", and then give this button an * action listener.*/ power() { super("Calculate Power"); setLayout(new FlowLayout()); X= new JTextField("Enter X value"); Y= new JTextField("Enter Y value"); answer= new JLabel("Answer"); calculate= new JButton("Calculate"); add(X); add(Y); add(calculate);

add(answer); Power p= new Power(); calculate.addActionListener(p); setSize(300,300); setVisible(true); } public void paintComponent(Graphics g){ setBackground(Color.RED); } /*we have a program called "math.pow" that gives us x^y. We call this now, assigning this value to the variable "ans" */ double calc(double x,double y) { double ans= Math.pow(x,y); return ans; } /*calling the method outlined for "calc" to perform, here we tell the * program to parse in the two doubles that are entered in the x and * y text fields, and to do "calc" to them. Then we put the resulting * "answer" into the label that displays x^y. */ class Power implements ActionListener { public void actionPerformed(ActionEvent e) { ans=calc(Double.parseDouble(X.getText()),Double.parseDouble(Y.getText( ))); answer.setText("The answer is: "+ans); } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import javax.swing.*; import java.awt.*;

import java.awt.event.*; /** * * @author michaelrodda * */ public class HarmonicNumber extends JFrame{ private JLabel text; private Container c; private JTextField input; /* * Here we give the label something to display, then create a text field * handler, give the text field something to display, and assign the * handler to it. We then take the container c that we created and add * the label to the south and the text field to the north. We then give * it a size and ensure that it will display. */ public HarmonicNumber(){ super ("Harmonic Number"); text = new JLabel("Answer"); c = getContentPane(); TextFieldHandler h = new TextFieldHandler(); input = new JTextField("Enter Number Here."); input.addActionListener(h); c.add(text, BorderLayout.NORTH); c.add(input, BorderLayout.SOUTH); setSize(200,100); setVisible(true); } /* This is the formula for finding harmonics. We take the variable "result", which we define by default as having the value of 0, and then tell it to * divide 1 by the resulting incrementing number that stops as it * equals the "result" variable. */ public static double findHarmonic(int input) { double result = 0;

for (int i = 1; i <= input; i++) { result += (1/(double) i); } return result; } private class TextFieldHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ String s = ""; int q = 0; double r = 0; if (event.getSource()==input){ s = input.getText(); q = Integer.parseInt(s); r = findHarmonic(q); s = String.valueOf(r); text.setText(s); } } } public static void main(String[] args){ HarmonicNumber app = new HarmonicNumber(); windowHandler wl = new windowHandler(); app.addWindowListener(wl); } /* * this ensures that the program will close without problem */ private static class windowHandler extends WindowAdapter{ public void windowClosing(WindowEvent event){ System.exit(0); } } }

DRAWING:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*;

import javax.swing.*; /** * * @author jonathanwu */ public class BouncingBall extends JFrame{ double delta_x=5,delta_y=5,gravity=0.7; int ball_x=30, ball_y=300, radius=20, speed=20, start_x=30, start_y=30, width=500, height=500 ; BouncingBall() { super("Bouncing Ball");

setSize(612,612); setVisible(true); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.RED); g.drawRect(start_x, start_y, width, height); g.setColor(Color.RED); g.fillOval(ball_x, ball_y, radius, radius); } public void bounceBall() { while(true) { try { Thread.sleep(speed); } catch(InterruptedException e) {} if(ball_x>= (start_x+ width-10)) { delta_x=-delta_x; } else if(ball_x<=(start_x-10)) { delta_x=-delta_x; } if(ball_y>= (start_y+ height-10)) { delta_y=-delta_y; } else if(ball_y<=(start_y-10)) { delta_y=-delta_y;

} ball_x+=delta_x; ball_y+=delta_y; if(delta_y<20) { delta_y+=gravity; gravity+=0.001; }

repaint(); } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author ariellablank * */ public class JGui_MousePanel extends JFrame{ private int xval=-10,yval=-10; /*we create an object m and add a mouse motion listener to it. we then * set the container size and visibility boolean values. */ public JGui_MousePanel(){ super("Mouse Drawing"); MousePainter m = new MousePainter(); addMouseMotionListener(m); setSize(500,500); setVisible(true); }

/*here we set the color of the drawing mouse and give the way in which it * draws a thickness and shape. */ public void paint(Graphics g){ g.setColor(Color.red); g.fillOval(xval, yval, 5, 5); } private class MousePainter extends MouseMotionAdapter{ public void mouseDragged(MouseEvent m_event){ xval=m_event.getX(); yval=m_event.getY(); repaint(); } }

ALGORITHMS:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author ariellablank */ public class BubbleSort { public void bubbleSort(int[] a){ int n=a.length; int temp=a[0]; for (int pass=1; pass<n; pass++){ for (int i=0; i<n-pass; i++){ if (a[i]>a[i+1]){ temp= a[i]; a[i]=a[i+1]; a[i+1] = temp;

} } } } public void bubbleSort(double[] a){ int n=a.length; double temp=a[0]; for (int pass=1; pass<n; pass++){ for (int i=0; i<n-pass; i++){ if (a[i]>a[i+1]){ temp= a[i]; a[i]=a[i+1]; a[i+1] = temp; } } } } public void bubbleSort(char[] a){ int n=a.length; char temp; for (int pass=1; pass<n; pass++){ for (int i=0; i<n-pass; i++){ if (a[i] >a[i+1]){ temp= a[i]; a[i]=a[i+1]; a[i+1] = temp; } } } } public void bubbleSort(String[] ss){ String temp=ss[0]; for (int pass=1; pass<ss.length; pass++){ for (int i=0; i<ss.length-pass; i++){ if ((ss[i].compareTo(ss[i+1]))>0){ temp= ss[i]; ss[i]=ss[i+1]; ss[i+1] = temp; } } } } } class BubbleSort_GUI extends JFrame { JButton Integer, Character, string, Double; JTextField Input; JLabel Output; BubbleSort b= new BubbleSort(); Parser p= new Parser();

String out="",s=""; BubbleSort_GUI() { super("Bubble Sort"); setLayout(new FlowLayout()); Input= new JTextField("Input List here"); Output= new JLabel("Sorted List will be displayed here"); Integer= new JButton("Sort Integer Values"); Character= new JButton("Sort Character Values"); string= new JButton("Sort String Values"); Double = new JButton("Sort Double Values"); add(Input); add(Integer); add(Character); add(string); add(Double); add(Output); Action a= new Action(); Integer.addActionListener(a); Character.addActionListener(a); string.addActionListener(a); Double.addActionListener(a); setSize(500,500); setVisible(true); } class Action implements ActionListener { /*here we give the program four options for what to do: if inputted * array is integers, characters, strings, or doubles. It handles * the other methods written and tells the parser to "parseIn" the * input, to convert it using its respective method, and then tells */ public void actionPerformed(ActionEvent e) { if(e.getSource()== Integer) { s=Input.getText(); p.parseIn(s); p.convertInt(p.array);

b.bubbleSort(p.int_array); out= p.convertInt_String(p.int_array); Output.setText(out); } else if(e.getSource()== Character) { s=Input.getText(); p.parseIn(s); p.convertChar(p.array); b.bubbleSort(p.char_array); out= p.convertChar_String(p.char_array); Output.setText(out); } else if(e.getSource()==string) { s=Input.getText(); p.parseIn(s); b.bubbleSort(p.array); out= p.convertStringArray_String(p.array); Output.setText(out); } else if(e.getSource()== Double) { s=Input.getText(); p.parseIn(s); p.convertDouble(p.array); b.bubbleSort(p.double_array); out= p.convertDouble_String(p.double_array); Output.setText(out); } } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author jonathanwu */ public class ReverseString extends JFrame { JTextField txt1, txt2; String h; /*we have 2 text fields, one that has the original string into which the

* user will input the string he/she so desires, and one that will * display the reversed string. we add these and set texts for them * to display. we assign an action listener, a, to the first text field, * and give it a size and visibility boolean. */ ReverseString() { super("Reverse String"); setLayout(new FlowLayout()); txt1 = new JTextField("Enter String here"); add(txt1); txt2= new JTextField("Reversed String here"); add(txt2); txt2.setEditable(false); Action a= new Action(); txt1.addActionListener(a); setVisible(true); setSize(500,500); } class Action implements ActionListener { /*this tells text field one to get the text, then to send this input * to the method reversestring, and then to set this value to the * second text field. */ public void actionPerformed(ActionEvent e) { h=reverseString(txt1.getText()); txt2.setText(h); } } /*this is the method for reversing the string. string b is first set to * be null, and then it swaps, without attention to values, all the * elements of the string, taking care to handle exceptions and * invalid input values. */ String reverseString(String s) { String b=""; try{ for(int i=s.length()-1; i>=0; i--) { b+=s.charAt(i);

}} catch(StringIndexOutOfBoundsException e){} return b; } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; /** * * @author pratanabanthoon */ public class SwapInt extends JFrame{ public static JTextField textField1, textField2 ; public SwapInt(){ super("swapping integer"); //create container and add both textfields for input and output Container container = getContentPane(); container.setLayout(new FlowLayout()); //textfield for input textField1 = new JTextField(10); container.add(textField1); //textfield for output textField2 = new JTextField(10); container.add(textField2); //call on event handler TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener(handler); textField2.addActionListener(handler); setSize(500, 100); setVisible(true); } public static void main(String[] args){ String i ; String j ; SwapInt application = new SwapInt(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} private void swapping(int i, int j ){ //swapping integer i and j int t=i; i=j; j=t; //instantiate i and j to a and b respectively textField1.setText(i+"") ; textField2.setText(j+"") ;

} private class TextFieldHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ //handle to swapping of integers swapping(Integer.parseInt(textField1.getText()), Integer.parseInt(textField2.getText())); } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; /** * * @author pratanabanthoon */ public class SwapString extends JFrame{ public static JTextField textField1, textField2 ; public static String a, b ; public SwapString(){ super("swapping"); //create container and add both textfields for input and output Container container = getContentPane(); container.setLayout(new FlowLayout()); //textfield for input

textField1 = new JTextField(10); container.add(textField1); //textfield for output textField2 = new JTextField(10); container.add(textField2); //call on event handler TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener(handler); textField2.addActionListener(handler); setSize(500, 100); setVisible(true); } public static void main(String[] args){ String i ; String j ; SwapString application = new SwapString(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void swapping(String i, String j ){ //swapping Strings i and j String t=i; i=j; j=t; //instantiate i and j to a and b respectively Character a = i.charAt(0) ; Character b = j.charAt(0) ; textField1.setText(a+""); textField2.setText(b+"");

} private class TextFieldHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ //handle to swapping of Strings swapping(textField1.getText(), textField2.getText()); } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */

package Showcasing; /** *this is the parser for our bubble sort program. It first takes the string * inputted by the user, counts the number of commas, converts the string * into an array, then converts the string array into the right type, and * finally returns an output which then is fed into our bubble sort program. * @author ariellablank */ public class Parser { public int count=1; public String[] array; public int[] int_array; public double[] double_array; public char[] char_array; public void parseIn(String s){ int element=0; for (int i=0; i<s.length(); i++){// counts number of commas if (s.charAt(i) == ',') count++; } array = new String[count];// makes a new string array for(int i=0; i<count; i++){ String number_string = new String(); try{ while (s.charAt(element) !=','){ number_string +=s.charAt(element); if(element>=s.length()-1) break; element++; }} catch(StringIndexOutOfBoundsException e){} array[i]=number_string.toString(); element++; } } /*The following take the string array and change it into the proper type

* so that it can then be processed, the respective types being: int, * double, and char. */ public void convertInt(String[] ss){ int_array = new int[count]; for(int i=0; i<count; i++){ int_array[i] = Integer.parseInt(array[i]); } } public void convertDouble(String[] ss){ double_array = new double[count]; for(int i=0; i<count; i++){ double_array[i] = Double.parseDouble(array[i]); } } public void convertChar(String[] ss){ char_array = new char[count]; for(int i=0; i<count; i++){ char_array[i] = array[i].charAt(0); } } /* The following methods enable the string, integer, double and char array * values to be outputted in string format, separated by commas. */ public String convertInt_String(int[] int_vals){ String output=""; for(int i=0; i<count; i++){ output+=int_vals[i]+","; } return output; } public String convertDouble_String(double[] Double_vals){ String output=""; for(int i=0; i<count; i++){ output+=Double_vals[i]+","; } return output; } public String convertChar_String(char[] char_vals){ String output=""; for(int i=0; i<count; i++){ output+=char_vals[i]+","; } return output; } public String convertStringArray_String(String[] str_vals){ String output=""; for(int i=0; i<count; i++){ output+=str_vals[i]+","; }

return output; } }

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Factorial JFrame Program * @author michaelrodda */ public class Factorial extends JFrame{ // declared variables for GUI private JLabel text; private Container c; private JTextField input; //constuctor is made public Factorial(){ super ("Factorial of a Number"); text = new JLabel("Answer"); c = getContentPane(); TextFieldHandler h = new TextFieldHandler(); input = new JTextField("Enter Number Here."); input.addActionListener(h); c.add(text, BorderLayout.NORTH); c.add(input, BorderLayout.SOUTH); setSize(200,100); setVisible(true); } //The factorial for the number input is found public static double findFactorial(int input) { double result = 1; for (int i = 1; i <= input; i++) {

result *= ((double)i); } return result; } // event handler is written here and handles the conversion // of the input to the factorial private class TextFieldHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ String s = ""; int q = 0; double r = 0; if (event.getSource()==input){ s = input.getText(); q = Integer.parseInt(s); r = findFactorial(q); s = String.valueOf(r); text.setText(s); } } } //main method public static void main(String[] args){ Factorial app = new Factorial(); windowHandler wl = new windowHandler(); app.addWindowListener(wl); } // window event handler that closes the program if the window is exited private static class windowHandler extends WindowAdapter{ public void windowClosing(WindowEvent event){ System.exit(0); } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Showcasing; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author ariellablank * Here we take the grade that is inputted from the JTextField and, after

* the user presses the button, assign a grade value to it. This is * accomplished through a series of options that we assign through else if * clauses. The output, the letter grade, is then set to the label. */ public class Grade extends JFrame{ JTextField input; JLabel output; JButton btn; int grade; String s= "The letter grade is: ", g; Grade() { super("Display Letter Grade"); setLayout(new FlowLayout()); input= new JTextField("Enter Percentage"); add(input); output= new JLabel("Letter Grade"); add(output); btn= new JButton("Calculate"); add(btn); LetterGrade G= new LetterGrade(); btn.addActionListener(G); setSize(300,200); setVisible(true); } /*Here we give the program specifics on what to do, assigning letter grades * to every possible integer input. */ void findGrade(int x) { if(x>=90) g="A"; else if(x>=80 && x<=90) g="B"; else if(x>=70 && x<=80) g="B"; else if(x>=60 && x<=70) g="B"; else if(x>=50 && x<=60) g="B"; else if(x<50) g="F"; } class LetterGrade implements ActionListener { public void actionPerformed(ActionEvent e) { grade=Integer.parseInt(input.getText()); findGrade(grade);

output.setText(s+g); } } }

Anda mungkin juga menyukai