Oops 8 Assignment Notes
Oops 8 Assignment Notes
Oops 8 Assignment Notes
Technology Allahabad
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public Calculator() {
textfield = new JTextField("", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);
ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C","sin","cos","log"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST);
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("");
equalOp = "=";
op.setTotal("");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String displayText = textfield.getText();
if (e.getActionCommand().equals("sin"))
{
textfield.setText("" +
Math.sin(Double.valueOf(displayText).doubleValue()));
}else
if (e.getActionCommand().equals("cos"))
{
textfield.setText("" +
Math.cos(Double.valueOf(displayText).doubleValue()));
}
else
if (e.getActionCommand().equals("log"))
{
textfield.setText("" +
Math.log(Double.valueOf(displayText).doubleValue()));
}
else if (e.getActionCommand().equals("C"))
{
textfield.setText("");
}
else
{
if (number)
{
action();
textfield.setText("");
}
else
{
number = true;
if (equalOp.equals("="))
{
op.setTotal(displayText);
}else
if (equalOp.equals("+"))
{
op.add(displayText);
}
else if (equalOp.equals("-"))
{
op.subtract(displayText);
}
else if (equalOp.equals("*"))
{
op.multiply(displayText);
}
else if (equalOp.equals("/"))
{
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp {
private int total;
public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void
setTotal(String n) {
total =
convertToNumber(n);
}
public void add(String n)
{ total +=
convertToNumber(n);
}
public void
subtract(String n) {
total -=
convertToNumber(n);
}
public void
multiply(String n) {
total *=
convertToNumber(n);
}
public void divide(String
n) { total /=
convertToNumber(n);
}
private int
convertToNumber(String n) {
return Integer.parseInt(n);
}
}
}
class SwingCalculator {
public static void main(String[]
args) {JFrame frame = new
Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
2
import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.*;
class MyFrame
extends JFrame
implements ActionListener {
// Components of the Form
private Container c;
private JLabel title;
private JLabel name;
private JTextField tname;
private JLabel regno;
private JTextField tregno;
private JLabel mno;
private JTextField tmno;
private JLabel email;
private JTextField temail;
private JLabel gender;
private JRadioButton male;
private JRadioButton female;
private ButtonGroup gengp;
private JLabel dob;
private JComboBox date;
private JComboBox month;
private JComboBox year;
private JLabel add;
private JTextArea tadd;
private JCheckBox term;
private JButton sub;
private JButton reset;
private JTextArea tout;
private JLabel res;
private JTextArea resadd;
c = getContentPane();
c.setLayout(null);
setVisible(true);
}
// method actionPerformed()
// to get the action performed
// by the user and act accordingly
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sub) {
if (term.isSelected()) {
String data1;
String data
= "Name : "
+ tname.getText() + "\n"
+ "Registration Number : "
+ tregno.getText() + "\n"
+ "Mobile : "
+ tmno.getText() + "\n"
+ "Email Id : "
+ temail.getText() + "\n";
if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";
// Driver Code
class Registration {
//
Frame
JFrame
f;
//
Constru
try {
// Set metal look and feel
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"
);
// Text component
t = new JTextArea();
// Create a menubar
JMenuBar mb = new JMenuBar();
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);
m2.add(mi4);
m2.add(mi5);
m2.add(mi6);
mc.addActionListener(this);
mb.add(m1);
mb.add(m2);
mb.add(mc);
f.setJMenuBar(mb);
f.add(t);
f.setSize(500, 500);
f.show();
}
// If a button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("cut")) {
t.cut();
}
else if (s.equals("copy")) {
t.copy();
}
else if (s.equals("paste")) {
t.paste();
}
else if (s.equals("Save")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");
if (r == JFileChooser.APPROVE_OPTION) {
try {
// Create a file writer
FileWriter wr = new FileWriter(fi, false);
// Write
w.write(t.getText());
w.flush();
w.close();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
// If the user cancelled the operation
else
JOptionPane.showMessageDialog(f, "the user cancelled the
operation");
}
else if (s.equals("Print")) {
try {
// print the file
t.print();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
else if (s.equals("Open")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");
try {
// String
String s1 = "", sl = "";
// File reader
FileReader fr = new FileReader(fi);
// Buffered reader
BufferedReader br = new BufferedReader(fr);
// Initialize sl
sl = br.readLine();
// Main class
public static void main(String args[])
{
editor e = new editor();
}
}
4
import
java.awt.*;
import
java.awt.event.*;
setLayout(null);
setVisible(true);
setTitle("Tic-
Tac-Toe");
}
add(game_area);
status = new Label("Start the game now...");
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
status.setBackground(Color.CYAN);
status.setText("Game Restarted...");
restart();
}
});
add(status);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}
}
if(sum==3)
{
status.setText("Congrats! Winner is ' X ' Click me to Restart.");
status.setBackground(Color.GREEN);
disableAll();
}
else if(sum==-3)
{
status.setText("Congrats! Winner is ' O ' Click me to Restart.");
status.setBackground(Color.GREEN);
disableAll();
}
else if(check_tie())
{
status.setText("It's a TIE. Click me to Restart.");
status.setBackground(Color.RED);
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Button x = (Button) e.getSource();
if(CrossZero == 1) {
x.setLabel("X");
x.setEnabled(false);
CrossZero *= -1;
}
else
{
x.setLabel("O");
x.setEnabled(false);
CrossZero *= -1;
}
status.setText("");
check_winner();
}
}
5
import // Using AWT's Graphics and
java.awt.*;
import java.awt.event.*;Color
// Using AWT's event classes and listener
interface
import javax.swing.*; // Using Swing's components and containers
/**
* Custom Graphics Example: Using key/button to move a line left or
right.
*/
@SuppressWarnings("seri
al")
public class CGMoveALine extends JFrame {
// Define constants for the various
dimensionspublic static final int
CANVAS_WIDTH = 400; public static final
int CANVAS_HEIGHT = 140;
public static final Color LINE_COLOR =
Color.BLACK; public static final Color
CANVAS_BACKGROUND = Color.CYAN;
// The moving line from (x1, y1) to (x2, y2), initially position at
thecenter
private int x1 = CANVAS_WIDTH
/ 2; private int y1 =
CANVAS_HEIGHT / 8;private int
x2 = x1;
private int y2 = CANVAS_HEIGHT / 8 * 7;
/**
* Define inner class DrawCanvas, which is a JPanel used for custom
drawing.
*/
class DrawCanvas extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(CANVAS_BACKGROUND);
g.setColor(LINE_COLOR);
g.drawLine(x1, y1, x2, y2); // Draw the line
}
}
import
javax.swing.ButtonGroup;
import
javax.swing.ImageIcon;
import
javax.swing.JButton;
import
javax.swing.JColorChooser;
import javax.swing.JFrame;
import
javax.swing.JMenu;
import
javax.swing.JMenuBar;
import
javax.swing.JMenuItem;
import
javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* CHANGE BY S AQEEL : Define a constant for background color, because we
are using it at a lot of places
*/
private static final Color BACKGROUND_COLOR = Color.WHITE;
/**
* CHANGE BY S AQEEL : Also define variables for eraser width and height.
In a more usable implementation you can allow user to change eraser size
*/
private int eraserWidth = 40;
private int eraserHeight = 40;
PaintProgram()
{
/**
* CHANGE BY S AQEEL : Use constant instead of hardcoding
*/
frame.setBackground(BACKGROUND_COLOR);
frame.getContentPane().add(this);
this.add(button1);
this.add(color);
this.add(erase);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
this.add(thin);
this.add(medium);
this.add(thick);
addMouseListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage grid;
Graphics2D gc;
switch (choice)
{
case 1:
check();
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
if (stroke == 0)
gc.setStroke(new BasicStroke(1));
if (stroke == 1)
gc.setStroke(new BasicStroke(3));
if (stroke == 2)
gc.setStroke(new BasicStroke(6));
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
repaint();
Color temp = gc.getColor();
/**
* CHANGE BY S AQEEL : Use constant instead of hardcoding
*/
gc.setColor(BACKGROUND_COLOR);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
break;
case 7:
if (eraser == 1)
{
gc.clearRect(xX1, yY1, w, h);
}
else
{
}
break;
}
}
if (e.getActionCommand().equals("Color"))
{
Color bgColor = JColorChooser.showDialog(this, "Choose Background
Color", getBackground());
if (bgColor != null)
gc.setColor(bgColor);
}
if (e.getActionCommand().equals("About"))
{
System.out.println("About Has Been Pressed");
JFrame about = new JFrame("About");
about.setSize(300, 300);
JButton picture = new JButton(new
ImageIcon("C:/Users/TehRobot/Desktop/Logo.png"));
about.add(picture);
about.setVisible(true);
}
if (e.getActionCommand().equals("Empty Rect"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled Rect"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
}
if (e.getActionCommand().equals("Erase?"))
{
eraser = 1;
choice = 7;
/**
* CHANGE BY S AQEEL : Add mousemotionlistener here.
*/
super.addMouseMotionListener(this);
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
draw();
}
xX1 = evt.getX();
yY1 = evt.getY();
/**
* CHANGE BY S AQEEL : MouseMotionListener functions implemented. Note
this listener is only registered when eraser is selected
*/
public void mouseDragged(MouseEvent me)
{
Color c = gc.getColor();
gc.setColor(BACKGROUND_COLOR);
gc.drawRect(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.fillRect(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.setColor(c);
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
8
SudokuFrame.java
import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.*;
JButton cells[][]=new
JButton[9][9];JButton solve;
JButton
active;
JButton
clear;
JButton
help;
HelpFram
e hf;
Color
activeCellColor
for(int j=0;j<9;j++){
cells[i][j]=new JButton("");
cells[i][j].addActionListener(this);
cells[i][j].addKeyListener(this);
int gridbox=i/3*3 + j/3;
if(gridbox%2==0)
cells[i][j].setBackground(new Color(240,240,220));
else
cells[i][j].setBackground(new Color(200,200,200));
}
hf = new HelpFrame();
hf.setVisible(false);
solve=new JButton("SOLVE");
solve.addActionListener(this);
solve.setPreferredSize(new Dimension(150,30));
solve.setHorizontalAlignment(SwingConstants.CENTER);
solve.setBackground(new Color(200,200,200));
help=new JButton("HELP");
help.addActionListener(this);
help.setPreferredSize(new Dimension(150,30));
help.setHorizontalAlignment(SwingConstants.CENTER);
help.setBackground(new Color(200,200,200));
clear=new JButton("CLEAR");
clear.addActionListener(this);
clear.setPreferredSize(new Dimension(150,30));
clear.setHorizontalAlignment(SwingConstants.CENTER);
clear.setBackground(new Color(200,200,200));
active=cells[0][0];
activeCellColor=active.getBackground();
active.setBackground(new Color(100,100,150));
addWindowListener(new WindowAdapter() {
setResizable(false);
setTitle("SUDOKU");
initialise();
setVisible(true);
}
void initialise(){
JLabel title=new JLabel("SUDOKU PROBLEM
SOLVER",SwingConstants.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 25));
title.setForeground(new Color(100,100,150));
title.setPreferredSize(new Dimension(200,80));
BorderLayout main = new BorderLayout();
this.setLayout(main);
this.add(title,BorderLayout.NORTH);
this.add(gridPanel,BorderLayout.CENTER);
this.add(buttonsPanel,BorderLayout.SOUTH);
}
}
else{
active.setBackground(activeCellColor);
activeCellColor=cell.getBackground();
cell.setBackground(new Color(100,100,150));
active=cell;
}
}
void solveSudoku(){
Sudoku s= new Sudoku();
int value;
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
String text=cells[i][j].getText();
if(text!=""){
value=Integer.parseInt(text);
s.setCell(i,j,value);
}
}
s.gotoNextCell();
s.solveNextCell();
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
value=s.getCell(i,j);
if(s.isFixed(i,j))
cells[i][j].setForeground(new Color(184,134,11));
else
cells[i][j].setForeground(new Color(0,0,0));
cells[i][j].setText(value+"");
}
}
void clearSudoku(){
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
cells[i][j].setText("");
}
}
}
addWindowListener(new WindowAdapter()
{ public void
windowClosing(WindowEvent e) {
setVisible(false);
}
});
}
} Main.java
public class Main {
public Main() {
}
Cell.java
class Cell {
int
value;
Group
row;
Group
column;
Group
grid;
boolean
fixed;
public
Cell(
) {
value
=0;
fixed
=fals
e;
}
void initialise(int
value){
this.value=value
;
}
int
getValu
e(){
return(
value);
}
boolean
isFixed
(){
return
fixed;
}
void setFixed(boolean
fixed){
this.fixed=fixed;
}
void Group.java
assignToRow(Group
class Group {
row){
Cellthis.row=row;
cells[]=new
}
Cell[9];public
void assignToColumn(Group
column){
Group() {
this.column=column;
}
}
void assignToGrid(Group
grid){
void registerCell(Cell cell,int
this.grid=grid;
index){cells[index]=cell;
}
} }
void display(){
for(int i=0;i<9;i++){
System.out.print(cells[i].getValue()+"
");
}
System.out.println("\n");
}
}
Sudoku.java
class Sudoku{
Cell cells[][] =new
Cell[9][9];Group rows[]
=new
Group[9]; Group columns[]
=new Group[9]; Group
grids[] =new
Group[9];
int
rowIndex;
int
columnInd
ex;
public Sudoku(){
rowIndex
=0;
columnIn
dex=-1;
for(int
i=0;i<9;i++)
for(int
j=0;j<9;j++){
cells[i][j]=new Cell();
}
for(int
i=0;i<9;i++){
rows[i]=new
Group();
}
for(int
}
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
rows[i].registerCell(cells[i][j],j);
cells[i][j].assignToRow(rows[i]);
columns[i].registerCell(cells[j][i],j);
cells[i][j].assignToColumn(columns[j]);
grids[i].registerCell(cells[gridrow][gridcol],j);
cells[gridrow][gridcol].assignToGrid(grids[i]);
}
}
void gotoNextCell(){
do{
if(rowIndex==8 && columnIndex==8){
rowIndex=8;
columnIndex=-1;
return;
}
else if(columnIndex==8){
rowIndex=rowIndex+1;
columnIndex=0;
}else{
columnIndex=columnIndex+1;
}
}while(cells[rowIndex][columnIndex].isFixed()==true);
}
void gotoPreviousCell(){
do{
if(rowIndex==0 && columnIndex==0){
rowIndex=0;
columnIndex=-1;
return;
}
else if(columnIndex==0){
rowIndex=rowIndex-1;
columnIndex=8;
}else{
columnIndex=columnIndex-1;
}
}while(cells[rowIndex][columnIndex].isFixed()==true);
}
boolean solveNextCell(){
int value=0;
boolean solved=false;
while(solved==false&&value<9){
value=value+1;
if(cells[rowIndex][columnIndex].setValue(value)==false)
continue;
gotoNextCell();
if(columnIndex!=-1)
solved=solveNextCell();
else
solved=true;
}
if(solved==false){
cells[rowIndex][columnIndex].initialise(0);
gotoPreviousCell();
}
return solved;
}
void display(){
for(int i=0;i<9;i++){
rows[i].display();
}
}
// Change color of O or X
public void actionPerformed(ActionEvent e) {
if (e.getSource()==oButton) {
Color newColor = JColorChooser.showDialog(this, "Choose a new color for
O", oColor);
if (newColor!=null)
oColor=newColor;
}
else if (e.getSource()==xButton) {
Color newColor = JColorChooser.showDialog(this, "Choose a new color for
X", xColor);
if (newColor!=null)
xColor=newColor;
}
board.repaint();
}
public Board() {
addMouseListener(this);
}
// Computer plays X
void putX() {