Wednesday, November 29, 2006

JRadioButton: Simpler Example



import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // step 1

// Mututally exclusive == >ButtonGroup

public class JRadioButtonDemo extends JFrame //step 2
implements ActionListener{

private JRadioButton rbtn1 = new JRadioButton("Ivan");
private JRadioButton rbtn2 = new JRadioButton("Kwan Yong");
private JButton btn = new JButton("Vote");

private ButtonGroup btngrp = new ButtonGroup();

public JRadioButtonDemo() {

btngrp.add(rbtn1); // For making one radiobutton clickable at one time
btngrp.add(rbtn2);

rbtn1.setSelected(true); // Set Ivan to be default

getContentPane().setLayout(new FlowLayout());
getContentPane().add(rbtn1);
getContentPane().add(rbtn2);
getContentPane().add(btn);

btn.addActionListener(this);//step 4:

} //end constructor

public void actionPerformed(ActionEvent ev){//step 3

String name = "";
if (ev.getSource() == btn){
if (rbtn1.isSelected()){ // Ivan was voted
name = "Ivan";
}
else if (rbtn2.isSelected()){
name = "Kwan Yong";
}

JOptionPane.showMessageDialog(null, "You voted for " + name);
}//end if

} //end actionPerformed

public static void main(String[] args) {
JRadioButtonDemo f = new JRadioButtonDemo();
f.setTitle("OOPG");
f.setSize(300, 300);
f.setVisible(true);

} //end main
} //end class

JRadioButton: More Complicated Example


import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // step 1

// Mututally exclusive == >ButtonGroup

public class JRadioButtonDemo2 extends JFrame //step 2
implements ActionListener{

private JRadioButton rbtn1 = new JRadioButton("Ivan");
private JRadioButton rbtn2 = new JRadioButton("Kwan Yong");
private JTextArea ta1 = new JTextArea(5,30);
private JButton btn = new JButton("Vote");

private int ivan;
private int kwanyong;

private ButtonGroup btngrp = new ButtonGroup();

public JRadioButtonDemo2() {

btngrp.add(rbtn1); // For making one radiobutton clickable at one time
btngrp.add(rbtn2);

rbtn1.setSelected(true); // Set Ivan to be default

getContentPane().setLayout(new FlowLayout());
getContentPane().add(rbtn1);
getContentPane().add(rbtn2);
getContentPane().add(btn);
getContentPane().add(ta1); // textarea display the no.of votes

btn.addActionListener(this);//step 4:

} //end constructor

public void actionPerformed(ActionEvent ev){//step 3

String name = "";
if (ev.getSource() == btn){
if (rbtn1.isSelected()){ // Ivan was voted
name = "Ivan";
ivan++;
}
else if (rbtn2.isSelected()){
name = "Kwan Yong";
kwanyong++;
}

JOptionPane.showMessageDialog(null, "You voted for " + name);
ta1.setText("Ivan:" + ivan + "\nKwan Yong:" + kwanyong);

}//end if

} //end actionPerformed

public static void main(String[] args) {
JRadioButtonDemo2 f = new JRadioButtonDemo2();
f.setTitle("OOPG");
f.setSize(300, 300);
f.setVisible(true);

} //end main
} //end class

JTextArea : setText, getText and append methods



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

import java.awt.event.*; // step 1

public class JTextAreaDemo extends JFrame //step 2
implements ActionListener{

private JTextArea ta1 = new JTextArea(10,20);
private JButton btn = new JButton("Add");
private JButton btn2 = new JButton("Append");
private JButton btn3 = new JButton("Get text in TextArea");

public JTextAreaDemo() {

getContentPane().setLayout(new FlowLayout());
getContentPane().add(ta1);
getContentPane().add(btn);
getContentPane().add(btn2);
getContentPane().add(btn3);

btn.addActionListener(this);//step 4:
btn2.addActionListener(this);
btn3.addActionListener(this);

} //end constructor

public void actionPerformed(ActionEvent teckyong){//step 3

if (teckyong.getSource() == btn){
ta1.setText("ABC"); // Add text, overwrite the previous
} //end if
else if (teckyong.getSource() == btn2){
ta1.append("ABC\n");
}
else if (teckyong.getSource() == btn3){
String s = ta1.getText(); // Get what is in the TextArea
JOptionPane.showMessageDialog(null,s);
}

} //end actionPerformed

public static void main(String[] args) {
JTextAreaDemo f = new JTextAreaDemo();
f.setTitle("OOPG");
f.setSize(300, 300);
f.setVisible(true);

} //end main
} //end class


Tuesday, November 28, 2006

ImageIcon example



import javax.swing.*;
import java.awt.*; // layout
// Step 1
import java.awt.event.*; //ActionListener

public class TongjinFrame extends JFrame
/*Step 2*/ implements ActionListener{

private JLabel lblPic;
private ImageIcon imgTJ, imgIvan;

private JButton btnChange;

public TongjinFrame(){

imgTJ = new ImageIcon("tongjin.jpg");
imgIvan = new ImageIcon("ivan.jpg");

lblPic = new JLabel(imgTJ);

btnChange = new JButton("Change");

getContentPane().add(lblPic);
getContentPane().add(btnChange, "South");

// Step 4
btnChange.addActionListener(this);
}

// Step 3:
public void actionPerformed(ActionEvent ev){
lblPic.setIcon(imgIvan);
} //end actionPerformed

}//end class

Friday, November 24, 2006

GUI with ActionListener


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

import java.awt.event.*;

public class ScaleConverter2 extends JFrame
implements ActionListener{


private JLabel lblValue, lblResult;
private JButton btnCompute, btnCancel;
private JRadioButton rbKm, rbMetre, rbCm;
private JRadioButton rbToKm, rbToMetre, rbToCm;
private JPanel convertFromPnl, convertToPnl, calculatePnl;
private JTextField txtValue, txtResult;

public ScaleConverter2() {
initConvertFromPnl();
initConvertToPnl();
initCalculatePnl();

getContentPane().setLayout(new GridLayout(3, 1));
getContentPane().add(convertFromPnl);
getContentPane().add(convertToPnl);
getContentPane().add(calculatePnl);

} //end constructor

public void initConvertFromPnl() {
convertFromPnl = new JPanel(new GridLayout(3, 1));
rbKm = new JRadioButton("Km");
rbMetre = new JRadioButton("Metre");
rbCm = new JRadioButton("Cm");
convertFromPnl.add(rbKm);
convertFromPnl.add(rbMetre);
convertFromPnl.add(rbCm);
convertFromPnl.setBorder(BorderFactory.createTitledBorder("Convert from"));

// Set KM as the default
rbKm.setSelected(true);

}

public void initConvertToPnl() {
convertToPnl = new JPanel(new GridLayout(3, 1));
rbToKm = new JRadioButton("Km");
rbToMetre = new JRadioButton("Metre");
rbToCm = new JRadioButton("Cm");
convertToPnl.add(rbToKm);
convertToPnl.add(rbToMetre);
convertToPnl.add(rbToCm);
convertToPnl.setBorder(BorderFactory.createTitledBorder("Convert from"));

rbToMetre.setSelected(true);
}

public void initCalculatePnl() {
calculatePnl = new JPanel(new GridLayout(3, 2,5,5));
lblValue = new JLabel("Value");
lblResult = new JLabel("Result");
btnCompute = new JButton("Compute");
btnCancel = new JButton("Cancel");
txtValue = new JTextField(10);
txtResult = new JTextField(10);

calculatePnl.add(lblValue);
calculatePnl.add(txtValue);
calculatePnl.add(lblResult);
calculatePnl.add(txtResult);
calculatePnl.add(btnCompute);
calculatePnl.add(btnCancel);

calculatePnl.setBorder(BorderFactory.createTitledBorder("Convert from"));

btnCompute.addActionListener(this);

} //end init


public void actionPerformed(ActionEvent ev){
if (ev.getSource() == btnCompute){
String input = txtValue.getText();//retrieve from textfield
double value = Double.parseDouble(input);
double result = 0;

// if the user wants to convert km to m
if (rbKm.isSelected() &&
rbToMetre.isSelected()){
result = value*1000;
}

txtResult.setText(String.valueOf(result));
}
} //end actionPerformed

public static void main(String args[]) {
ScaleConverter2 f = new ScaleConverter2();
f.setSize(400, 400);
f.setVisible(true);
f.setTitle("Scale Converter");
} //end main

} //end class


GUI Solution Only


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

public class ScaleConverter
extends JFrame {

private JLabel lblValue, lblResult;
private JButton btnCompute, btnCancel;
private JRadioButton rbKm, rbMetre, rbCm;
private JRadioButton rbToKm, rbToMetre, rbToCm;
private JPanel convertFromPnl, convertToPnl, calculatePnl;
private JTextField txtValue, txtResult;

public ScaleConverter() {
initConvertFromPnl();
initConvertToPnl();
initCalculatePnl();

getContentPane().setLayout(new GridLayout(3, 1));
getContentPane().add(convertFromPnl);
getContentPane().add(convertToPnl);
getContentPane().add(calculatePnl);

} //end constructor

public void initConvertFromPnl() {
convertFromPnl = new JPanel(new GridLayout(3, 1));
rbKm = new JRadioButton("Km");
rbMetre = new JRadioButton("Metre");
rbCm = new JRadioButton("Cm");
convertFromPnl.add(rbKm);
convertFromPnl.add(rbMetre);
convertFromPnl.add(rbCm);
convertFromPnl.setBorder(BorderFactory.createTitledBorder("Convert from"));
}

public void initConvertToPnl() {
convertToPnl = new JPanel(new GridLayout(3, 1));
rbToKm = new JRadioButton("Km");
rbToMetre = new JRadioButton("Metre");
rbToCm = new JRadioButton("Cm");
convertToPnl.add(rbToKm);
convertToPnl.add(rbToMetre);
convertToPnl.add(rbToCm);
convertToPnl.setBorder(BorderFactory.createTitledBorder("Convert from"));
}

public void initCalculatePnl() {
calculatePnl = new JPanel(new GridLayout(3, 2,5,5));
lblValue = new JLabel("Value");
lblResult = new JLabel("Result");
btnCompute = new JButton("Compute");
btnCancel = new JButton("Cancel");
txtValue = new JTextField(10);
txtResult = new JTextField(10);

calculatePnl.add(lblValue);
calculatePnl.add(txtValue);
calculatePnl.add(lblResult);
calculatePnl.add(txtResult);
calculatePnl.add(btnCompute);
calculatePnl.add(btnCancel);

calculatePnl.setBorder(BorderFactory.createTitledBorder("Convert from"));
} //end init

public static void main(String args[]) {
ScaleConverter f = new ScaleConverter();
f.setSize(400, 400);
f.setVisible(true);
f.setTitle("Scale Converter");
} //end main

} //end class

Setting Border

convertFromPnl.setBorder(BorderFactory.createTitledBorder("Convert From"));

Do this GUI

Demo02 : Event Handling


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

public class Demo02 extends JFrame
implements ActionListener{

private JButton btn1, btn2;
private JPanel northPanel;

public Demo02(){
btn1 = new JButton("Button 1");
btn2 = new JButton("Button 2");
northPanel = new JPanel();
northPanel.add(btn1);
northPanel.add(btn2);
getContentPane().add(northPanel,
BorderLayout.NORTH);
// Step 4:
btn1.addActionListener(this);
btn2.addActionListener(this);
}//end constructor


// Step 3: add this method
public void actionPerformed(ActionEvent ev){
if (ev.getSource() == btn1)
JOptionPane.showMessageDialog(null,
"Hi,you clicked button 1");
else if (ev.getSource() == btn2){
JOptionPane.showMessageDialog(null,
"Hi,you clicked button 2");
}
}//end actionPerformed


}//end class


Demo 01 : Event Handling


import javax.swing.*;
import java.awt.*; // Layout
// Step 1
import java.awt.event.*; // Event

public class Demo01 extends JFrame
/*Step 2*/ implements ActionListener{

private JButton btn1;
private JPanel northPanel;

public Demo01(){
btn1 = new JButton("Button 1");
northPanel = new JPanel();
northPanel.add(btn1);
getContentPane().add(northPanel,
BorderLayout.NORTH);
// Step 4:
btn1.addActionListener(this);
}//end constructor


// Step 3: add this method
public void actionPerformed(ActionEvent ev){
JOptionPane.showMessageDialog(null,
"Hi,you clicked button 1");
}//end actionPerformed


}//end class

Wednesday, November 22, 2006

Practical 08 Question 2


public class TestTourBookingFrame {

public static void main(String[] args) {

//(a)Create an instance of the
//TourBookingFrame named f.

TourBookingFrame f = new TourBookingFrame();
//(b)Set the title of f to be “Tour Booking Frame”.
f.setTitle("Tour Booking Frame");
//(c)Set the size of f to be 500 by 250.
f.setSize(500,250);
//(d)Set f to be visible.
f.setVisible(true);

f.show();
} //end main

}//end class

Practical 08 Question 1


//(a)Import all relevant packages
import javax.swing.*;
import java.awt.*; // Layout

/*(b)Write the codes to specify
TourBookingFrame as the subclass of JFrame.*/
public class TourBookingFrame extends JFrame{

private ButtonGroup buttongroup;
/*(c)Declare all the components in the JFrame
*/
private JLabel welcomeLbl;
private JTextArea detailsTxt;
private JRadioButton memberBtn, nonMemberBtn;
private JButton submitBtn, resetBtn;
// (d)Declare all the JPanels
private JPanel northPanel, centerPanel, southPanel;

public TourBookingFrame(){
//(e)Create northPanel and welcomeLbl.
// Add welcomeLbl to northPanel
northPanel = new JPanel();
welcomeLbl = new JLabel("Welcome to Tour Booking"
+ " System, enter your booking"
+ " details below");
northPanel.add(welcomeLbl);

// f) Create centerPanel and detailsTxt.
// Add detailsTxt to centerPanel.
// detailsTxt should be 10 rows 40 columns wide.
centerPanel = new JPanel();
detailsTxt = new JTextArea(10,40);
centerPanel.add(detailsTxt);

// (g) Create southPanel & component(s) in southPanel.
// Add the component(s) to southPanel.
southPanel = new JPanel();
memberBtn = new JRadioButton("Member");
nonMemberBtn = new JRadioButton("Non-member");
submitBtn = new JButton("Submit");
resetBtn = new JButton("Reset");
southPanel.add(memberBtn);
southPanel.add(nonMemberBtn);
southPanel.add(submitBtn);
southPanel.add(resetBtn);

buttongroup = new ButtonGroup();
buttongroup.add(memberBtn);
buttongroup.add(nonMemberBtn);

//(h)Which Layout Manager would the JFrame be using?
// Add all the JPanels to the respective areas of
//the content Pane of the JFrame.
getContentPane().add(northPanel, BorderLayout.NORTH);
getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(southPanel, BorderLayout.SOUTH);

} //end constructor

}//end class

Tuesday, November 21, 2006

Assignment Starter Kit



import javax.swing.*; // For JFrame, JButton etc
import java.awt.*; // For layout

public class QuizFrame extends JFrame {

private JLabel lblCategory;

private JPanel panelButtons;
private JButton btnPrev, btnNext;

public QuizFrame() {
makeNorth();
makeCenter();
makeSouth();

} //end constructor

public void makeNorth() {
lblCategory = new JLabel("IT Quiz");
getContentPane().add(lblCategory, "North");
}

public void makeCenter() {

}

public void makeSouth() {
// Step 1: Create Panel and components
panelButtons = new JPanel();
btnPrev = new JButton("Prev");
btnNext = new JButton("Next");
// Step 2: Add components to panel
panelButtons.add(btnPrev);
panelButtons.add(btnNext);

// Step 3:
getContentPane().add(panelButtons, "South");

}


} //end class




import javax.swing.*;
import java.awt.*; // Necessary for layout

public class DifferentLayouts extends JFrame {

private JButton b1, b2, b3, b4, b5, b6;


public DifferentLayouts() {

getContentPane().setLayout(new GridLayout(3,2));

b1 = new JButton("b1");
b2 = new JButton("b2");
b3 = new JButton("b3");
b4 = new JButton("b4");
b5 = new JButton("b5");
b6 = new JButton("b6");

getContentPane().add(b1);
getContentPane().add(b2);
getContentPane().add(b3);
getContentPane().add(b4);
getContentPane().add(b5);
getContentPane().add(b6);


} //end constructor

public static void main(String[] args) {
DifferentLayouts f;
f = new DifferentLayouts();
f.setSize(300, 300);
f.setVisible(true);
} //end main
} //end class


import javax.swing.*;

// In this example, no layout is specified
// BorderLayout applies becos JFrame uses BorderLayout
// by default
// Therefore, components must all have
// a direction specified

public class MyThirdGUI extends JFrame{

// Step 1: Declare the components
private JButton tongjin;
private JTextField ivan;

public MyThirdGUI(){
// Step 2: Create the component
tongjin = new JButton("Click me");
ivan = new JTextField(10);

// Step 3: Add the component to the container
getContentPane().add(tongjin,"South");
getContentPane().add(ivan);
}



public static void main(String args[]){
MyThirdGUI barnet = new MyThirdGUI();

barnet.setSize(100,200);
barnet.setVisible(true);

} //end main

}//end class




import javax.swing.*;

public class MySecondGUI extends JFrame{

// Step 1: Declare the componentw
private JButton tongjin;

public MySecondGUI(){
// Step 2: Create the component
tongjin = new JButton("Click me");

// Step 3: Add the component to the container
getContentPane().add(tongjin);
}



public static void main(String args[]){
MySecondGUI barnet = new MySecondGUI();

barnet.setSize(100,200);
barnet.setVisible(true);

} //end main

}//end class



// Step 1: Import the package classes
import javax.swing.*;

public class MyFirstGUI extends JFrame/*Step2*/{

public static void main(String args[]){

// Step 3: Instantiate an instance
MyFirstGUI yonghui= new MyFirstGUI();

// Step 4: Set the properties
yonghui.setSize(300,400);
yonghui.setVisible(true);

}//end main


}//end class

Friday, November 17, 2006

Practical 6 Additional Q1



public class Entry {

private String title, name, address;

// Purpose of a constructor:
// Initialise instance variables


public Entry(String title, String name, String address){
this.title = title;
this.name = name;
this.address = address;
} //end constructor

public void setTitle(String title){
this.title = title;
}

public void setName(String name){
this.name = name;
}

public void setAddress(String address){
this.address = address;
}

public void printEntryDetails(){

System.out.println("To:" + title + " " + name);
System.out.println("Address:" + address + "\n");

} //end printEntryDetails

}//end class





public class AddressBook {

public static void main(String[] args) {

Entry entry1, entry2, entry3;

entry1 = new Entry("Mr.", "Chris Howard Shin",
"1 Elm Street S(123456)");

entry2 = new Entry("Miss", "Mary Lim",
"Blk 222 Hougang Ave 4 S(530222)");

entry3 = new Entry("Mr.", "John Tang",
"Blk 333 Hougang Ave 1 S(530333)");

entry1.printEntryDetails();
entry2.printEntryDetails();
entry3.printEntryDetails();

entry1.setName("TCS");
entry2.setTitle("Mrs");
entry3.setAddress("Blk 333 Ang Mo Kio Ave 1 S(530333)");

entry1.printEntryDetails();
entry2.printEntryDetails();
entry3.printEntryDetails();


} //end main
}//end class

Friday, November 03, 2006

Solution for Mock Test (Available only until 10 Nov 2006)



import javax.swing.*;

public class VendingMachine {

public static int readChoice() {
String inputString;
int choice;
do {
inputString = JOptionPane.showInputDialog(null,
"Enter your choice of drink:\n"
+ "1. Coke (60 cents)\n"
+ "2. Pepsi (60 cents)\n"
+ "3. Soya Bean (50 cents)\n"
+ "4. Green Tea (70 cents)\n"
+ "5. Ice Coffee (80 cents)\n",
"SP Vendimatic Vending Machine",
JOptionPane.QUESTION_MESSAGE);
choice = Integer.parseInt(inputString);

if (choice < 1 || choice > 5) {
JOptionPane.showMessageDialog(null,
"Invalid input ! Please enter in the range from 1 to 5.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
} while (choice < 1 || choice > 5);

return choice;
}

public static int computeAndDisplayPrice(int choice) {
int price = 0;
switch (choice) {
case 1:
case 2:
price = 60;
break;
case 3:
price = 50;
break;
case 4:
price = 70;
break;
case 5:
price = 80;
}
JOptionPane.showMessageDialog(null,
"Price is " + price + " cents");
return price;
}

public static int readPayment(int price) {
String inputString;
int payment;
do {
inputString = JOptionPane.showInputDialog(null,
"Please enter your payment ("
+ price + " - 100 cents):\n",
"SP Vendimatic Vending Machine",
JOptionPane.QUESTION_MESSAGE);
payment = Integer.parseInt(inputString);

if (payment < price) {
JOptionPane.showMessageDialog(null,
"Invalid input ! Please enter a minimum payment of " +
price + " cents.",
"Error",
JOptionPane.ERROR_MESSAGE);
} else if (payment > 100) {
JOptionPane.showMessageDialog(null,
"Invalid input ! Please do not enter more than 100 cents.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
} while (payment < price || payment > 100);

return payment;
}

public static int computeAndDisplayChange(int payment, int price) {
int change;
change = payment - price;
JOptionPane.showMessageDialog(null, "Change is " + change + " cents.");
return change;
}

public static void dispenseChange(int change) {
int num50cents, num20cents, num10cents;
int balance;

num50cents = change / 50;
balance = change % 50;

num20cents = balance / 20;
balance = balance % 20;

num10cents = balance / 10;
String s = "Dispensing...\n"
+ num50cents + " x 50c coin\n"
+ num20cents + " x 20c coin\n"
+ num10cents + " x 10c coin";

JOptionPane.showMessageDialog(null, s );

}

public static void main(String[] args) {
int choice;
int price;
int payment;
int change;

String inputString;

char cont;

do {
choice = readChoice();
price = computeAndDisplayPrice(choice);
payment = readPayment(price);
change = computeAndDisplayChange(payment, price);

if (change > 0) {
dispenseChange(change);
}

do {
inputString = JOptionPane.showInputDialog(null,
"Do you want another drink (Y/N)?");
cont = inputString.charAt(0);

if (! (cont == 'Y' || cont == 'N' || cont == 'y' || cont == 'n')) {
JOptionPane.showMessageDialog(null,
"Invalid input ! Please enter Y or N.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
while (! (cont == 'Y' || cont == 'N' || cont == 'y' || cont == 'n'));

}
while (cont == 'Y' || cont == 'y');
JOptionPane.showMessageDialog(null,
"VendingMachine class program terminated.");

} //end main

} //end class