Credits

Friday, March 26, 2010

Another Java Graphics Sample

I have this sample exercise for my students to illustrate the use of buttons with Graphics methods and use of Font class to the works. 


See  the sample program.

[+/-] show/hide



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//
public class GraphicsQuiz extends JApplet implements ActionListener{
Container con = getContentPane();
JButton increase = new JButton ("increase");
JButton decrease = new JButton ("decrease");
JLabel lbl=new JLabel(" S T I");
int size=10;

public void init()
{
con.setLayout(new FlowLayout ());


con.add(increase);
con.add(decrease);
con.add(lbl);
increase.addActionListener(this);
decrease.addActionListener(this);
setBackground(Color.red);
}


public void actionPerformed(ActionEvent e)
{ Object source =e.getSource();

if (source==increase)
{Font myFont=new Font("Arial",Font.BOLD, size+=10);
lbl.setFont(myFont);
if (size>50)
size=10;
repaint();}
else
if (source==decrease)
{Font myFont=new Font("Arial",Font.BOLD, size-=10);
lbl.setFont(myFont);
if (size<0)
size=10;

repaint();}

}
}

AddThis