|
A simple swing application:
Below is the Sample Saloon Application, which uses JFrame, JLabel, JPanel, JTextBox and some other components.
Total cost is calculated based on whether the customer is member or not.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class SaloonApp1{
public static void main(String[]args){
JFrame frame = new JFrame("The Saloon Center");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(30,20,10,10));
panel.add(new JLabel(" Name:"));
final JTextField jtf = new JTextField();
panel.add(jtf);
panel.add(new JLabel(" Member or non Member:"));
final JRadioButton Yes=new JRadioButton(" Member (25% discount on Total Cost)");
final JRadioButton No=new JRadioButton(" Non-member");
ButtonGroup buttonGroup =new ButtonGroup();
buttonGroup.add(Yes);
panel.add(Yes);
buttonGroup.add(No);
panel.add(No);
panel.add(new JLabel(" Please select a type of treatment:"));
final JCheckBox Body=new JCheckBox(" Body");
final JCheckBox Hair=new JCheckBox(" Hair");
panel.add(Body);
panel.add(Hair);
panel.add(new JLabel(" For Body treatment, please make your selection:"));
final JRadioButton SeveralParts = new JRadioButton(" Several parts - Rs 320.00");
final JRadioButton AllParts = new JRadioButton(" All parts - Rs 600.00");
ButtonGroup BTreatment =new ButtonGroup();
BTreatment.add(SeveralParts);
panel.add(SeveralParts);
BTreatment.add(AllParts);
panel.add(AllParts);
panel.add(new JLabel(" For hair treatment, please make your selection:"));
final JCheckBox Rebonding = new JCheckBox(" Rebonding - Rs 250 ");
panel.add(Rebonding);
final JCheckBox Cutting = new JCheckBox(" Cutting - Rs 50 ");
panel.add(Cutting);
final JCheckBox Washing = new JCheckBox(" Washing - Rs 15 ");
panel.add(Washing);
final JCheckBox Dyeing = new JCheckBox(" Dyeing - Rs 100 ");
panel.add(Dyeing);
JButton button =new JButton("Submit");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
double severalPartsOfBody= 320.00;
double allPartsOfBody= 600.00;
double rebondingPrice=250.00;
double cuttingPrice= 50.00;
double washingPrice=15.00;
double dyeingPrice=100.00;
double Member_Concession=0;
String str="Customer Name: "+jtf.getText()+"\n";
double TotalCost = 0;
if(Body.isSelected()==true){
str=str+"Body treatment:\n";
if (SeveralParts.isSelected()==true){
str=str+"Cost for Several Parts: Rs "+severalPartsOfBody+"\n";
TotalCost = TotalCost + severalPartsOfBody;
}
if (AllParts.isSelected()==true){
str=str+"Cost for All Parts: Rs "+allPartsOfBody+"\n";
TotalCost = TotalCost + allPartsOfBody;
}
}
if(Hair.isSelected()==true){
str=str+"Hair treatment:\n";
if(Rebonding.isSelected()==true) {
str = str+"Cost for Rebonding: Rs "+rebondingPrice+"\n";
TotalCost = TotalCost + rebondingPrice;
}
if(Cutting.isSelected()==true) {
str = str+"Cost for Cutting: Rs "+cuttingPrice+"\n";
TotalCost = TotalCost + cuttingPrice;
}
if(Washing.isSelected()==true) {
str = str+"Cost for Washing: Rs "+washingPrice+"\n";
TotalCost = TotalCost + washingPrice;
}
if(Dyeing.isSelected()==true) {
str = str+"Cost for Dyeing: Rs "+dyeingPrice+"\n";
TotalCost = TotalCost + dyeingPrice;
}
}
str = str+"Total Cost: Rs "+TotalCost+"\n";
if(Yes.isSelected()==true){
Member_Concession=TotalCost/4;
str = str+"Member Concession : Rs "+Member_Concession+"\nAmount to be paid: "+(TotalCost-Member_Concession);
}
if(No.isSelected()==true){
str = str+"Member Concession : Rs "+Member_Concession+"\nAmount to be paid: "+(TotalCost-Member_Concession);
}
JOptionPane.showMessageDialog(null,str);
}});
frame.add(panel);
panel.add(button);
frame.setSize(750, 750);
frame.setVisible(true);
}
}
Output of the above application:
|
Overview of several swing components
- Simple uses of JButton are very similar to Button.
You create a JButton with a String as a label, and then drop it in a window.
Events are normally handled just as with a Button: you attach an ActionListener via the addActionListener method.
- JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.
- JFrame is Swing’s version of Frame and is descended directly from that class.
The components added to the frame are referred to as its contents; these are managed by the contentPane.
To add a component to a JFrame, we must use its contentPane instead.
- JWindow is Swing’s version of Window and is descended directly from that class. Like Window,
it uses BorderLayout by default.
- JDialog is Swing’s version of Dialog and is descended directly from that class.
Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow.
- JLabel descended from JComponent, is used to create text labels.
- The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes
including JButton.
- JTextField allows editing of a single line of text.
New features include the ability to justify the text left, right, or center, and to set the text’s font.
- JRadioButton is similar to JCheckbox, except for the default icon for each class.
A set of radio buttons can be associated as a group in which only
one button at a time can be selected.
- JCheckBox is not a member of a checkbox group.
A checkbox can be selected and deselected, and it also displays its current state.
|
Java Graphics capabilities – Introduction:
Java GUI programming involves two packages:
the original Abstract Windows Toolkit (AWT) and the newer Swing toolkit.
Swing components have the prefix J to distinguish them from the original AWT ones (e.g. JFrameinstead of Frame).
To include AWT or Swing components and methods in your project, you must import java.awt.*, java.awt.event.* and javax.swing.* packages.
Displayable frames are top-level containers such as JFrame, JWindows, JDialog, and JApplet.
Non-displaying content panes are intermediate containers such as JPanel, JOptionsPane, JScrollPane and JSplitPane.
Containers are therefore widgets or GUI controls that are used to hold and group other widgets such as text boxes, check boxes, radio buttons etc.
Every GUI starts with a window meant to display things.
In Swing, there are three types of windows: the Applet, the Dialog and the Frame.
Stated simply, the content pane is where we place out text fields or other widgets, so to add and display GUI controls,
we need to specify that it is the content pane that we are adding to.
The content pane is then at the top of a containment hierarchy, in which this tree-like hierarchy has a top-level container (in our case JFrame).
Working down the tree, we would find other top level containers like JPanel to hold the components.
Here is the code that produces a simple frame upon to build on:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame1 extends JFrame
{
JPanel pane = new JPanel();
Frame1() {
super("My Simple Frame");
setBounds(100,100,300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(pane);
setVisible(true);
}
public static void main(String args[]) {new Frame1();}
}
|
Graphics contexts and Graphics objects:
A Graphics context enables drawing on the screen. It is encapsulated by Graphics class and is obtained in 2 ways.
- It is passed to an applet when paint() or update() is called.
- It is returned by getGraphics() method of Component.
A Graphics object manages a graphics context and draws pixels on the screen that represent text & other graphical objects
(eg. lines, ellipses, rectangles and other polygons).
Graphics objects contain methods for drawing, font manipulation, color manipulation etc.
Class Graphics is an abstract class (i.e Graphics objects cannot be instantiated).
This contributes to Java’s portability.
Because drawing is performed differently on every platform that supports Java,
there cannot be only one implementation of the drawing capabilities across all systems.
For example, the graphics capabilities that enable a PC running Microsoft Windows to draw a rectangle are different
from those that enable a Linux workstation to draw a rectangle and they’re both different
from the graphics capabilities that enable a Macintosh to draw a rectangle.
When Java is implemented on each platform, a subclass of Graphics is created that implements the drawing capabilities.
This implementation is hidden by class Graphics, which supplies the interface that enables us to use graphics
in a platform-independent manner.
|
Color control:
The AWT color system allows you to specify any color you want.
Color is encapsulated by the Color class.
Color defines several constants(ex: Color.black) to specify number of common colors.
You can also create your own colors using one of the color constructors.
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The Color class defines several methods that help manipulate colors.
Using Hue, Saturation and Brightness:
The Hue-Saturation-Brightness(HSB) color model is an alternative to RGB for specifying particular colors.
Color supplies 2 methods that let you convert between RGB and HSB.
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[] RGBtoHSB(int red, int green, int blue, float values[])
getRed(), getGreen(), getBlue() methods:
Use getRGB() method to obtain RGB representation of a color.
Ex:
import java.awt.*;
import java.applet.*;
public class ColorDemo extends Applet{
public void paint(Graphics g){
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.setColor(c2);
g.drawLine(0, 100, 100, 0);
g.setColor(Color.blue);
g.drawOval(190, 10, 90, 30);
g.drawRect(10, 10, 60, 50);
}
}
Output:
Font control:
An instance of the Font class represents a specific font to the system.
Within AWT, a font is specified by its name, style, and point size.
Each platform that supports Java provides a basic set of fonts.
To find the fonts supported on any platform, call Toolkit.getDefaultToolkit().getFontList().
This method returns aString array of the fonts available.
There are four styles for displaying fonts in Java: plain, bold, italic, and bold italic. Three class constants are used to represent font styles:
public static final int BOLD
public static final int ITALIC
public static final int PLAIN
The combination BOLD | ITALIC represents a bold italic font.
Constructors:
public Font (String name, int style, int size)
There is a single constructor for Font. It requires a name, style, and size. name represents the name of the font to create,
setFont (new Font ("TimesRoman", Font.BOLD | Font.ITALIC, 20));
Characteristics:
public String getName()
The getName() method returns the font's logical name.
public String getFamily()
The getFamily() method returns the actual name of the font that is being used to display characters.
public int getStyle()
The getStyle() method returns the current style of the font as an integer.
Compare this value with the constants Font.BOLD, Font.PLAIN, andFont.ITALIC to see which style is meant.
It is easier to use the isPlain(), isBold(), and isItalic() methods to find out the current style.
getStyle()is more useful if you want to copy the style of some font when creating another.
public int getSize()
The getSize() method retrieves the point size of the font, as set by the size parameter in the constructor. The actual displayed size may be different.
Styles:
public boolean isPlain()
The isPlain() method returns true if the current font is neither bold nor italic. Otherwise, it returns false.
public boolean isBold()
The isBold() method returns true if the current font is either bold or bold and italic. Otherwise, it returns false.
public boolean isItalic()
The isItalic() method returns true if the current font is either italic or bold and italic. Otherwise, it returns false.
public boolean equals(Object o)
The equals() method overrides the equals() method of Object to define equality for Font objects.
Two Font objects are equal if their size, style, and name are equal.
The following example demonstrates why this is necessary.
Font a = new Font ("TimesRoman", Font.PLAIN, 10);
Font b = new Font ("TimesRoman", Font.PLAIN, 10);
// displays false since the objects are different objects
System.out.println (a == b);
// displays true since the objects have equivalent settings
Drawing Lines:
Lines are drawn using drawLine() method.
void drawLine(int startX, int startY, int endX, int endY)
drawLine() displays a line in the current drawing color that begins at (startX, startY) and ends at (endX, endY)
Ex:
import java.awt.*;
import java.applet.*;
public class Lines extends Applet{
public void paint(Graphics g){
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
}
}
Output:
Drawing Rectangles:
The drawRect() and fillRect methods display an outlined and filled rectangle.
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper left corner of the rectangle is at (top, left).
To draw a rounded rectangle, use drawRoundRect() or fillRoundRect() methods.
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
The diameter of rounding arc along X-axis is specified by xDiam and the diameter of rounding arc along Y-axis is specified by yDiam.
import java.awt.*;
import java.applet.*;
public class Rectangles extends Applet{
public void paint(Graphics g){
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
Output:
Drawing Ellipses and Circles:
To draw an ellipse use drawOval(), to fill an ellipse, use fillOval().
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by (top, left) and
whose width, height are specified by width and height.
import java.awt.*;
import java.applet.*;
public class Ellipses extends Applet{
public void paint(Graphics g){
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
Output:
Drawing Arcs:
Arcs can be drawn with drawArc() and fillArc() methods.
void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by (top, left) and width and height are specified by width and height.
The arc is drawn from startAngle through the angular distance specified by sweepAngle.
import java.awt.*;
import java.applet.*;
public class Arcs extends Applet{
public void paint(Graphics g){
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
}
}
Output:
|
Layout Management:
Java technology uses Layout Managers to define the location and size of GUI components.
Java technology does not encourage programmers to use absolute location and size of components.
Java technology instead places components based on specified Layout Manager.
A Layout Manager implements a layout policy that defines constraints between components in a container.
Types of Layout Managers:
Java technology provides the following Layout Managers, each of which implements the LayoutManager interface.
- FlowLayout:
FlowLayout is the default layout manager.
FlowLayout implements a simple layout style which is similar to a text editor.
Below are the constructors for FlowLayout:
FlowLayout()- creates default layout.
FlowLayout(int how)- allows specifies how each line is aligned.
Valid values for how:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout(int how, int horz, int vert)- allows you to specify the horizontal and vertical space left between components.
Ex:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FlowLayoutDemo extends Applet implements ItemListener{
Checkbox WIP_Item, BOM_Item;
public void init(){
setLayout(new FlowLayout(FlowLayout.LEFT));
WIP_Item = new Checkbox("WIP Item", null, true);
BOM_Item = new Checkbox("BOM Item");
add(WIP_Item);
add(BOM_Item);
WIP_Item.addItemListener(this);
BOM_Item.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
repaint();
}
public void paint(Graphics g){
String str1="WIP_Item "+WIP_Item.getState();
String str2="BOM_Item "+BOM_Item.getState();
g.drawString("Current State: ", 6, 80);
g.drawString(str1, 6, 100);
g.drawString(str2, 6, 120);
}
}
Output:
- GridLayout:
The components in a GridLayout are in a two-dimensional grid.
The constructors defined by GridLayout are shown here:
GridLayout()- creates single column grid layout.
GridLayout(int numRows, int numCols)- creates a grid layout with specified number of rows and columns.
GridLayout(int numRows, int numCols, int horz, int vert)-
allows you to specify horizontal and vertical space left between components.
Here is sample program that creates 4X4 grid and fills it with 15 buttons, each labeled with its index.
import java.awt.*;
import java.applet.*;
public class GridLayoutDemo extends Applet{
static final int n=4;
public void init(){
setLayout(new GridLayout(n,n));
setFont(new Font("sansSerif", Font.BOLD, 24));
for(int i=0;i< n;i++){
for(int j=0;j< n;j++){
int k=i*n+j;
if(k>0) add(new Button("" + k));
}
}
}
}
Output:
- BorderLayout:
The BorderLayout class implements a common layout style for top_level windows.
It has four narrow, fixed-width components at the edges and one large area in the center.
The four sides are reffered as north, south, east and west.
Constructors defined by BorderLayout:
BorderLayout() – creates default border layout.
BorderLayout(int horz, int vert) – allows you to specify horizontal and vertical space left between components.
BorderLayout defines following constants:
BorderLayout.CENTER
BorderLayout.NORTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.SOUTH
To add these constants, use add() method.
void add(Component compObj, Object region);
Ex:
import java.awt.*;
import java.applet.*;
import java.util.*;
public class BorderLayoutDemo extends Applet{
public void init(){
setLayout(new BorderLayout());
add(new Button(“This is Top”), BorderLayout.NORTH);
add(new Label(“This is Bottom”), BorderLayout.SOUTH);
add(new Button(“This is Right”), BorderLayout.EAST);
add(new Button(“This is Left”), BorderLayout.WEST);
String msg=”This is BorderLayout demo program.”;
add(new TextArea(msg), BorderLayout.CENTER);
}
}
- BoxLayout:
The BoxLayout class puts components in a single row or column.
It respects the components' requested maximum sizes and also lets you align components.
Constructor:
BoxLayout(Container target, int axis)
Creates a layout manager that will lay out components along the given axis.
The value of axis can be one of the following:
BoxLayout.X_AXIS
BoxLayout.Y_AXIS
BoxLayout.LINE_AXIS
BoxLayout.PAGE_AXIS
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BoxLayoutTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("BoxLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLayout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS); // top to bottom
frame.setLayout(boxLayout);
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.pack();
frame.setVisible(true);
}
}
Output:
|
|