changingFace-GUI-Java

A Simple GUI (Changing Face)

“A Simple GUI (Changing Face)” is simple Java program to explain couple of simple usage of java swing library and so forth.

The ChangingFace Class:


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

public class ChangingFace extends JFrame implements ActionListener
{
int whichFeel = 0;
private JButton happyButton = new JButton("Smile");
private JButton thinkButton = new JButton("Think");
private JButton sadButton = new JButton("Frown");

public ChangingFace()
{
// set the title
setTitle("Changing Face");

// choose a Flow Layout policy
setLayout(new FlowLayout());

// add the buttons to the frame
add(happyButton);
add(thinkButton);
add(sadButton);

// set the background to yellow
getContentPane().setBackground(Color.yellow);

// enable the buttons to listen for a mouse-click
happyButton.addActionListener(this);
thinkButton.addActionListener(this);
sadButton.addActionListener(this);

// configure the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(250, 200);
setLocation(300,300);
setVisible(true);
}

public void paint(Graphics g)
{
// call the paint method of the superclass, Jframe
super.paint(g);
// paint the face
g.setColor(Color.red);
g.drawOval(85,75,75,75);
g.setColor(Color.blue);
g.fillOval(100,95,10,10);
g.fillOval(135,95,10,10);
g.drawString("Changing Face", 80,185);
g.drawRect(121, 150, 3, 20);
if(whichFeel == 1)
{
// draw a smiling mouth
g.drawArc(102,115,40,25,0,-180);
}
else if(whichFeel == 3)
{
// draw a frowning mouth
g.drawArc(102,115,40,25,0,180);
} else if(whichFeel == 2) {
// draw a thinking mouth
g.drawLine(102, 130, 142, 130);
}

}
// this is where we code the event-handling routine
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == happyButton)
{
whichFeel = 1;
repaint();
}
if(e.getSource() == thinkButton)
{
whichFeel = 2;
repaint();
}
if(e.getSource() == sadButton)
{
whichFeel = 3;
repaint();
}
}
}

 The Tester Class:


public class ChangingFaceTester {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ChangingFace();

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *