java lab programs part 1
TRANSCRIPT
-
7/30/2019 Java Lab Programs Part 1
1/37
1. Develop a simple paint-like program that can draw basic graphicalprimitives in different dimensions and colors. Use appropriate menuand buttons.
Shape.javaimport java.awt.Graphics2D;
import java.awt.Color;import java.awt.Paint;import java.awt.Stroke;
public abstract class Shape{
private int x1;private int y1;private Paint paint;private Stroke stroke;
// Class constructor with no argumentpublic Shape (){
x1 = 0;y1 = 0;paint = Color.BLACK;
}
// Class constructor with three argumentpublic Shape( int x1Value , int y1Value , Paint paintValue , Stroke
strokeValue )
{ x1 = x1Value;y1 = y1Value;paint = paintValue;stroke = strokeValue;
}
// Each class that inherites this class must implement this method// because this method is an abstract methodpublic abstract void draw( Graphics2D g2d );
public int getx1(){
return x1;}
public void setx1( int x1Value){
x1 = ( x1Value > 0 ? x1Value : 0 );
-
7/30/2019 Java Lab Programs Part 1
2/37
}
public int gety1(){
return y1;
}public void sety1( int y1Value ){
y1 = ( y1Value > 0 ? y1Value : 0 );}
public Paint getPaint(){
return paint;}
public void setPaint( Paint paintValue ){
paint = paintValue;}
public void setStroke( Stroke strokeValue ){
stroke = strokeValue;}
public Stroke getStroke(){return stroke;
}} // end class Shape
paint.javaimport javax.swing.JFrame;
public class Drawing{
public static void main (String[] args){
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
-
7/30/2019 Java Lab Programs Part 1
3/37
frame.setSize ( 600 , 600 );frame.setVisible ( true );
}} // end class Drawing
DrawPanel.javaimport javax.swing.JPanel;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Color;import java.awt.Paint;import java.awt.GradientPaint;import java.awt.BasicStroke;import java.awt.Stroke;
import java.awt.event.MouseAdapter;import java.awt.event.MouseMotionListener;import java.awt.event.MouseEvent;
public class DrawPanel extends JPanel{
private Shape shapes[]; // Holds the shapes that the user hasdrawn
private Shape currentShape; // Holds the current shape the user isdrawing
private Color color1; // If user uses Gradient , it holds the firstcolorprivate Color color2; // If user uses Gradient , it holds the second
colorprivate Paint currentPaint; // Holds the current paint Patternprivate Stroke currentStroke; // Holds the current stroke patternprivate int lineWidth; // Holds the line width as a parameter for
currentStrokeprivate int dashLength; // Holds the dash lenght as a parameter for
currentStrokeprivate int shapeCount; // Holds the number of shapes the user
has drawnprivate int shapeType; // Holds the current shapeType ( Line ,
Retangle or oval )private int x1 , y1 , x2 , y2; // Holds necessary pointsprivate boolean filledShape; // Holds whether to draw a fill or notprivate boolean useGradient; // Holds whether to use gradient or notprivate boolean dashed; // Holds whether to draw dashed lines or
not
-
7/30/2019 Java Lab Programs Part 1
4/37
private final int LINE = 0, // Constants for identifying how to drawdifferent shapes
RECT = 1,OVAL = 2;
// Class constructorpublic DrawPanel(){
shapes = new Shape[ 100 ];currentShape = null;color1 = Color.BLACK;color2 = Color.BLACK;currentPaint = Color.BLACK;currentStroke = null;lineWidth = 1;
dashLength = 1;shapeCount = 0;shapeType = 0;x1 = 0;y1 = 0;x2 = 0;y2 = 0;filledShape = false;useGradient = false;dashed = false;
// Set the DrawPanel's background colorthis.setBackground ( Color.WHITE );
// Register event listeners for DrawPanelthis.addMouseMotionListener ( new mouseHandler() );this.addMouseListener ( new mouseHandler() );
} // end constructor
public void paintComponent( Graphics g ){
super.paintComponent ( g );
// Cast Graphics object "g" to Graphics2DGraphics2D g2d = ( Graphics2D ) g;
int i = 0;
-
7/30/2019 Java Lab Programs Part 1
5/37
// Draw preceding shapes that the user has drawnwhile ( i < shapeCount ){
shapes[ i ].draw ( g2d );i++;
}// Draw the current shape that user has just drawnif ( currentShape != null )
currentShape.draw ( g2d );
} // end method paintComponent
public void setShapeType( int shapeTypeValue ){
shapeType = shapeTypeValue;
}public void setCurrentPaint( Paint paintValue ){
currentPaint = paintValue;}
public void setStroke( Stroke strokeValue ){
currentStroke = strokeValue;}
public void setFilledShape( boolean fillValue){
filledShape = fillValue;}
public void setUseGradient( boolean useGradientValue ){
useGradient = useGradientValue;}
public void setColor1( Color color1Value ){
color1 = color1Value;}
public void setColor2( Color color2Value ){
color2 = color2Value;
-
7/30/2019 Java Lab Programs Part 1
6/37
}
public void setDashed( boolean dashValue ){
dashed = dashValue;
}public void setLineWidth( int lineWidthValue ){
lineWidth = lineWidthValue;}
public void setDashLength( int dashLenghtValue ){
dashLength = dashLenghtValue;}
public void clearLastShape(){
if ( shapeCount > 0 ){shapeCount--;currentShape=null;
// Invoke method repaint to refresh the DrawPanelthis.repaint ();
}}
public void clearDrawing(){
shapeCount = 0;currentShape = null;
// Invoke method repaint to refresh the DrawPanelthis.repaint ();
}
// Inner class for handling mouse eventsprivate class mouseHandler extends MouseAdapter implements
MouseMotionListener{
public void mousePressed( MouseEvent event ){
// set the shape's first pointif ( event.isAltDown () == false && event.isMetaDown () == false){
-
7/30/2019 Java Lab Programs Part 1
7/37
x1 = event.getX ();y1 = event.getY ();
}}
public void mouseReleased( MouseEvent event ){// Put the drew shape into the array "shapes"if ( event.isAltDown () == false && event.isMetaDown () == false){
shapes [ shapeCount ] = currentShape;shapeCount++;
}}
public void mouseDragged( MouseEvent event )
{ if ( event.isAltDown () == false && event.isMetaDown () == false){
// Set the shape's second pointx2 = event.getX ();y2 = event.getY ();
// Check whether user wants to use gradientif ( useGradient == true )
currentPaint = new GradientPaint( 0 , 0 , color1 , 50 , 50 , color2 ,
true ); elsecurrentPaint = color1;
// Check whether user wants to draw dashed linesif ( dashed == true ) {
float dashLenghtArray[]={ dashLength };currentStroke = new BasicStroke( lineWidth ,
BasicStroke.CAP_ROUND , BasicStroke.JOIN_ROUND , 10 , dashLenghtArray ,0 );
}else
currentStroke = new BasicStroke( lineWidth );
// Create the appropriate shape according to the user selectionswitch ( shapeType ){
case LINE:
-
7/30/2019 Java Lab Programs Part 1
8/37
currentShape = new Line( x1 , y1 , x2 , y2 , currentPaint ,currentStroke);
break;case RECT:
currentShape = new Rectangle( x1 , y1 , x2 , y2 , currentPaint ,
currentStroke , filledShape );break;case OVAL:
currentShape = new Oval( x1 , y1 , x2 , y2 , currentPaint ,currentStroke , filledShape );
break;}
DrawPanel.this.repaint ();
} // end if
} // end method mouseDragged
} // end class MouseHandler} // end class DrawPanel
Line.javaimport java.awt.Graphics2D;import java.awt.Stroke;
import java.awt.Paint;
public class Line extends Shape{
private int x2;private int y2;
// Class constructor with no argumentpublic Line (){
super();x2 = 0;y2 = 0;
}
// Class constructor with five argumentpublic Line( int x1Value , int y1Value , int x2Value , int y2Value , Paint
paintValue , Stroke strokeValue )
-
7/30/2019 Java Lab Programs Part 1
9/37
{super ( x1Value , y1Value , paintValue , strokeValue );x2= x2Value;y2 = y2Value;
}
// Override abstract method "draw" inherited from class "Shape" to draw a linepublic void draw( Graphics2D g2d ){
g2d.setPaint ( super.getPaint () );g2d.setStroke ( super.getStroke () );
g2d.drawLine ( super.getx1 () , super.gety1 () , x2 , y2 );
}} // end class Line
Oval.javaimport java.awt.Graphics2D;import java.awt.Color;import java.awt.Stroke;import java.awt.Paint;
public class Oval extends Shape{
private int width;private int height;private boolean fill;
// Class constructor with no argumentpublic Oval (){
super();width = 1;height = 1;fill = false;
}
// Class constructor with six argumentpublic Oval( int x1Value , int y1Value , int x2Value , int y2Value , Paint
paintValue , Stroke strokeValue , boolean fillValue ){
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ?y1Value : y2Value , paintValue , strokeValue );
-
7/30/2019 Java Lab Programs Part 1
10/37
width = Math.abs ( x1Value - x2Value );height = Math.abs ( y1Value - y2Value );fill = fillValue;
}
// Override abstract method "draw" inherited from class "Shape" to draw anovalpublic void draw ( Graphics2D g2d ){
g2d.setPaint ( super.getPaint () );g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillOval ( super.getx1 () , super.gety1 () , width , height );else
g2d.drawOval ( super.getx1 () , super.gety1 () , width , height );
}} // end class Oval
DrawFrame.javaimport javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JButton;
import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.JComboBox;import javax.swing.JCheckBox;import javax.swing.JColorChooser;import javax.swing.JOptionPane;import java.awt.Color;import java.awt.FlowLayout;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.ItemListener;import java.awt.event.ItemEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;
public class DrawFrame extends JFrame{
-
7/30/2019 Java Lab Programs Part 1
11/37
private DrawPanel drawPanel;private JPanel panel1;private JPanel panel2;private JPanel panel3;private JButton undoButton;
private JButton clearButton;private JButton firstColorButton;private JButton secondColorButton;private JComboBox shapeComboBox;private JCheckBox fillCheckBox;private JCheckBox gradientCheckBox;private JCheckBox dashCheckBox;private JLabel shapesLabel;private JLabel widthLabel;private JLabel lengthLabel;private JTextField widthTextField;
private JTextField dashLengthTextField;private final String shapeNames[] = { "Line" , "Rectangle" ,"Oval" };
// Class constructorpublic DrawFrame (){
// Set the title of JFramesetTitle ( "Drawing Application" );
// Create a JPanel as a container for GUI components in first row
panel1 = new JPanel();// Set the layout of panel1panel1.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel as a container for GUI components in second rowpanel2 = new JPanel();
// Set the layout of panel2panel2.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel to hold panel1 , panel2 and panel3panel3 = new JPanel();
// Set the layout of panel4panel3.setLayout ( new GridLayout( 2,1,0,0) );
// Create button "Undo" and add it to the panelundoButton = new JButton();
-
7/30/2019 Java Lab Programs Part 1
12/37
undoButton.setText( "Undo" );undoButton.addActionListener (
// Create and register an ActionListenernew ActionListener()
{
public void actionPerformed( ActionEvent event ){drawPanel.clearLastShape ();
}}
);panel1.add ( undoButton );
// Create button "Clear" and add it to panel1clearButton = new JButton();
clearButton.setText( "Clear" );clearButton.addActionListener (// Create and register an ActionListenernew ActionListener()
{public void actionPerformed( ActionEvent event ){
drawPanel.clearDrawing ();}
});
panel1.add ( clearButton );
// Create label "shapesLabel" and add it to panel1shapesLabel = new JLabel();shapesLabel.setText ( "Shapes:" );panel1.add ( shapesLabel );
// Create a combobox that contains shape names and add it to panel1shapeComboBox = new JComboBox( shapeNames);shapeComboBox.setMaximumRowCount ( 3 );shapeComboBox.addItemListener (
// Create and register an ItemLsitenernew ItemListener(){
public void itemStateChanged( ItemEvent event ){
if ( event.getStateChange () == ItemEvent.SELECTED )drawPanel.setShapeType ( shapeComboBox.getSelectedIndex
() );
-
7/30/2019 Java Lab Programs Part 1
13/37
}}
);panel1.add ( shapeComboBox );
// Create checkbox "fillCheckBox" and add it to panel1fillCheckBox = new JCheckBox();fillCheckBox.setText ( "Filled" );fillCheckBox.addItemListener (
// Create and register an ItemListenernew ItemListener()
{public void itemStateChanged( ItemEvent event ){
drawPanel.setFilledShape ( fillCheckBox.isSelected () );
}}
);panel1.add ( fillCheckBox );
// Create checkbox "gradientCheckBox" and add it to panel2gradientCheckBox = new JCheckBox();gradientCheckBox.setText ( "Use Gradient" );gradientCheckBox.addItemListener (
// Create and register an ItemListener
new ItemListener(){public void itemStateChanged( ItemEvent event ){
drawPanel.setUseGradient ( gradientCheckBox.isSelected () );}
});panel2.add ( gradientCheckBox );
// Create button "firstColor" and add it to panel2firstColorButton = new JButton();firstColorButton.setText ( "1st Color..." );firstColorButton.addActionListener (
// Create and register an ActionListenernew ActionListener()
{public void actionPerformed( ActionEvent event ){
-
7/30/2019 Java Lab Programs Part 1
14/37
Color color = Color.BLACK;
color = JColorChooser.showDialog ( null , "Color Chooser" , color);
if ( color == null)color = color.BLACK;
drawPanel.setColor1 ( color );}
});panel2.add ( firstColorButton );
// Create button "secondColor" and add it to panel2secondColorButton = new JButton();
secondColorButton.setText ( "2nd Color..." );secondColorButton.addActionListener (// Create and register an ActionListenernew ActionListener()
{public void actionPerformed( ActionEvent event ){
Color color = Color.BLACK;
color = JColorChooser.showDialog ( null , "Color Chooser" , color);
if ( color == null)color = color.BLACK;
drawPanel.setColor2 ( color );
}}
);panel2.add ( secondColorButton );
// Create label "widthLabel" and set its propertieswidthLabel = new JLabel();widthLabel.setText ( "Line width:" );panel2.add ( widthLabel );
// Create text field "widthTextField" and set its propertieswidthTextField = new JTextField();widthTextField.addKeyListener(
// Create and register an KeyListener
-
7/30/2019 Java Lab Programs Part 1
15/37
new KeyAdapter(){
public void keyReleased( KeyEvent e){
int lineWidth;
try{
lineWidth = Integer.parseInt ( widthTextField.getText () );
if ( lineWidth < 1 || lineWidth > 20 )throw new NumberFormatException();
drawPanel.setLineWidth ( lineWidth );
}catch ( NumberFormatException exception )
{ JOptionPane.showMessageDialog( null , "Please enter aninteger between 1 to 20" , "Error" , JOptionPane.INFORMATION_MESSAGE );
widthTextField.setText( "" );}
}}
);widthTextField.setColumns ( 2 );panel2.add ( widthTextField );
// create label "lenghtLabel" and set its propertieslengthLabel = new JLabel();lengthLabel.setText ( "Dash length:" );panel2.add ( lengthLabel );
// Create text field "dashLenghtTextField" and set its propertiesdashLengthTextField = new JTextField();dashLengthTextField.setColumns ( 2 );dashLengthTextField.addKeyListener(
// Create and register an KeyListenernew KeyAdapter(){
public void keyReleased( KeyEvent e){
int dashLength;
try{
-
7/30/2019 Java Lab Programs Part 1
16/37
dashLength = Integer.parseInt ( dashLengthTextField.getText ());
if ( dashLength < 1 || dashLength > 50 )throw new NumberFormatException();
drawPanel.setDashLength ( dashLength );}catch ( NumberFormatException exception ){
JOptionPane.showMessageDialog( null , "Please enter aninteger between 1 to 50" , "Error" , JOptionPane.INFORMATION_MESSAGE );
dashLengthTextField.setText( "" );}
}}
);panel2.add ( dashLengthTextField );
// Create check box "dashCheckBox" and set its propertiesdashCheckBox = new JCheckBox();dashCheckBox.setText ( "Dashed" );dashCheckBox.addItemListener (
// Create and register an ItemLitenernew ItemListener(){
public void itemStateChanged( ItemEvent event )
{ drawPanel.setDashed ( dashCheckBox.isSelected () );}
});panel2.add ( dashCheckBox );
// Add panel1 to panel3panel3.add ( panel1 );
// add panel2 to panel3panel3.add ( panel2 );
// Add panel3 to the south region of JFramethis.add ( panel3 , BorderLayout.NORTH );
// Create an object of type DrawPaneldrawPanel = new DrawPanel();
-
7/30/2019 Java Lab Programs Part 1
17/37
// Add "DrawPanel" object to JFramethis.add ( drawPanel );
} // end constructor
} // end class DrawFrame
Rectangle.javaimport java.awt.Graphics2D;import java.awt.Color;import java.awt.Stroke;import java.awt.Paint;
public class Rectangle extends Shape{
private int width;private int height;private boolean fill;
// Class constructor with no argumentpublic Rectangle (){
super();
width = 1;height = 1;fill = false;
}
// Class constructor with six argumentpublic Rectangle( int x1Value , int y1Value , int x2Value , int y2Value , Paint
paintValue , Stroke strokeValue , boolean fillValue ){
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ?y1Value : y2Value , paintValue , strokeValue );
width = Math.abs ( x1Value - x2Value );height = Math.abs ( y1Value - y2Value );fill = fillValue;
}
// Override abstract method "draw" inherited from class "Shape" to draw arectangle
public void draw ( Graphics2D g2d )
-
7/30/2019 Java Lab Programs Part 1
18/37
{g2d.setPaint ( super.getPaint () );g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillRect ( super.getx1 () , super.gety1 () , width , height );elseg2d.drawRect ( super.getx1 () , super.gety1 () , width , height );
}} // end class Rectangle
2. Develop a scientific calculator using even-driven programmingparadigm of Java.
//Scientific Calculatorimport java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.Cursor;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.GridLayout;
import java.awt.Insets;import java.awt.Toolkit;
import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.ButtonGroup;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JRadioButton;
-
7/30/2019 Java Lab Programs Part 1
19/37
import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.WindowConstants;import javax.swing.border.EmptyBorder;
public class Calc extends JFrame implementsActionListener,MouseListener //,KeyListener{
private JButtonjb_one,jb_two,jb_three,jb_four,jb_five,jb_six,jb_seven,jb_eight,jb_nine,jb_zero;
private JButton jb_plus,jb_minus,jb_divide,jb_multiply;private JButton jb_sin,jb_cos,jb_tan,jb_asin,jb_acos,jb_atan,jb_pie,jb_E;private JButton
jb_decimalpoint,jb_equalto,jb_fact,jb_power,jb_changesign,jb_reciporcal;
private JButton jb_todeg,jb_torad,jb_round,jb_CA,jb_CE,jb_Backspace;private JRadioButton jrb_deg,jrb_rad;private ButtonGroup jrb_group;private JTextField jtf_display;
private double tempdisplayNum;boolean
plusPressed,minusPressed,mulPressed,divPressed,equalPressed,powerPressed;
/*** This constructor forms GUI and add required Compontents* to listeners.*/public Calc(){
super("Scientic Calculator ( Currently running on JVM Version " +System.getProperty("java.version") + " )");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
-
7/30/2019 Java Lab Programs Part 1
20/37
Calc.this.dispose();System.runFinalization();System.gc();System.exit(0);
}
});
tempdisplayNum = 0;resetAllButton();equalPressed = false;
/** GUI Formation*/JPanel jp_main = new JPanel();jp_main.setLayout(new BorderLayout());
jp_main.setBorder(new EmptyBorder(new Insets(3,5,5,5)));JPanel jp_top = new JPanel();jp_top.setLayout(new BorderLayout());JPanel jp_top_down = new JPanel();jp_top_down.setLayout(new BorderLayout());JPanel jp_top_west = new JPanel();jb_Backspace = new JButton("BackSpace");jp_top_west.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));jp_top_west.add(jb_Backspace);JPanel jp_top_east = new JPanel();jp_top_east.setLayout(new FlowLayout(FlowLayout.RIGHT));
jtf_display = new JTextField();jtf_display.setEditable(false);jtf_display.setHorizontalAlignment( JTextField.RIGHT );
jtf_display.setRequestFocusEnabled(false);jtf_display.setBackground(Color.white);jrb_deg = new JRadioButton("Degrees");jrb_rad = new JRadioButton("Radian");jrb_deg.setSelected(true);jrb_group = new ButtonGroup();jrb_group.add(jrb_deg);jrb_group.add(jrb_rad);jp_top_east.add(jrb_deg);jp_top_east.add(jrb_rad);jp_top_down.add(jp_top_east,BorderLayout.EAST);jp_top_down.add(jp_top_west,BorderLayout.WEST);jp_top.setLayout(new BorderLayout());
jp_top.add(jtf_display,BorderLayout.CENTER);
-
7/30/2019 Java Lab Programs Part 1
21/37
jp_top.add(jp_top_down,BorderLayout.SOUTH);JPanel jp_center = new JPanel();jp_center.setLayout(new GridLayout(5,7,5,5));jb_one = new JButton("1");jb_two = new JButton("2");
jb_three = new JButton("3");jb_four = new JButton("4");jb_five = new JButton("5");jb_six = new JButton("6");jb_seven = new JButton("7");jb_eight = new JButton("8");jb_nine = new JButton("9");jb_zero = new JButton("0");jb_plus = new JButton("+");jb_minus = new JButton("-");jb_divide = new JButton("/");
jb_multiply = new JButton("*");jb_sin = new JButton("Sin");jb_cos = new JButton("Cos");jb_tan = new JButton("Tan");jb_asin = new JButton("aSin");jb_acos = new JButton("aCos");jb_atan = new JButton("aTan");jb_pie = new JButton("PI");jb_E = new JButton("E");jb_decimalpoint = new JButton(".");jb_equalto = new JButton("=");
jb_fact = new JButton("x!");jb_power = new JButton("x^n");jb_changesign = new JButton("+/-");jb_reciporcal = new JButton("1/x");jb_todeg = new JButton("toDeg");jb_torad = new JButton("toRad");jb_round = new JButton("Round");jb_CA = new JButton("CA");jb_CE = new JButton("CE");
/*** Adding Button to Listeners*/jb_one.addActionListener(Calc.this);jb_two.addActionListener(Calc.this);jb_three.addActionListener(Calc.this);jb_four.addActionListener(Calc.this);jb_five.addActionListener(Calc.this);jb_six.addActionListener(Calc.this);
-
7/30/2019 Java Lab Programs Part 1
22/37
jb_seven.addActionListener(Calc.this);jb_eight.addActionListener(Calc.this);jb_nine.addActionListener(Calc.this);jb_zero.addActionListener(Calc.this);jb_plus.addActionListener(Calc.this);
jb_minus.addActionListener(Calc.this);jb_divide.addActionListener(Calc.this);jb_multiply.addActionListener(Calc.this);jb_sin.addActionListener(Calc.this);jb_cos.addActionListener(Calc.this);jb_tan.addActionListener(Calc.this);jb_asin.addActionListener(Calc.this);jb_acos.addActionListener(Calc.this);jb_atan.addActionListener(Calc.this);jb_pie.addActionListener(Calc.this);jb_E.addActionListener(Calc.this);
jb_decimalpoint.addActionListener(Calc.this);jb_equalto.addActionListener(Calc.this);jb_fact.addActionListener(Calc.this);jb_power.addActionListener(Calc.this);jb_changesign.addActionListener(Calc.this);jb_reciporcal.addActionListener(Calc.this);jb_todeg.addActionListener(Calc.this);jb_torad.addActionListener(Calc.this);jb_round.addActionListener(Calc.this);jb_CA.addActionListener(Calc.this);jb_CE.addActionListener(Calc.this);
jb_Backspace.addActionListener(Calc.this);
jp_center.add(jb_one);jp_center.add(jb_two);jp_center.add(jb_three);jp_center.add(jb_multiply);jp_center.add(jb_reciporcal);jp_center.add(jb_sin);jp_center.add(jb_asin);jp_center.add(jb_four);jp_center.add(jb_five);jp_center.add(jb_six);jp_center.add(jb_divide);jp_center.add(jb_power);jp_center.add(jb_cos);jp_center.add(jb_acos);jp_center.add(jb_seven);
-
7/30/2019 Java Lab Programs Part 1
23/37
jp_center.add(jb_eight);jp_center.add(jb_nine);jp_center.add(jb_plus);jp_center.add(jb_changesign);jp_center.add(jb_tan);
jp_center.add(jb_atan);jp_center.add(jb_zero);jp_center.add(jb_decimalpoint);jp_center.add(jb_equalto);jp_center.add(jb_minus);jp_center.add(jb_fact);jp_center.add(jb_pie);jp_center.add(jb_E);jp_center.add(jb_CA);jp_center.add(jb_CE);jp_center.add(jb_round);
jp_center.add(jb_todeg);jp_center.add(jb_torad);
Container cp = this.getContentPane();jp_main.add(jp_top,BorderLayout.NORTH);jp_main.add(jp_center,BorderLayout.CENTER);cp.add(jp_main,BorderLayout.CENTER);setSize(520,250);/* Packing all Commponent, so spaces are left */pack();/* Making Window to appear in Center of Screen */
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();Dimension frameSize = this.getPreferredSize();setLocation(screenSize.width/2 - (frameSize.width/2),screenSize.height/2 -
(frameSize.height/2));setVisible(true);
this.requestFocus();}
/*** This method is used to reset the condition that* No plus,minus,multiply,division or power action is going on* if there is cancel it.*/public void resetAllButton(){
plusPressed = false;minusPressed = false;mulPressed = false;
-
7/30/2019 Java Lab Programs Part 1
24/37
divPressed = false;powerPressed = false;
}
/**
* This method is use to calculate the factorial of* number of double data type*
* @param Double value* @return String value*/public String factorial(double num){int theNum = (int)num;
if (theNum < 1)
{ JOptionPane.showMessageDialog(Calc.this,"Cannot find the factorial ofnumbers less than 1.","Facorial Error",JOptionPane.WARNING_MESSAGE);
return ("0");}else{
for (int i=(theNum -1); i > 1; --i)theNum *= i;return Integer.toString(theNum);
}
}
/*** This is important method where All action takes places*/public void actionPerformed(ActionEvent e){String s = e.getActionCommand();String temptext = jtf_display.getText();boolean decimalPointFound = false;double displayNumber = 0;
/*** Converts String value of jtf_display's to Double value for Calculation*/try{
displayNumber = Double.valueOf(jtf_display.getText()).doubleValue();
-
7/30/2019 Java Lab Programs Part 1
25/37
}catch(NumberFormatException nfe) {}
/*** Checks if equal button is pressed
*/if(equalPressed){jtf_display.setText("");equalPressed = false;
}
if(s.equals("1"))jtf_display.setText(jtf_display.getText()+"1");
if(s.equals("2"))
jtf_display.setText(jtf_display.getText()+"2");if(s.equals("3"))jtf_display.setText(jtf_display.getText()+"3");
if(s.equals("4"))jtf_display.setText(jtf_display.getText()+"4");
if(s.equals("5"))jtf_display.setText(jtf_display.getText()+"5");
if(s.equals("6"))jtf_display.setText(jtf_display.getText()+"6");
if(s.equals("7"))jtf_display.setText(jtf_display.getText()+"7");
if(s.equals("8"))jtf_display.setText(jtf_display.getText()+"8");if(s.equals("9"))jtf_display.setText(jtf_display.getText()+"9");
if(s.equals("0") && !temptext.equals(""))jtf_display.setText(jtf_display.getText()+"0");
if(s.equals("E"))jtf_display.setText(Double.toString(Math.E));
if(s.equals("PI"))jtf_display.setText(Double.toString(Math.PI));
if(s.equals("toDeg"))jtf_display.setText(Double.toString(Math.toDegrees(displayNumber)));
if(s.equals("toRad"))jtf_display.setText(Double.toString(Math.toRadians(displayNumber)));
if(s.equals("CE"))jtf_display.setText("");
-
7/30/2019 Java Lab Programs Part 1
26/37
if(s.equals("CA")){
resetAllButton();jtf_display.setText("");
}
if(s.equals(".")){
for (int i =0; i < temptext.length(); ++i){if(temptext.charAt(i) == '.'){decimalPointFound = true;continue;
}}if(!decimalPointFound && temptext.length()==0)jtf_display.setText("0.");
if(!decimalPointFound && temptext.length()!=0)jtf_display.setText(jtf_display.getText()+".");
}
/*** Calulation of sin,cos etc*/
if(s.equals("Sin")){if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.sin((displayNumber*Math.PI)/180)));
else{jtf_display.setText(Double.toString(Math.sin(displayNumber)));
// decimalPointpressed}
}
if(s.equals("Cos")){if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.cos((displayNumber*Math.PI)/180)))
;else{jtf_display.setText(Double.toString(Math.cos(displayNumber)));
-
7/30/2019 Java Lab Programs Part 1
27/37
// decimalPointpressed}
}
if(s.equals("Tan"))
{if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.tan((displayNumber*Math.PI)/180)));
else{jtf_display.setText(Double.toString(Math.tan(displayNumber)));
// decimalPointpressed}
}
if(s.equals("aSin"))
{if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.asin((displayNumber*Math.PI)/180))
);else{jtf_display.setText(Double.toString(Math.asin(displayNumber)));
// decimalPointpressed}
}
if(s.equals("aCos")){if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.acos((displayNumber*Math.PI)/180))
);else{jtf_display.setText(Double.toString(Math.acos(displayNumber)));
// decimalPointpressed}
}
if(s.equals("aTan")){if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.atan((displayNumber*Math.PI)/180))
);else{
-
7/30/2019 Java Lab Programs Part 1
28/37
jtf_display.setText(Double.toString(Math.atan(displayNumber)));// decimalPointpressed}
}
/*** Calculation of "/""*""+""-"*/if(s.equals("*")){resetAllButton();mulPressed = true;try{tempdisplayNum = displayNumber;
}
catch(NumberFormatException mule){ tempdisplayNum = 0; }jtf_display.setText("");}
if(s.equals("+")){resetAllButton();plusPressed = true;try{
tempdisplayNum = displayNumber;}catch(NumberFormatException pluse){ tempdisplayNum = 0; }
jtf_display.setText("");}
if(s.equals("-")){resetAllButton();minusPressed = true;try{tempdisplayNum = displayNumber;}catch(NumberFormatException sube){ tempdisplayNum = 0; }
jtf_display.setText("");}
-
7/30/2019 Java Lab Programs Part 1
29/37
if(s.equals("/")){resetAllButton();divPressed = true;
try{tempdisplayNum = displayNumber;}catch(NumberFormatException dive){ tempdisplayNum = 0; }
jtf_display.setText("");}
/*** It calculate power
*/if(s.equals("x^n")){powerPressed = true;try{tempdisplayNum = displayNumber;}catch(NumberFormatException dive){ tempdisplayNum = 0; }
jtf_display.setText("");
}
/*** Events after "=" is pressed*/if(s.equals("=")){if(mulPressed)jtf_display.setText(Double.toString(tempdisplayNum*displayNumber));if(plusPressed)jtf_display.setText(Double.toString(tempdisplayNum+displayNumber));if(minusPressed)jtf_display.setText(Double.toString(tempdisplayNum-displayNumber));if(divPressed)jtf_display.setText(Double.toString(tempdisplayNum/displayNumber));if(powerPressed)jtf_display.setText(Double.toString(Math.pow(tempdisplayNum,displayNumber
)));
-
7/30/2019 Java Lab Programs Part 1
30/37
resetAllButton();equalPressed = true;
}
/**
* Events for more functions "1/x""+/-""x!""Round"*/if(s.equals("1/x"))jtf_display.setText(Double.toString(1/displayNumber));if(s.equals("+/-") && displayNumber!=0)jtf_display.setText(Double.toString(-displayNumber));if(s.equals("x!"))jtf_display.setText(factorial(displayNumber));if(s.equals("Round"))jtf_display.setText(Double.toString(Math.round(displayNumber)));
/*** For BackSpace Event*/if(s.equals("BackSpace")){String temptextt = jtf_display.getText();if(!temptextt.equals(""))jtf_display.setText(temptextt.substring(0, temptextt.length() - 1));}
}
public void mouseClicked(MouseEvent me){}
public void mouseEntered(MouseEvent me){
}
public void mouseExited(MouseEvent me){
}
public void mouseReleased(MouseEvent me) {}public void mousePressed(MouseEvent me) {}
-
7/30/2019 Java Lab Programs Part 1
31/37
public static void main(String args[]){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}
new Calc();}
}
3. Develop a template for linked-list class along with its methods in Java.import java.util.*;
public class LinkedListExample{
public static voidmain(String[] args) {
System.out.println("Linked List Example!");
LinkedList list = new LinkedList();
int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
int size;
Iterator iterator;
//Adding data in the list
list.add(num1);
list.add(num2);
list.add(num3);
list.add(num4);
size = list.size(); System.out.print( "Linked list data: ");
//Create a iterator
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
//Check list empty or not
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
System.out.println("Adding data at 1st location: 55");
//Adding first
list.addFirst(55);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
-
7/30/2019 Java Lab Programs Part 1
32/37
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at last location: 66");
//Adding last or append
list.addLast(66);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at 3rd location: 55");
//Adding data at 3rd position
list.add(2,99);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println(); System.out.println("Now the size of list: " + list.size());
//Retrieve first data
System.out.println("First data: " + list.getFirst());
//Retrieve lst data
System.out.println("Last data: " + list.getLast());
//Retrieve specific data
System.out.println("Data at 4th position: " + list.get(3));
//Remove first
int first = list.removeFirst();
System.out.println("Data removed from 1st location: " + first);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove last
int last = list.removeLast();
System.out.println("Data removed from last location: " + last);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
} System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove 2nd data
int second = list.remove(1);
System.out.println("Data removed from 2nd location: " + second);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
-
7/30/2019 Java Lab Programs Part 1
33/37
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove all
list.clear();
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
}
}
4. Design a thread-safe implementation of Queue class. Write a multi-threaded producer-consumer application that uses this Queue class.
class Q {
int n;boolean valueSet = false;
synchronized int get() {
if(!valueSet)try {
wait();
} catch(InterruptedException e) {System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);valueSet = false;
notify();
return n;
}synchronized void put(int n) {
if(valueSet)
try {wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}this.n = n;
valueSet = true;
System.out.println("Put: " + n);notify();
}
}
-
7/30/2019 Java Lab Programs Part 1
34/37
class Producer implements Runnable {
Q q;
Producer(Q q) {this.q = q;
new Thread(this, "Producer").start();
}public void run() {
int i = 0;
while(true) {q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {while(true) {
q.get();
}}
}
class PCFixed {public static void main(String args[]) {Q q = new Q();
new Producer(q);
new Consumer(q);System.out.println("Press Control-C to stop.");
}
}
5. Write a multi-threaded Java program to print all numbers below 100,000that are both prime and fibonacci number (some examples are 2, 3, 5,13, etc.). Design a thread that generates prime numbers below 100,000and writes them into a pipe. Design another thread that generatesfibonacci numbers and writes them to another pipe. The main threadshould read both the pipes to identify numbers common to both.
import java.io.*;import java.util.*;
class MyThread1 extends Thread {
-
7/30/2019 Java Lab Programs Part 1
35/37
private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr, PipedWriter pw) {
this.pr = pr;this.pw = pw;
}
public void run() {
try {
int i;
for (i=1;i
-
7/30/2019 Java Lab Programs Part 1
36/37
public void run() {
try {
int f1, f2 = 1, f3 = 1;for (int i = 1; i
-
7/30/2019 Java Lab Programs Part 1
37/37
}
}
}
OUTPUT:
Prime Numbers:
2
35
7
Fibonacci Numbers:
12
3
5
813
2134
55
Elements common to both lists are:2
3
5