You are on page 1of 49

Motilal Nehru National Institute of

Technology Allahabad

Computer Science & Engineering Department

Object Oriented Programming Lab


(CS 13201)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calculator extends JFrame {


private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();

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;

private String dates[]


= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" };
private String years[]
= { "1995", "1996", "1997", "1998",
"1999", "2000", "2001", "2002",
"2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };
// constructor, to initialize the components
// with default values.
public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 700);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

c = getContentPane();
c.setLayout(null);

title = new JLabel("Registration Form");


title.setFont(new Font("Arial", Font.PLAIN, 30));
title.setSize(300, 30);
title.setLocation(300, 30);
c.add(title);

name = new JLabel("Name");


name.setFont(new Font("Arial", Font.PLAIN, 20));
name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name);

tname = new JTextField();


tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setSize(190, 20);
tname.setLocation(200, 100);
c.add(tname);

regno = new JLabel("Reg. No.");


regno.setFont(new Font("Arial", Font.PLAIN, 20));
regno.setSize(100, 20);
regno.setLocation(100, 150);
c.add(regno);

tregno = new JTextField();


tregno.setFont(new Font("Arial", Font.PLAIN, 15));
tregno.setSize(190, 20);
tregno.setLocation(200, 150);
c.add(tregno);

mno = new JLabel("Mobile");


mno.setFont(new Font("Arial", Font.PLAIN, 20));
mno.setSize(100, 20);
mno.setLocation(100, 200);
c.add(mno);
tmno = new JTextField();
tmno.setFont(new Font("Arial", Font.PLAIN, 15));
tmno.setSize(150, 20);
tmno.setLocation(200, 200);
c.add(tmno);

email = new JLabel("Email Id");


email.setFont(new Font("Arial", Font.PLAIN, 20));
email.setSize(100, 20);
email.setLocation(100, 250);
c.add(email);

temail = new JTextField();


temail.setFont(new Font("Arial", Font.PLAIN, 15));
temail.setSize(150, 20);
temail.setLocation(200, 250);
c.add(temail);

gender = new JLabel("Gender");


gender.setFont(new Font("Arial", Font.PLAIN, 20));
gender.setSize(100, 20);
gender.setLocation(100, 300);
c.add(gender);

male = new JRadioButton("Male");


male.setFont(new Font("Arial", Font.PLAIN, 15));
male.setSelected(true);
male.setSize(75, 20);
male.setLocation(200, 300);
c.add(male);

female = new JRadioButton("Female");


female.setFont(new Font("Arial", Font.PLAIN, 15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 300);
c.add(female);

gengp = new ButtonGroup();


gengp.add(male);
gengp.add(female);

dob = new JLabel("DOB");


dob.setFont(new Font("Arial", Font.PLAIN, 20));
dob.setSize(100, 20);
dob.setLocation(100, 350);
c.add(dob);
date = new JComboBox(dates);
date.setFont(new Font("Arial", Font.PLAIN, 15));
date.setSize(50, 20);
date.setLocation(200, 350);
c.add(date);

month = new JComboBox(months);


month.setFont(new Font("Arial", Font.PLAIN, 15));
month.setSize(60, 20);
month.setLocation(250, 350);
c.add(month);

year = new JComboBox(years);


year.setFont(new Font("Arial", Font.PLAIN, 15));
year.setSize(60, 20);
year.setLocation(320, 350);
c.add(year);

add = new JLabel("Address");


add.setFont(new Font("Arial", Font.PLAIN, 20));
add.setSize(100, 20);
add.setLocation(100, 400);
c.add(add);

tadd = new JTextArea();


tadd.setFont(new Font("Arial", Font.PLAIN, 15));
tadd.setSize(200, 75);
tadd.setLocation(200, 400);
tadd.setLineWrap(true);
c.add(tadd);

term = new JCheckBox("Accept Terms And Conditions.");


term.setFont(new Font("Arial", Font.PLAIN, 15));
term.setSize(250, 20);
term.setLocation(150, 500);
c.add(term);

sub = new JButton("Submit");


sub.setFont(new Font("Arial", Font.PLAIN, 15));
sub.setSize(100, 20);
sub.setLocation(150, 550);
sub.addActionListener(this);
c.add(sub);

reset = new JButton("Reset");


reset.setFont(new Font("Arial", Font.PLAIN, 15));
reset.setSize(100, 20);
reset.setLocation(270, 550);
reset.addActionListener(this);
c.add(reset);

tout = new JTextArea();


tout.setFont(new Font("Arial", Font.PLAIN, 15));
tout.setSize(300, 400);
tout.setLocation(500, 100);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);

res = new JLabel("");


res.setFont(new Font("Arial", Font.PLAIN, 20));
res.setSize(500, 25);
res.setLocation(100, 500);
c.add(res);

resadd = new JTextArea();


resadd.setFont(new Font("Arial", Font.PLAIN, 15));
resadd.setSize(200, 75);
resadd.setLocation(580, 175);
resadd.setLineWrap(true);
c.add(resadd);

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";

String data3 = "Address : " + tadd.getText();


tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully Done");
}
else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}
}

else if (e.getSource() == reset) {


String def = "";
tname.setText(def);
tadd.setText(def);
tmno.setText(def);
res.setText(def);
tout.setText(def);
term.setSelected(false);
date.setSelectedIndex(0);
month.setSelectedIndex(0);
year.setSelectedIndex(0);
resadd.setText(def);
}
}
}

// Driver Code
class Registration {

public static void main(String[] args) throws Exception


{
MyFrame f = new MyFrame();
}
}
3
import
java.awt.*;
import
javax.swing.*;
import
java.io.*;
import java.awt.event.*;
import
javax.swing.plaf.metal.*;
import
javax.swing.text.*;
class editor extends JFrame implements ActionListener {
// Text
component
JTextArea
t;

//
Frame
JFrame
f;

//
Constru
try {
// Set metal look and feel
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"
);

// Set theme to ocean


MetalLookAndFeel.setCurrentTheme(new OceanTheme());
}
catch (Exception e) {
}

// Text component
t = new JTextArea();

// Create a menubar
JMenuBar mb = new JMenuBar();

// Create amenu for menu


JMenu m1 = new JMenu("File");

// Create menu items


JMenuItem mi1 = new JMenuItem("New");
JMenuItem mi2 = new JMenuItem("Open");
JMenuItem mi3 = new JMenuItem("Save");
JMenuItem mi9 = new JMenuItem("Print");

// Add action listener


mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi9.addActionListener(this);

m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);

// Create amenu for menu


JMenu m2 = new JMenu("Edit");

// Create menu items


JMenuItem mi4 = new JMenuItem("cut");
JMenuItem mi5 = new JMenuItem("copy");
JMenuItem mi6 = new JMenuItem("paste");

// Add action listener


mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);

m2.add(mi4);
m2.add(mi5);
m2.add(mi6);

JMenuItem mc = new JMenuItem("close");

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:");

// Invoke the showsSaveDialog function to show the save dialog


int r = j.showSaveDialog(null);

if (r == JFileChooser.APPROVE_OPTION) {

// Set the label to the path of the selected directory


File fi = new File(j.getSelectedFile().getAbsolutePath());

try {
// Create a file writer
FileWriter wr = new FileWriter(fi, false);

// Create buffered writer to write


BufferedWriter w = new BufferedWriter(wr);

// 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:");

// Invoke the showsOpenDialog function to show the save dialog


int r = j.showOpenDialog(null);

// If the user selects a file


if (r == JFileChooser.APPROVE_OPTION) {
// Set the label to the path of the selected directory
File fi = new File(j.getSelectedFile().getAbsolutePath());

try {
// String
String s1 = "", sl = "";

// File reader
FileReader fr = new FileReader(fi);
// Buffered reader
BufferedReader br = new BufferedReader(fr);

// Initialize sl
sl = br.readLine();

// Take the input from the file


while ((s1 = br.readLine()) != null) {
sl = sl + "\n" + s1;
}

// Set the text


t.setText(sl);
}
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("New")) {
t.setText("");
}
else if (s.equals("close")) {
f.setVisible(false);
}
}

// Main class
public static void main(String args[])
{
editor e = new editor();
}
}
4
import
java.awt.*;
import
java.awt.event.*;

class TicTacToe extends Frame implements


ActionListener{Label status;
int
CrossZero =
1;
Button[][]
b;
TicTacToe()
{
setSize(408, 450);
this.setResizable(false);
setBackground(Color.LIGHT_G
RAY);

setLayout(null);
setVisible(true);
setTitle("Tic-
Tac-Toe");

Panel game_area = new Panel();

game_area.setBounds(5, 25, 400,


Font f = new Font("Times New Roman",Font.PLAIN,60);
for(int i=0;i<3;i++)
{
for(int j = 0; j<3;j++)
{
b[i][j] = new Button();
b[i][j].addActionListener(this);
b[i][j].setFont(f);
game_area.add(b[i][j]);
}

}
add(game_area);
status = new Label("Start the game now...");

status.setBounds(5, 25 + game_area.getHeight(), game_area.getWidth(),


20);
status.setBackground(Color.CYAN);
status.addMouseListener(new MouseAdapter() {

@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);
}

});

private void restart() {


for(Button row[] : b)
{
for(Button x: row)
{
x.setLabel("");
x.setEnabled(true);
}
}
}

private void disableAll() {


for(Button row[] : b)
{
for(Button x: row)
{
x.setEnabled(false);
}
}
}

private int val(String xo)


{
if(xo.equals("X"))
return 1;
else if(xo.equals("O"))
return -1;
else
return 0;
}

private Boolean check_tie(){


for(Button row[] : b)
{
for(Button x: row)
{
if(x.getLabel().equals(""))
return false;
}
}
return true;
}

private void check_winner()


{
int i,j;
int sum = 0;
for(i=0;i<3;i++)
{
sum = 0;
for(j=0;j<3;j++)
{
sum += (val(b[i][j].getLabel()));
}
if(sum==3 || sum== -3)
break;
}
if(sum!=3 && sum!= -3)
{
for(j=0;j<3;j++)
{
sum = 0;
for(i=0;i<3;i++)
{
sum += (val(b[i][j].getLabel()));
}
if(sum==3 || sum== -3)
break;
}
if(sum!=3 && sum!= -3)
{
sum = 0;
for(i=0;i<3;i++)
sum+= (val(b[i][i].getLabel()));
if(sum!=3 && sum!= -3)
{
sum = 0;
for(i=0;i<3;i++)
sum+= (val(b[i][2-i].getLabel()));
}

}
}
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();
}

public class Game {

public static void main(String[] args) {


// TODO Auto-generated method stub
new TicTacToe();

}
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;

private DrawCanvas canvas; // The custom drawing canvas (an innder


classextends JPanel)
// Constructor to set up the GUI components and event handlers
public CGMoveALine() {
// Set up a panel for the buttons
JPanel btnPanel = new JPanel(new FlowLayout());
JButton btnLeft = new JButton("Move Left ");
btnPanel.add(btnLeft);
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x1 -= 10;
x2 -= 10;
canvas.repaint();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
JButton btnRight = new JButton("Move Right");
btnPanel.add(btnRight);
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x1 += 10;
x2 += 10;
canvas.repaint();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});

// Set up a custom drawing JPanel


canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

// Add both panels to this JFrame's content-pane


Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(btnPanel, BorderLayout.SOUTH);

// "super" JFrame fires KeyEvent


addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
switch(evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
x1 -= 10;
x2 -= 10;
repaint();
break;
case KeyEvent.VK_RIGHT:
x1 += 10;
x2 += 10;
repaint();
break;
}
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE


button
setTitle("Move a Line");
pack(); // pack all the components in the JFrame
setVisible(true); // show it
requestFocus(); // set the focus to JFrame to receive KeyEvent
}

/**
* 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
}
}

// The entry main() method


public static void main(String[] args) {
// Run GUI codes on the Event-Dispatcher Thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CGMoveALine(); // Let the constructor do the job
}
});
}
}
7
import
java.awt.BasicStroke;
import
java.awt.Color;
import
java.awt.Graphics;
import
java.awt.Graphics2D;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.awt.event.MouseEvent;
import
java.awt.event.MouseListener;
import
java.awt.event.MouseMotionListener;
import
java.awt.image.BufferedImage;

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;

public static void main(String[] args)


{
new PaintProgram();
}

PaintProgram()
{

JFrame frame = new JFrame("Paint Program");


frame.setSize(1200, 800);

/**
* CHANGE BY S AQEEL : Use constant instead of hardcoding
*/
frame.setBackground(BACKGROUND_COLOR);
frame.getContentPane().add(this);

JMenuBar menuBar = new JMenuBar();


frame.setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);

JButton button1 = new JButton("Clear");


button1.addActionListener(this);
JButton color = new JButton("Color");
color.addActionListener(this);
JButton erase = new JButton("Erase?");
erase.addActionListener(this);
JButton button2 = new JButton("Empty Rect");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Filled Rect");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);

ButtonGroup lineOption = new ButtonGroup();


lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);

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);

public void paintComponent(Graphics g)


{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (grid == null)
{
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage) (this.createImage(w, h));
gc = grid.createGraphics();
gc.setColor(Color.BLUE);
}
g2.drawImage(grid, null, 0, 0);
check();
}

BufferedImage grid;
Graphics2D gc;

public void draw()


{
Graphics2D g = (Graphics2D) getGraphics();
int w = xX2 - xX1;
if (w < 0)
w = w * (-1);

int h = yY2 - yY1;


if (h < 0)
h = h * (-1);

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;
}
}

public void check()


{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 = z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}

public void actionPerformed(ActionEvent e)


{
/**
* CHANGE BY S AQEEL : Remove mousemotionlistener(which is added when
eraser is selected) So that if another control is pressed, the user does
* not accidentally erases
*/
super.removeMouseMotionListener(this);

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();
}

public void mouseExited(MouseEvent evt)


{
}

public void mouseEntered(MouseEvent evt)


{
}

public void mouseClicked(MouseEvent evt)


{
}

public void mousePressed(MouseEvent evt)


{

xX1 = evt.getX();
yY1 = evt.getY();

public void mouseReleased(MouseEvent evt)


{
xX2 = evt.getX();
yY2 = evt.getY();
draw();
eraser = 0;
}

/**
* 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.*;

public class SudokuFrame extends JFrame implements


ActionListener,KeyListener
{

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() {

public void windowClosing(WindowEvent e) {


System.exit(0);
}
});

setResizable(false);

setTitle("SUDOKU");

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();


setSize(520, 500);
int w = getSize().width;
int h = getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
setLocation(x, y);

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);

FlowLayout buttonsLayout = new FlowLayout(FlowLayout.CENTER);


Panel buttonsPanel=new Panel();
buttonsPanel.setLayout(buttonsLayout);
buttonsPanel.add(solve);
buttonsPanel.add(clear);
buttonsPanel.add(help);

GridLayout sudokugrid = new GridLayout(10,9);


Panel gridPanel=new Panel();
gridPanel.setLayout(sudokugrid);
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
gridPanel.add(cells[i][j]);
}

this.add(title,BorderLayout.NORTH);
this.add(gridPanel,BorderLayout.CENTER);
this.add(buttonsPanel,BorderLayout.SOUTH);
}

public void actionPerformed(ActionEvent e) {


JButton cell;
cell=(JButton)e.getSource();
if(cell==solve){
solveSudoku();
solve.setEnabled(false);
solve.setBackground(new Color(240,240,240));
}
else if(cell==clear){
clearSudoku();
solve.setEnabled(true);
solve.setBackground(new Color(200,200,200));
}
else if(cell==help){
if(hf.isVisible()==false)
hf.setVisible(true);
else{
hf.setVisible(false);
hf.setVisible(true);
}

}
else{
active.setBackground(activeCellColor);
activeCellColor=cell.getBackground();
cell.setBackground(new Color(100,100,150));
active=cell;
}
}

public void keyTyped(KeyEvent e) {

public void keyPressed(KeyEvent e) {


char ch=(char)e.getKeyCode();
if(solve.isEnabled()){
if(ch>='1' && ch<='9'){
active.setForeground(new Color(184,134,11));
active.setText(Character.toString(ch));
}
else if (ch=='0')
active.setText("");
}
}

public void keyReleased(KeyEvent e) {

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("");
}
}
}

class HelpFrame extends JFrame{


HelpFrame(){
super("Help");
String msg="<HTML><h4>SUDOKU PROBLEM SOLVER</h4><BR>To enter a value
choose any cell by mouse click.<BR>Enter any number (1 to 9) .<BR>0 to
delete/clear.<BR>Click SOLVE to solve the sudoku problem you have
entered.<BR>Click CLEAR to clear all cells.<BR><BR>* Please enter a valid
problem to get result since the program is not checking for it.</HTML>";

JLabel help = new JLabel(msg,JLabel.CENTER);


add(help);
setResizable(false);

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();


setSize(320, 300);
int w = getSize().width;
int h = getSize().height;
int x = (dim.width-w)/2;
int y =
(dim.height-h)/2;
setLocation(x, y);

addWindowListener(new WindowAdapter()

{ public void

windowClosing(WindowEvent e) {
setVisible(false);
}
});
}
} Main.java
public class Main {

public Main() {
}

public static void main(String[]


args) { SudokuFrame sudokuFrame=new
SudokuFrame();
}
}

Cell.java
class Cell {
int
value;
Group
row;
Group
column;
Group
grid;
boolean
fixed;

public
Cell(
) {
value
=0;
fixed
=fals
e;
}

boolean setValue(int value){


if(row.isDuplicateValueExists(value)||column.isDuplicateValueExi
sts(va
this.value
=value;
return
true;
}
}

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;
}
} }

boolean isDuplicateValueExists(int value){


for(int i=0;i<9;i++){
if(cells[i].getValue()=
=value)
return true;
}
return false;
}

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]);

int gridrow=i/3*3 + j/3;


int gridcol=i%3*3 + j%3;

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 setCell(int i,int j,int value){


cells[i][j].setValue(value);
cells[i][j].setFixed(true);
}

int getCell(int i,int j){


return(cells[i][j].getValue());
}

void display(){
for(int i=0;i<9;i++){
rows[i].display();
}
}

boolean isFixed(int i,int j){


return cells[i][j].isFixed();
}
}
11
import
java.awt.*;
import
java.awt.event.*;
import
java.awt.geom.*;
import
javax.swing.*;
import
javax.swing.event.*;
import
java.util.Random;

public class TicTacToe extends JFrame implements


ChangeListener,ActionListener {
private JSlider slider;
private JButton oButton,
xButton;private Board
board;
private int lineThickness=4;
private Color oColor=Color.BLUE,
xColor=Color.RED;static final char BLANK='
', O='O', X='X';
private char position[]={ // Board position (BLANK, O, or
X)BLANK, BLANK, BLANK,
BLANK, BLANK,
BLANK,BLANK,
BLANK, BLANK};
private int wins=0, losses=0, draws=0; // game count by user

// Start the game


// Initialize
public TicTacToe() {
super("Tic Tac Toe demo");
JPanel topPanel=new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(new JLabel("Line Thickness:"));
topPanel.add(slider=new JSlider(SwingConstants.HORIZONTAL, 1, 20, 4));
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.addChangeListener(this);
topPanel.add(oButton=new JButton("O Color"));
topPanel.add(xButton=new JButton("X Color"));
oButton.addActionListener(this);
xButton.addActionListener(this);
add(topPanel, BorderLayout.NORTH);
add(board=new Board(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}

// Change line thickness


public void stateChanged(ChangeEvent e) {
lineThickness = slider.getValue();
board.repaint();
}

// 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();
}

// Board is what actually plays and displays the game


private class Board extends JPanel implements MouseListener {
private Random random=new Random();
private int rows[][]={{0,2},{3,5},{6,8},{0,6},{1,7},{2,8},{0,8},{2,6}};
// Endpoints of the 8 rows in position[] (across, down, diagonally)

public Board() {
addMouseListener(this);
}

// Redraw the board


public void paintComponent(Graphics g) {
super.paintComponent(g);
int w=getWidth();
int h=getHeight();
Graphics2D g2d = (Graphics2D) g;

// Draw the grid


g2d.setPaint(Color.WHITE);
g2d.fill(new Rectangle2D.Double(0, 0, w, h));
g2d.setPaint(Color.BLACK);
g2d.setStroke(new BasicStroke(lineThickness));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));
g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));

// Draw the Os and Xs


for (int i=0; i<9; ++i) {
double xpos=(i%3+0.5)*w/3.0;
double ypos=(i/3+0.5)*h/3.0;
double xr=w/8.0;
double yr=h/8.0;
if (position[i]==O) {
g2d.setPaint(oColor);
g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));
}
else if (position[i]==X) {
g2d.setPaint(xColor);
g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));
g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));
}
}
}

// Draw an O where the mouse is clicked


public void mouseClicked(MouseEvent e) {
int xpos=e.getX()*3/getWidth();
int ypos=e.getY()*3/getHeight();
int pos=xpos+3*ypos;
if (pos>=0 && pos<9 && position[pos]==BLANK) {
position[pos]=O;
repaint();
putX(); // computer plays
repaint();
}
}

// Ignore other mouse events


public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// Computer plays X
void putX() {

// Check if game is over


if (won(O))
newGame(O);
else if (isDraw())
newGame(BLANK);

// Play X, possibly ending the game


else {
nextMove();
if (won(X))
newGame(X);
else if (isDraw())
newGame(BLANK);
}
}

// Return true if player has won


boolean won(char player) {
for (int i=0; i<8; ++i)
if (testRow(player, rows[i][0], rows[i][1]))
return true;
return false;
}

// Has player won in the row from position[a] to position[b]?


boolean testRow(char player, int a, int b) {
return position[a]==player && position[b]==player
&& position[(a+b)/2]==player;
}

// Play X in the best spot


void nextMove() {
int r=findRow(X); // complete a row of X and win if possible
if (r<0)
r=findRow(O); // or try to block O from winning
if (r<0) { // otherwise move randomly
do
r=random.nextInt(9);
while (position[r]!=BLANK);
}
position[r]=X;
}

// Return 0-8 for the position of a blank spot in a row if the


// other 2 spots are occupied by player, or -1 if no spot exists
int findRow(char player) {
for (int i=0; i<8; ++i) {
int result=find1Row(player, rows[i][0], rows[i][1]);
if (result>=0)
return result;
}
return -1;
}

// If 2 of 3 spots in the row from position[a] to position[b]


// are occupied by player and the third is blank, then return the
// index of the blank spot, else return -1.
int find1Row(char player, int a, int b) {
int c=(a+b)/2; // middle spot
if (position[a]==player && position[b]==player && position[c]==BLANK)
return c;
if (position[a]==player && position[c]==player && position[b]==BLANK)
return b;
if (position[b]==player && position[c]==player && position[a]==BLANK)
return a;
return -1;
}

// Are all 9 spots filled?


boolean isDraw() {
for (int i=0; i<9; ++i)
if (position[i]==BLANK)
return false;
return true;
}

// Start a new game


void newGame(char winner) {
repaint();

// Announce result of last game. Ask user to play again.


String result;
if (winner==O) {
++wins;
result = "You Win!";
}
else if (winner==X) {
++losses;
result = "I Win!";
}
else {
result = "Tie";
++draws;
}
if (JOptionPane.showConfirmDialog(null,
"You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"
+"Play again?", result, JOptionPane.YES_NO_OPTION)
!=JOptionPane.YES_OPTION) {
System.exit(0);
}

// Clear the board to start a new game


for (int j=0; j<9; ++j)
position[j]=BLANK;

// Computer starts first every other game


if ((wins+losses+draws)%2 == 1)
nextMove();
}
} // end inner class Board
} // end class TicTacToe

You might also like