Exercise for Java Thirdyear

69
Chapter12 12.1 (Using the FlowLayoutmanager) Write a program that meets the following requirements ■Create a frame and set its layout to FlowLayout. ■Create two panels and add them to the frame. ■Each panel contains three buttons. The panel uses FlowLayout. import java.awt.*; import javax.swing.*; public class Exercise12_1 extends JFrame{ public Exercise12_1(){ setLayout(new FlowLayout(FlowLayout.LEFT,5,5)); JPanel p1=new JPanel(); p1.add(new JButton("Button 1")); p1.add(new JButton("Button 2")); p1.add(new JButton("Button 3")); JPanel p2=new JPanel(); p2.add(new JButton("Button 4")); p2.add(new JButton("Button 5")); p2.add(new JButton("Button 6")); add(p1); add(p2); } public static void main(String[] args){ Exercise12_1 frame=new Exercise12_1(); frame.setTitle("Exercise12_1"); frame.setSize(600,100); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } ------------------------------------------------------------------

description

Exercise for Java Thirdyear

Transcript of Exercise for Java Thirdyear

Page 1: Exercise for Java Thirdyear

Chapter1212.1 (Using the FlowLayoutmanager) Write a program that meets the following requirements

■Create a frame and set its layout to FlowLayout.

■Create two panels and add them to the frame.

■Each panel contains three buttons. The panel uses FlowLayout.

import java.awt.*;import javax.swing.*;public class Exercise12_1 extends JFrame{

public Exercise12_1(){setLayout(new FlowLayout(FlowLayout.LEFT,5,5));JPanel p1=new JPanel();p1.add(new JButton("Button 1"));p1.add(new JButton("Button 2"));p1.add(new JButton("Button 3"));JPanel p2=new JPanel();p2.add(new JButton("Button 4"));p2.add(new JButton("Button 5"));p2.add(new JButton("Button 6"));add(p1);add(p2);

}public static void main(String[] args){

Exercise12_1 frame=new Exercise12_1();frame.setTitle("Exercise12_1");frame.setSize(600,100);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}

------------------------------------------------------------------12.2. (Using the BorderLayoutmanager) Rewrite the preceding program to create the same user interface, but instead of using FlowLayoutfor the frame, use BorderLayout. Place one panel in the south of the frame and the other in thecenter.

import java.awt.*;

Page 2: Exercise for Java Thirdyear

import javax.swing.*;public class Exercise12_2 extends JFrame{

public Exercise12_2(){setLayout(new BorderLayout(5,5));JPanel p1=new JPanel(new FlowLayout(FlowLayout.LEFT,5,5));

p1.add(new JButton("Button 1"));p1.add(new JButton("Button 2"));p1.add(new JButton("Button 3"));JPanel p2=new JPanel(new FlowLayout(FlowLayout.LEFT,5,5));p2.add(new JButton("Button 4"));p2.add(new JButton("Button 5"));p2.add(new JButton("Button 6"));add(p1,BorderLayout.SOUTH);add(p2,BorderLayout.CENTER);

}public static void main(String[] args){

Exercise12_2 frame=new Exercise12_2();frame.setTitle("Exercise12_2");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}

12.4(UsingJPanelto group buttons) Rewrite the preceding program to create the same user interface. Instead of creating buttons and panels separately, define a class that extends the JPanel class. Place three buttons in your panel class, and create two panels from the user-defined panel class.

import java.awt.*;

import javax.swing.*;

public class Exercise12_4 extends JFrame{

public Exercise12_4(){

setLayout(new FlowLayout(FlowLayout.LEFT,5,5));

JPanel p1=new NewPanel("Button 1","Button 2","Button 3");

JPanel p2=new NewPanel("Button 4","Button 5","Button 6");

add(p1);

add(p2);

Page 3: Exercise for Java Thirdyear

}

public static void main(String[] args){

Exercise12_4 frame=new Exercise12_4();

frame.setTitle("Exercise12_4");

frame.setSize(600,100);

frame.setLocationRelativeTo(null);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

class NewPanel extends JPanel{

NewPanel(String s1,String s2,String s3){

add(new JButton(s1));

add(new JButton(s2));

add(new JButton(s3));

}

}

12.5. (Displaying labels) Write a program that displays four lines of text in four labels, as shown in Figure Add a line border on each label.

import java.awt.*;import javax.swing.*;import javax.swing.border.*;public class Exercise12_5 extends JFrame{

Exercise12_5(){

Page 4: Exercise for Java Thirdyear

JLabel l1=new JLabel("Department of ComputerScience");JLabel l2=new JLabel("School of Computing");JLabel l3=new JLabel("Armstrong Atlantic State University");JLabel l4=new JLabel("Tel:(921)");LineBorder lb=new LineBorder(Color.BLACK,1);l1.setBorder(lb);l2.setBorder(lb);l3.setBorder(lb);l4.setBorder(lb);setLayout(new GridLayout(4,1));add(l1);add(l2);add(l3);add(l4);

}public static void main(String[] args){

Exercise12_5 frame=new Exercise12_5();frame.setSize(300,200);frame.setTitle("Exercise12_5");frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}

12.6 Write a program that displays four icons in four labels, as shown in Figure 12.15(b). Add a line border on each label.

import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;public class Exercise12_6 extends JFrame{

public Exercise12_6(){JLabel l1=new JLabel(new ImageIcon("image/china.gif"));JLabel l2=new JLabel(new ImageIcon("image/my.gif"));JLabel l3=new JLabel(new ImageIcon("image/uk.gif"));JLabel l4=new JLabel(new ImageIcon("image/us.gif"));LineBorder lb=new LineBorder(Color.BLACK,1);l1.setBorder(lb);l2.setBorder(lb);l3.setBorder(lb);l4.setBorder(lb);setLayout(new GridLayout(2,2,3,3));add(l1);add(l2);add(l3);add(l4);

Page 5: Exercise for Java Thirdyear

}public static void main(String[] args){

Exercise12_6 frame=new Exercise12_6();frame.setTitle("Exercise12_6");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}_________________________________________________________________________

12.8. Display a frame that contains six labels. Set the background of the labels to white. Set the foreground of the labels to black, blue, cyan, green, magenta, and orange, respectively, as shown in Figure.Set the border of each label to a line border with the yellow color. Set the font of each label to TimesRoman, bold, and 20 pixels. Set the text and tool tip text of each label to the name of its foreground color.

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

public class Exercise12_8 extends JFrame{public Exercise12_8(){

setLayout(new GridLayout(2,3));JLabel black=new JLabel("black");JLabel blue=new JLabel("blue");JLabel cyan=new JLabel("cyan");JLabel green=new JLabel("green");JLabel magenta=new JLabel("magenta");JLabel orange=new JLabel("orange");black.setBackground(Color.WHITE);blue.setBackground(Color.WHITE);cyan.setBackground(Color.WHITE);green.setBackground(Color.WHITE);magenta.setBackground(Color.WHITE);orange.setBackground(Color.WHITE);black.setForeground(Color.BLACK);blue.setForeground(Color.BLUE);cyan.setForeground(Color.CYAN);green.setForeground(Color.GREEN);magenta.setForeground(Color.MAGENTA);orange.setForeground(Color.ORANGE);

Page 6: Exercise for Java Thirdyear

LineBorder l=new LineBorder(Color.YELLOW,2);Font f=new Font("TimesRoman",Font.BOLD,20);black.setBorder(l);blue.setBorder(l);cyan.setBorder(l);green.setBorder(l);magenta.setBorder(l);orange.setBorder(l);black.setFont(f);blue.setFont(f);cyan.setFont(f);green.setFont(f);magenta.setFont(f);orange.setFont(f);

black.setToolTipText("This is black");blue.setToolTipText("This is blue");cyan.setToolTipText("This is cyan");green.setToolTipText("This is green");magenta.setToolTipText("This is magenta");orange.setToolTipText("This is orange");add(black);add(blue);add(cyan);add(green);add(magenta);add(orange);

}public static void main(String[] args){

Exercise12_8 frame=new Exercise12_8();frame.setTitle("Exercise12_8");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}-----------------------------------------------

12.10.Write a program that displays a checkerboard in which each white and black cell is a JButtonwith a background black or white, as shown in Figure.

Page 7: Exercise for Java Thirdyear

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

public class Exercise12_9 extends JFrame{Exercise12_9(){

setLayout(new GridLayout(8,8));

for(int i=1;i<=8;i++){

for(int j=1;j<=4;j++){ if(i%2==0){

JButton b1=new JButton();b1.setBackground(Color.BLACK);JButton b2=new JButton();b2.setBackground(Color.WHITE);add(b1);add(b2);

}

else{

JButton b1=new JButton();b1.setBackground(Color.WHITE);JButton b2=new JButton();b2.setBackground(Color.BLACK);add(b1);add(b2);

}

}

}

public static void main(String[] args){Exercise12_9 frame=new Exercise12_9();frame.setTitle("Exercise12_9");

Page 8: Exercise for Java Thirdyear

frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}_________________________________________________________________________

Chapter1515.2(Creating a custom button class) Develop a custom button class named OvalButtonthat extends JButtonand displays the button text inside an oval. Figure shows two buttons created using the OvalButton class.

import javax.swing.*;

import java.awt.*;

public class Exercise15_2 extends JFrame {

private OvalButton jbtOk = new OvalButton("OK");

private OvalButton jbtCancel = new OvalButton("Cancle");

public Exercise15_2() {

setLayout(new FlowLayout());

add(jbtOk);

add(jbtCancel);

}

public static void main(String[] args) {

Exercise15_2 frame = new Exercise15_2();

frame.setTitle("Exercise15_2");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setLocationRelativeTo(null);

Page 9: Exercise for Java Thirdyear

frame.setVisible(true);

}

}

class OvalButton extends JButton {

public OvalButton() {

}

public OvalButton(String text) {

super(text);

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

System.out.println(getWidth());

System.out.println(getHeight());

g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);

}

public Dimension getPreferredSize() {

return new Dimension(100, 50);

}

}

______________________________________________________________________________

15.6The FigurePanel class in Listing 15.3 can display lines, rectangles, round-cornered rectangles, and ovals. Add appropriate new code in the class to display arcs and polygons. Write a test program to display the shapes as shown in Figure using the new FigurePanel class.

Page 10: Exercise for Java Thirdyear

import java.awt.*;import javax.swing.*;public class Exercise15_6 extends JFrame{

public Exercise15_6() {setLayout(new GridLayout(2,2));add(new FigureP(FigureP.A));add(new FigureP(FigureP.P));add(new FigureP(FigureP.A,true));add(new FigureP(FigureP.P,true));

}public static void main(String[] args){

Exercise15_6 frame=new Exercise15_6();frame.setTitle("Exercise15_6");frame.setSize(400,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}

class FigureP extends JPanel{

public static final int A=1;public static final int P=2;private int type=1;private boolean fill=false;

FigureP(){

}FigureP(int type){

this.type=type;

}FigureP(int type,boolean filled){

this.type=type;this.fill=filled;

}protected void paintComponent(Graphics g){

super.paintComponent(g);int xCenter =getWidth()/2;

int yCenter = getHeight()/2; int radius = (int)(Math.min(getWidth(), getHeight()*0.4));

int x = xCenter - radius; int y = yCenter - radius;

Page 11: Exercise for Java Thirdyear

if(type==A){

if(fill){

g.fillArc(x, y, 2*radius, 2*radius, 0, 30); g.fillArc(x, y, 2*radius, 2*radius, 90, 30); g.fillArc(x, y, 2*radius, 2*radius, 180, 30); g.fillArc(x, y, 2*radius, 2*radius, 270, 30); } else g.drawArc(x, y, 2*radius, 2*radius, 0, 30); g.drawArc(x, y, 2*radius, 2*radius, 90, 30); g.drawArc(x, y, 2*radius, 2*radius, 180, 30); g.drawArc(x, y, 2*radius, 2*radius, 270, 30);

}else if(type==P){

Polygon p=new Polygon();for(int i=0;i<6;i++){

p.addPoint((int)(xCenter+radius*Math.cos(2* i* Math.PI/6)),(int)( yCenter-radius*Math.sin(2*i*Math.PI/6)));

}if(fill)

g.fillPolygon(p);elseg.drawPolygon(p);

}}

public int getType() {return type;

}public void setType(int type) {

this.type = type;repaint();

}public boolean isFill() {

return fill;}public void setFill(boolean fill) {

this.fill = fill;repaint();

}public Dimension getPreferredSize(){

return new Dimension(80,80);}

}____________________________________________________________15.8 (Drawing an octagon) Write a program that draws an octagon, as shown inFigure.

Page 12: Exercise for Java Thirdyear

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

public class Exercise15_10 extends JFrame{public Exercise15_10() {add(new CylinderPanel());}public static void main(String[] args){

Exercise15_10 frame=new Exercise15_10();frame.setTitle("Exercise15_10");frame.setSize(300,300);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}class CylinderPanel extends JPanel{

protected void paintComponent(Graphics g) { super.paintComponent(g);

g.drawOval(40, 20, getWidth() - 40 * 2, 40);

g.drawArc(40, getHeight() - 60, getWidth() - 40 * 2, 40, 30, -230); g.drawArc(40, getHeight() - 60, getWidth() - 40 * 2, 40, 60, 15); g.drawArc(40, getHeight() - 60, getWidth() - 40 * 2, 40, 90, 15); g.drawArc(40, getHeight() - 60, getWidth() - 40 * 2, 40, 120, 15); g.drawLine(40, 40, 40, getHeight() - 40); g.drawLine(getWidth() - 40, 40, getWidth() - 40, getHeight() - 40); }

public Dimension getPreferredSize() { return new Dimension(200, 200); }}

_______________________________________________________________________15.16. Write a program that displays the message “Java is fun” in a panel. Set the panel’s font to TimesRoman, bold, and 20pixel. Display the font’s leading, ascent, descent, height, and the string width as a tool tip text for the panel, as shown in Figure.

Page 13: Exercise for Java Thirdyear

package chapter15;import java.awt.*;import javax.swing.*;public class Exercise15_16 extends JFrame{

public static void main(String[] args) { JFrame frame = new Exercise15_16(); frame.setSize(400, 200); frame.setTitle("Exercise15_16"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); }

public Exercise15_16() { add(new MyPanel()); }

class MyPanel extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); setFont(new Font("TimesRoman", Font.BOLD, 20));

FontMetrics fm = g.getFontMetrics();

g.drawString("Java is fun", 40, 40); setToolTipText("Ascent: " + fm.getAscent() + " " + "Descent: " + fm.getDescent() + " " + "Leading: " + fm.getLeading() + " " + "string width: " + fm.stringWidth("Java is fun")); } }}

__________________________________________________________________________________________15.22 (Displaying a STOP sign) Write a program that displays a STOP sign, as shown in Figure. The hexagon is in red and the sign is in white.

Page 14: Exercise for Java Thirdyear

package chapter15;import java.awt.*;import javax.swing.*;public class Exercise15_22 extends JFrame{

public Exercise15_22() { add(new StopSignPanel()); }

public static void main(String[] args) { Exercise15_22 frame = new Exercise15_22(); frame.setLocationRelativeTo(null); // Center the frame frame.setTitle("Exercise15_22"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 250); frame.setLocationRelativeTo(null); // Center the frame frame.setVisible(true); }}

class StopSignPanel extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g);

int xCenter = getWidth() / 2; int yCenter = getHeight() / 2; int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);

Polygon polygon = new Polygon();

// Add points to the polygon for (int i = 0; i < 8; i++) { polygon.addPoint((int)(xCenter + radius * Math.cos(i * 2 * Math.PI / 8 + 2 * Math.PI / 16)), (int)(yCenter - radius * Math.sin(i * 2 * Math.PI / 8 + 2 * Math.PI / 16))); }

// Draw the polygon g.setColor(Color.RED); g.fillPolygon(polygon);

g.setFont(new Font("Arial Black", Font.BOLD, 30));

Page 15: Exercise for Java Thirdyear

// Get font metrics for the current font FontMetrics fm = g.getFontMetrics();

// Find the center location to display int stringWidth = fm.stringWidth("STOP"); int stringAscent = fm.getAscent();

// Get the position of the leftmost character in the baseline int xCoordinate = getWidth() / 2 - stringWidth / 2; int yCoordinate = getHeight() / 2 + stringAscent / 2; System.out.println(getHeight()); System.out.println(stringAscent); System.out.println(yCoordinate);

g.setColor(Color.WHITE); g.drawString("STOP", xCoordinate, yCoordinate); }}

_______________________________________________________________________15.26 (Using the MessagePanel class) Write a program that displays four messages,as shown in Figure.

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

public class Exercise15_26 extends JFrame{ Exercise15_26() {

MessagePanel1 m1 = new MessagePanel1("Java"); MessagePanel1 m2 = new MessagePanel1("HTML"); MessagePanel1 m3 = new MessagePanel1("Tomcat"); MessagePanel1 m4 = new MessagePanel1("PHP");

m1.setCentered(true); m2.setCentered(true); m3.setCentered(true); m4.setCentered(true);

m1.setBackground(Color.white); m2.setBackground(Color.cyan); m3.setBackground(Color.white); m4.setBackground(Color.green);

Font font = new Font("TimezRoman", Font.ITALIC, 14);

m1.setFont(font); m2.setFont(font);

Page 16: Exercise for Java Thirdyear

m3.setFont(font); m4.setFont(font);

JPanel p = new JPanel(new GridLayout(3, 1)); p.add(m2); p.add(m3); p.add(m4);

add(m1, BorderLayout.CENTER); add(p, BorderLayout.EAST); }

public static void main(String[] args) { Exercise15_26 frame = new Exercise15_26(); frame.setSize(400, 400); frame.setTitle("Exercise15_26"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); // Center the frame frame.setVisible(true); }}

class MessagePanel1 extends JPanel{private int xCoordinate=20;private int yCoordinate=20;private boolean centered;private String message="Welcome to java";private int interval=10;MessagePanel1(){

}MessagePanel1(String message){

this.message=message;}public int getXCoordinate() {

return xCoordinate;}public void setXCoordinate(int coordinate) {

xCoordinate = coordinate;repaint();

}public int getYCoordinate() {

return yCoordinate;}public void setYCoordinate(int coordinate) {

yCoordinate = coordinate;repaint();

}public boolean isCentered() {

return centered;}public void setCentered(boolean centered) {

this.centered = centered;repaint();

}

Page 17: Exercise for Java Thirdyear

public String getMessage() {return message;

}public void setMessage(String message) {

this.message = message;repaint();

}public int getInterval() {

return interval;}public void setInterval(int interval) {

this.interval = interval;repaint();

}public void moveLeft(){

xCoordinate-=interval;repaint();

}public void moveRight(){

xCoordinate+=interval;repaint();

}public void moveUp(){

yCoordinate-=interval;repaint();

}public void moveDown(){

yCoordinate+=interval;repaint();

}public Dimension getPreferredSize(){

return new Dimension(200,30);}protected void paintComponent(Graphics g){

super.paintComponent(g);if(centered){

FontMetrics f=g.getFontMetrics();int stringWidth=f.stringWidth(message);int stringascent=f.getAscent();xCoordinate=getWidth()/2- stringWidth/2;yCoordinate=getHeight()/2 -stringascent/2;

}g.drawString(message, xCoordinate, yCoordinate);

}

}

____________________________________________________________________________

Chapter1616.2 (UsingComponentEvent) Any GUI component can fire a ComponentEvent. TheComponentListenerdefines the componentMoved,componentResized, componentShown, and componentHiddenmethods for processing componentevents. Write a test program to demonstrate ComponentEvent.

Page 18: Exercise for Java Thirdyear

import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Exercise16_2 extends JFrame{

Exercise16_2(){addComponentListener(new ComponentListener(){

public void componentMoved(ComponentEvent e){System.out.println("It is component moved.");

}public void componentResized(ComponentEvent e){

System.out.println("It is component resized.");}public void componentShown(ComponentEvent e){

System.out.println("It is component shown.");}public void componentHidden(ComponentEvent e){

System.out.println("It is component Hidden.");}

});

}public static void main(String[] args){

Exercise16_2 f=new Exercise16_2();f.setTitle("Exercise16_2");f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}

}__________________________________________________________________________________16.3* (Moving the ball) Write a program that moves the ball in a panel. You should define a panel class for displaying the ball and provide the methods for moving the button left, right, up, and down, as shown in Figure.

import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Exercise16_3 extends JFrame{

public static void main(String[] args){Exercise16_3 f=new Exercise16_3();f.setTitle("Exercise16_3");f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

Page 19: Exercise for Java Thirdyear

}private JButton jbtLeft=new JButton("Left");private JButton jbtRight=new JButton("Right");private JButton jbtUp=new JButton("Up");private JButton jbtDown=new JButton("Down");private CanvasPanel canvas=new CanvasPanel();Exercise16_3(){

JPanel p=new JPanel();p.add(jbtLeft);p.add(jbtRight);p.add(jbtUp);p.add(jbtDown);add(canvas,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);ButtonListener b=new ButtonListener();jbtLeft.addActionListener(b);jbtRight.addActionListener(b);jbtUp.addActionListener(b);jbtDown.addActionListener(b);

}class ButtonListener implements ActionListener{

public void actionPerformed(ActionEvent e){if(e.getSource()==jbtLeft)

canvas.Left();else if(e.getSource()==jbtRight)

canvas.Right();else if(e.getSource()==jbtUp)

canvas.Up();else if(e.getSource()==jbtDown)canvas.Down();

}}

class CanvasPanel extends JPanel{private int xCoordinate=80;private int yCoordinate=80;private int radius=8;

protected void paintComponent(Graphics g){super.paintComponent(g);g.drawOval(xCoordinate, yCoordinate, radius*2, radius*2);

}public void Left(){

if(xCoordinate < 0){xCoordinate =10; }

xCoordinate-=10;repaint();

}public void Right(){

if(xCoordinate > getWidth()){

xCoordinate=10;}

Page 20: Exercise for Java Thirdyear

xCoordinate+=10;repaint();

}public void Up(){

if(yCoordinate <0){yCoordinate=20;

}yCoordinate-=10;repaint();

}public void Down(){

if(yCoordinate>getHeight()){yCoordinate=20;

}yCoordinate+=10;repaint();

}

}

}______________________________________________________________________16.4(Creating a simple calculator) Write a program to perform add, subtract, multiply, and divide operation.

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

import java.awt.event.*;

public class Exercise16_4 extends JFrame{private JTextField jtn1=new JTextField(8);private JTextField jtn2=new JTextField(8);private JTextField jtresult=new JTextField(8);

private JLabel result=new JLabel();private JButton jbtAdd=new JButton("Add");private JButton jbtSubtract=new JButton("Subtract");private JButton jbtMultiply=new JButton("Multiply");private JButton jbtDivide=new JButton("Divide");Exercise16_4(){

JPanel p1=new JPanel();p1.add(new JLabel("Number 1"));p1.add(jtn1);

Page 21: Exercise for Java Thirdyear

p1.add(new JLabel("Number 2"));p1.add(jtn2);p1.add(new JLabel("Result"));p1.add(jtresult);jtresult.setEditable(false);jtresult.setHorizontalAlignment(SwingConstants.RIGHT);jtresult.setBorder(new LineBorder(Color.black,1));JPanel p2=new JPanel();p2.add(jbtAdd);p2.add(jbtSubtract);p2.add(jbtMultiply);p2.add(jbtDivide);p1.setBorder(new LineBorder(Color.black,1));p2.setBorder(new LineBorder(Color.black,1));setLayout(new BorderLayout(5,5));add(p1,BorderLayout.CENTER);add(p2,BorderLayout.SOUTH);ButtonListner listner=new ButtonListner();jbtAdd.addActionListener(listner);jbtSubtract.addActionListener(listner);jbtMultiply.addActionListener(listner);jbtDivide.addActionListener(listner);

}public static void main(String[] args){

Exercise16_4 f=new Exercise16_4();f.setTitle("Exercise16_4");f.pack();f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}class ButtonListner implements ActionListener{

public void actionPerformed(ActionEvent e){double n1=Double.parseDouble(jtn1.getText());double n2=Double.parseDouble(jtn2.getText());if(e.getSource()==jbtAdd){

jtresult.setText(String.format("%.1f", (n1+n2)));}else if(e.getSource()==jbtSubtract){

jtresult.setText(String.format("%.1f", (n1-n2)));}else if(e.getSource()==jbtMultiply){

jtresult.setText(String.format("%.1f", (n1*n2)));}else if(e.getSource()==jbtDivide){

jtresult.setText(String.format("%.1f", (n1/n2)));}

Page 22: Exercise for Java Thirdyear

}}

}___________________________________________________________________________16.5(Creating an investment-value calculator) Write a program that calculates thefuture value of an investment at a given interest rate for a specified number ofyears. The formula for the calculation is as follows:futureValue = investmentAmount * Math.pow(1 + monthlyInterestRate,noofyear*12)

Use text fields for interest rate, investment amount, and years. Display the futureamount in a text field when the user clicks the Calculate button.

import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Exercise16_5 extends JFrame{

private JTextField jtIA=new JTextField();private JTextField jtY=new JTextField();private JTextField jtAIR=new JTextField();private JTextField jtFV=new JTextField();private JButton jbtCalculate=new JButton("Calculate");public Exercise16_5() {

jtIA.setHorizontalAlignment(SwingConstants.RIGHT);jtY.setHorizontalAlignment(SwingConstants.RIGHT);jtAIR.setHorizontalAlignment(SwingConstants.RIGHT);jtFV.setHorizontalAlignment(SwingConstants.RIGHT);JPanel p1=new JPanel();p1.setLayout(new GridLayout(4,2));p1.add(new JLabel("Investment Amount"));p1.add(jtIA);p1.add(new JLabel("Years"));p1.add(jtY);p1.add(new JLabel("Annual Interest Rate"));p1.add(jtAIR);p1.add(new JLabel("Future Variable"));p1.add(jtFV);jtFV.setEditable(false);JPanel p2=new JPanel();p2.setLayout(new FlowLayout(FlowLayout.RIGHT));p2.add(jbtCalculate);add(p1,BorderLayout.CENTER);add(p2,BorderLayout.SOUTH);

Page 23: Exercise for Java Thirdyear

jbtCalculate.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){

double ia=Double.parseDouble(jtIA.getText());double y=Double.parseDouble(jtY.getText());double air=Double.parseDouble(jtAIR.getText());double mir=air/1200;double fa=ia*Math.pow(1+mir,y*12);jtFV.setText(String.format("%.2f", fa));

}});

}public static void main(String[] args){

Exercise16_5 frame=new Exercise16_5();frame.setTitle("Exercise16_5");frame.pack();frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}

}_______________________________________________________________________________________16.6** (Alternating two messages) Write a program to rotate with a mouse click two messages displayed on a panel, “Java is fun” and “Java is powerful”.

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

public class Exercise16_6 extends JFrame { private DisplayPanel panel = new DisplayPanel();

public Exercise16_6() { add(panel,BorderLayout.CENTER);

add(panel, BorderLayout.CENTER); panel.setFocusable(true); }

/** Main method */ public static void main(String[] args) { JFrame frame = new Exercise16_6(); frame.setTitle("Exercise16_6"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

Page 24: Exercise for Java Thirdyear

class DisplayPanel extends JPanel { private String m1 = "Java is fun"; private String m2 = "Java is powerful"; private String message=m1;

public DisplayPanel() { addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(message.equals(m1)) message=m2; else message=m1; repaint(); } }); } protected void paintComponent(Graphics g){ super.paintComponent(g); FontMetrics fm=g.getFontMetrics(); int sw=fm.stringWidth(message); int sa=fm.getAscent(); int x=getWidth()/2-sw/2; int y=getHeight()/2+sa/2; g.drawString(message, x, y); }}}_______________________________________________________________________16.8 (Displaying the mouse position) Write two programs, such that one displays the mouse position when the mouse is clicked and the other displays the mouse position when the mouse is pressed and ceases to display it when the mouse is released.

import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Exercise16_8 extends JFrame{

public static void main(String[] args){Exercise16_8 frame=new Exercise16_8();frame.setTitle("Exercise16_8");frame.setSize(300,200);

Page 25: Exercise for Java Thirdyear

frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}Exercise16_8(){

DisplayPanel panel=new DisplayPanel();add(panel);

}class DisplayPanel extends JPanel{

private int xc=0;private int yc=0; public DisplayPanel(){

addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){

xc=e.getX(); yc=e.getY(); repaint();

} });

}protected void paintComponent(Graphics g){

super.paintComponent(g); g.drawString("(" + xc + ", " + yc + ")", xc, yc);

}}

}__________________________________________________________________________16-9. (Drawing lines using the arrow keys) Write a program that draws line segments using the arrow keys. The line starts from the center of the frame and draws toward east, north, west, or south when the right-arrow key, up-arrow key, left arrow key, or down-arrow key is clicked, as shown in Figure.

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

import java.awt.event.*;public class Exercise16_9 extends JFrame{

public static void main(String[] args){Exercise16_9 f=new Exercise16_9();f.setTitle("Exercise16_9");f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Page 26: Exercise for Java Thirdyear

f.setVisible(true);}Exercise16_9(){

KeyPanel p=new KeyPanel();add(p);p.setFocusable(true);

}class KeyPanel extends JPanel{

private int x1;private int y1;private int x2;private int y2;boolean firstTime=true;

KeyPanel(){

addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){

switch(e.getKeyCode()){case KeyEvent.VK_UP: x1=x2;y1=y2;y2-=10; break;case KeyEvent.VK_DOWN: x1=x2;y1=y2; y2+=10;break;case KeyEvent.VK_RIGHT: x1=x2;y1=y2;x2+=10; break;case KeyEvent.VK_LEFT:x1=x2;y1=y2; x2-=10;break;}repaint();

}});

}protected void paintComponent(Graphics g){

if(firstTime) { x2= x1= getWidth() / 2;

y2= y1 = getHeight() / 2; firstTime = false; }

g.drawLine(x1, y1, x2, y2);}

}____________________________________________________________________________________16.10**(Entering and displaying a string) Write a program that receives a string from the keyboard and displays it on a panel. The Enter key signals the end of a string. Whenever a new string is entered, it is displayed on the panel.import java.awt.*;import javax.swing.*;

import java.awt.event.*;public class Exercise16_10 extends JFrame{

Page 27: Exercise for Java Thirdyear

public static void main(String[] args){Exercise16_10 f=new Exercise16_10();f.setTitle("Exercise16_10");f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}Exercise16_10(){

DisplayPanel p=new DisplayPanel();add(p);p.setFocusable(true);

} class DisplayPanel extends JPanel {

private String message = "Welcome to java"; private StringBuffer buffer = new StringBuffer();

public DisplayPanel() { this.addKeyListener(new Listener()); // Add listener } class Listener extends KeyAdapter {

public void keyTyped(KeyEvent e) { buffer.append(e.getKeyChar()); }

public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { message=String.valueOf(buffer); buffer.setLength(0); repaint(); } } } protected void paintComponent(Graphics g){ super.paintComponent(g); FontMetrics fm=g.getFontMetrics(); int sw=fm.stringWidth(message); int sa=fm.getAscent(); int x=getWidth()/2-sw/2; int y=getHeight()/2+sa/2; g.drawString(message, x, y); }

}

}_______________________________________________________16.14**(Raising flag) Write a Java program that animates raising a flag, as shown inFigure.

Page 28: Exercise for Java Thirdyear

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

import java.awt.event.*;public class Exercise16_14 extends JFrame{

public static void main(String[] args){Exercise16_14 f=new Exercise16_14();f.setTitle("Exercise16_14");f.setSize(500,300);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}Exercise16_14(){

add(new FlagPanel());}class FlagPanel extends JPanel{ private int xc=20;private int yc=200;

private Image image=new ImageIcon("image/fr.gif").getImage();FlagPanel(){

Timer t=new Timer(500,new ActionListener(){public void actionPerformed(ActionEvent e){

repaint();}

});t.start();

}protected void paintComponent(Graphics g){

super.paintComponent(g);if(yc<0)

yc=200;yc-=5;g.drawImage(image, xc, yc, this);

}}

}_______________________________________________________________16.26** (Moving a circle using mouse) Write a program that displays a circle with radius 10pixels. You can point the mouse inside the circle and drag (i.e., move with mouse pressed) the circle wherever the mouse goes, as shown in Figure.

Page 29: Exercise for Java Thirdyear

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

import java.awt.event.*;public class Exercise16_26 extends JFrame{

public static void main(String[] args) { Exercise16_26 frame = new Exercise16_26(); frame.setSize(300, 400); frame.setTitle("Exercise16_26"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); // Center the frame frame.setVisible(true); }public Exercise16_26() {

add(new MovingCircle());}

class MovingCircle extends JPanel {

private int x = 20; private int y = 20; public int RADIUS = 10;

public MovingCircle() { this.addMouseMotionListener(new MouseAdapter() { public void mouseDragged(MouseEvent e) { if (insideCircle(e.getX(), e.getY(),x,y)) { x = e.getX(); y = e.getY(); repaint(); } } }); } public boolean insideCircle(double x1,double y1,double x2,double y2){

return Math.sqrt((x2-x2)*(x2-x1)+(y2-y1)*(y2-y1)) < RADIUS; }

public void paintComponent(Graphics g) {

Page 30: Exercise for Java Thirdyear

super.paintComponent(g);

g.drawOval(x - RADIUS, y - RADIUS, 2 * RADIUS, 2 * RADIUS); }}

}________________________________________________________________________16.27 Write a program that displays a circle of radius 10pixels filled with a random color at a random location on a panel, as shown in Figure. When you click the circle, it is gone and a new random-color circle is displayed at another random location. After twenty circles are clicked, display the time spent in the panel, as shown in Figure.

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

import java.awt.event.*;public class Exercise16_27 extends JFrame{

public static void main(String[] args) { Exercise16_27 frame = new Exercise16_27(); frame.setLocationRelativeTo(null); // Center the frame frame.setTitle("Exercise16_27"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 250); frame.setLocationRelativeTo(null); // Center the frame frame.setVisible(true); }

Exercise16_27(){ add(new RandomCircle());

}class RandomCircle extends JPanel{private int x = 20;

private int y = 20;

public int RADIUS = 10;

private long count = 0L;

private long startTime = System.currentTimeMillis();

public RandomCircle(){addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {if (insideCircle(x,y,e.getX(), e.getY()))

repaint();}});}

Page 31: Exercise for Java Thirdyear

public boolean insideCircle(double x1,double y1,double x2,double y2){ return Math.sqrt((x2-x2)*(x2-x1)+(y2-y1)*(y2-y1)) < RADIUS;

}

public void paintComponent(Graphics g){super.paintComponent(g);

if (count > 20L) {long endTime = System.currentTimeMillis();g.drawString("Time spent: " + (endTime - startTime) +" milliseconds", 20, 20);} else {count ++;

x = (int)(getWidth() * Math.random());y = (int)(getHeight() * Math.random());

g.setColor(new Color((int)(Math.random() * 255.0D),(int)(Math.random() * 255.0D), (int)(Math.random() * 255.0D)));g.fillOval(x - RADIUS, y - RADIUS, 2 * RADIUS, 2 * RADIUS);}}}

}

_________________________________________________________________________16.36* (Flipping coins) Write a program that displays head (H) or tail (T) for each of nine coins, as shown in Figure 16.33. When a cell is clicked, the coin is flipped. A cell is a JLable. Write a custom cell class that extends JLablewith the mouse listener for handling the clicks. When the program starts, all cells initially display H.

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

import java.awt.event.*;public class Exercise16_36 extends JFrame{

public static void main(String[] args) { Exercise16_36 frame = new Exercise16_36(); frame.setLocationRelativeTo(null); // Center the frame frame.setTitle("Exercise16_36"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,200); frame.setLocationRelativeTo(null); // Center the frame frame.setVisible(true); }

Page 32: Exercise for Java Thirdyear

public Exercise16_36() { setLayout(new GridLayout(3,3));for(int i=0;i<9;i++){

CoinPanel c=new CoinPanel("H");add(c);c.setBorder(new LineBorder(Color.black,1));c.setFont(new Font("TimeRoman",Font.BOLD,20)); c.setHorizontalAlignment(JLabel.CENTER);

}

} class CoinPanel extends JLabel{

CoinPanel(String message){ super(message);

addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e){

if(getText().equals("H")){ setText("T");

} else

setText("H");

}});

}

}

}____________________________________________________________________________

Chapter1717.1 Rewrite Listing 17.2 to add a group of radio buttons to select background colors. The available colors are red, yellow, white, gray, and green.

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.TitledBorder;

import java.awt.event.*;

Page 33: Exercise for Java Thirdyear

public class Exercise17_1 extends JFrame{private MessagePanel canvas=new MessagePanel("Welcome to java");private JButton b1=new JButton("<=");private JButton b2=new JButton("=>");JRadioButton jb1=new JRadioButton("Red");JRadioButton jb2=new JRadioButton("Yellow");JRadioButton jb3=new JRadioButton("White");JRadioButton jb4=new JRadioButton("Gray");JRadioButton jb5=new JRadioButton("Green");public Exercise17_1() {

JPanel p=new JPanel();p.add(b1);p.add(b2);ButtonGroup bg=new ButtonGroup();bg.add(jb1);bg.add(jb2);bg.add(jb3);bg.add(jb4);bg.add(jb5);JPanel p1=new JPanel();p1.setLayout(new GridLayout(1,5));p1.add(jb1);p1.add(jb2);p1.add(jb3);p1.add(jb4);p1.add(jb5);p1.setBorder(new TitledBorder("Select Message Panel Background"));add(p1,BorderLayout.NORTH);add(canvas,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);jb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.setBackground(Color.RED);

}});jb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.setBackground(Color.YELLOW);

}});jb3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.setBackground(Color.WHITE);

}});jb4.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.setBackground(Color.GRAY);

}});jb5.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.setBackground(Color.GREEN);

}});

Page 34: Exercise for Java Thirdyear

b1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){

canvas.moveLeft();}

});b2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){canvas.moveRight();

}});jb3.setSelected(true);canvas.setBackground(Color.WHITE);

}public static void main(String[] args){

Exercise17_1 f=new Exercise17_1();f.setTitle("Exercise17_1");f.pack();//f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}

}_________________________________________________________________________17.2 Write a program that draws various figures, as shown in Figure 17.34. The user selects a figure from a radio button and specifies whether it is filled in a check box. (Hint: Use the FigurePanel class introducedin Listing 15.3 to display a figure.)

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;

import java.awt.event.*;public class Exercise17_2 extends JFrame{

public static void main(String[] args){Exercise17_2 frame=new Exercise17_2();frame.setTitle("Exercise17_2");frame.pack();frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Page 35: Exercise for Java Thirdyear

frame.setVisible(true);}private FigurePanel fp=new FigurePanel();private JRadioButton jrb1=new JRadioButton("Line");private JRadioButton jrb2=new JRadioButton("Rectangle");private JRadioButton jrb3=new JRadioButton("Oval");private JCheckBox jck1=new JCheckBox("Filled");public Exercise17_2() {

ButtonGroup group=new ButtonGroup();group.add(jrb1);group.add(jrb2);group.add(jrb3);setLayout(new BorderLayout(5,5));JPanel p=new JPanel();p.setLayout(new GridLayout(1,4,5,5));p.add(jrb1);p.add(jrb2);p.add(jrb3);p.add(jck1);p.setBorder(new LineBorder(Color.BLACK,2));fp.setBorder(new LineBorder(Color.BLACK,2));add(fp,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);jrb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){fp.setType(FigurePanel.LINE);

}});jrb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){fp.setType(FigurePanel.RECTANGLE);

}});jrb3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){fp.setType(FigurePanel.OVAL);

}});jck1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){fp.setFilled(jck1.isSelected());

}});jck1.setSelected(true);jrb3.setSelected(true);fp.setType(FigurePanel.OVAL);fp.setFilled(true);

}

}_______________________________________________________________17.3**(Traffic lights) Write a program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time (see Figure 17.35). No light is on when the program starts.

Page 36: Exercise for Java Thirdyear

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;

import java.awt.event.*;

public class Exercise17_3 extends JFrame{public static void main(String[] args){

Exercise17_3 frame=new Exercise17_3();frame.setTitle("Exercise17_3");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}private Canvas c=new Canvas();private JRadioButton jrb1=new JRadioButton("Red");private JRadioButton jrb2=new JRadioButton("Green");private JRadioButton jrb3=new JRadioButton("BLue");

Exercise17_3(){ButtonGroup bg=new ButtonGroup();bg.add(jrb1);bg.add(jrb2);bg.add(jrb3);JPanel p=new JPanel();p.setLayout(new GridLayout(1,3));p.add(jrb1);p.add(jrb2);p.add(jrb3);jrb1.setMnemonic('R');jrb2.setMnemonic('G');jrb3.setMnemonic('B');c.setBorder(new LineBorder(Color.black,1));p.setBorder(new LineBorder(Color.black,1));setLayout(new BorderLayout(5,5));add(c,BorderLayout.CENTER);

add(p,BorderLayout.SOUTH);jrb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){//c.red();c.setC1(true);c.setC2(false);c.setC3(false);

Page 37: Exercise for Java Thirdyear

}});jrb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

c.setC2(true);c.setC1(false);c.setC3(false);

}});jrb3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

c.setC3(true);c.setC1(false);c.setC2(false);

}});jrb3.setSelected(true);c.setC3(true);

}class Canvas extends JPanel{

private boolean c1,c2,c3=false;

public boolean isC1() {return c1;

}

public void setC1(boolean c1) {this.c1 = c1;repaint();

}

public boolean isC2() {return c2;

}

public void setC2(boolean c2) {this.c2 = c2;repaint();

}

public boolean isC3() {return c3;

}

public void setC3(boolean c3) {this.c3 = c3;repaint();

}

Page 38: Exercise for Java Thirdyear

protected void paintComponent(Graphics g){super.paintComponent(g);int xc=getWidth()/2;int yc=getHeight()/2;g.drawRect(xc-12, yc-36, 24, 72);if(c1){g.setColor(Color.RED);g.fillOval(xc-10,yc-34, 20, 20);g.setColor(Color.BLACK);g.drawOval(xc-10, yc-10, 20, 20);g.drawOval(xc-10, yc+14, 20, 20);

}if(c2){

g.setColor(Color.GREEN);g.fillOval(xc-10, yc-10, 20, 20);g.setColor(Color.BLACK);g.drawOval(xc-10, yc+14, 20, 20);g.drawOval(xc-10,yc-34, 20, 20);

}

if(c3){g.setColor(Color.BLUE);g.fillOval(xc-10, yc+14, 20, 20);g.setColor(Color.BLACK);g.drawOval(xc-10, yc-10, 20, 20);

g.drawOval(xc-10,yc-34, 20, 20);

}

}}

}__________________________________________________________________________17.4 Write a program that displays a text file in a text area, as shown in Figure 17.36. The user enters a file name in a text field and clicks the View button; the file is then displayed in a text area.

package ch17;import java.awt.*;import javax.swing.*;import java.io.*;import java.util.*;

import java.awt.event.*;public class Exercise17_4 extends JFrame{

Page 39: Exercise for Java Thirdyear

public static void main(String[] args){Exercise17_4 frame=new Exercise17_4();

frame.setTitle("Exercise17_4");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}private JTextArea jta=new JTextArea();private JTextField jtf=new JTextField(10);private JButton jbt=new JButton("View");public Exercise17_4() {

JLabel jlb=new JLabel("FileName");JPanel p=new JPanel();p.add(jlb);p.add(jtf);p.add(jbt);JScrollPane sp=new JScrollPane(jta);

jta.setLineWrap(true); jta.setWrapStyleWord(true); add(sp,BorderLayout.CENTER); add(p,BorderLayout.SOUTH); jbt.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){ try{ String fn=jtf.getText(); Scanner input=new Scanner(new File(fn)); while(input.hasNext()){

String l=input.nextLine(); jta.append(l+"\n");

} } catch(Exception ex){

ex.printStackTrace(); }

}

});

}

}______________________________________________________________________17.6 Write a program that converts miles and kilometers, as shown in Figure 17.37. If you enter a value in the Mile text field and press the Enter key, the corresponding kilometer is displayed in the Kilometer text field. Likewise, if you enter a value in the Kilometer text field and press the Enter key, the corresponding mile is displayed in the Mile text field.

Page 40: Exercise for Java Thirdyear

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;

import java.awt.event.*;

public class Exercise17_6 extends JFrame{public static void main(String[] args){

Exercise17_6 f=new Exercise17_6();f.setTitle("Exercise17_6");

f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JTextField jtf1=new JTextField();private JTextField jtf2=new JTextField();Exercise17_6(){

JPanel p=new JPanel();p.setLayout(new GridLayout(2,1,3,3));p.add(new JLabel("Mile"));p.add(new JLabel("Kilometer"));JPanel p2=new JPanel();p2.setLayout(new GridLayout(2,1,2,2));p2.add(jtf1);p2.add(jtf2);jtf1.setHorizontalAlignment(SwingConstants.LEFT);jtf2.setHorizontalAlignment(SwingConstants.LEFT);

p.setBorder(new LineBorder(Color.black,1));p2.setBorder(new LineBorder(Color.black,1));setLayout(new BorderLayout(5,5));add(p,BorderLayout.WEST);add(p2,BorderLayout.CENTER);jtf1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){double mile=Double.parseDouble(jtf1.getText());double kg=mile*1.6023732254464;jtf2.setText(String.valueOf(kg));

}});jtf2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){double kg=Double.parseDouble(jtf2.getText());double mi=kg/1.6023732254464;jtf1.setText(String.valueOf(mi));

}});

}

}_________________________________________________________________________

Page 41: Exercise for Java Thirdyear

17.8**(Selecting a font) Write a program that can dynamically change the font of a message to be displayed on a panel. The message can be displayed in bold and italic at the same time, or can be displayed in the center of the panel. You can select the font name or font size from combo boxes, as shown in Figure 17.39. The available font names can be obtained using getAvailableFontFamilyNames()in GraphicsEnvironment(§12.8, “The FontClass”). The combo box for font size is initialized with numbers from 1to100.

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;

import java.awt.event.*;public class Exercise17_8 extends JFrame{

public static void main(String[] args){Exercise17_8 frame=new Exercise17_8();frame.setTitle("Exercise17_8");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}private JComboBox jcb1=new JComboBox();private JComboBox jcb2=new JComboBox();private JCheckBox jck1=new JCheckBox("Centered");private JCheckBox jck2=new JCheckBox("Bold");private JCheckBox jck3=new JCheckBox("Italic");private Canvas c=new Canvas("Java is Cool");Exercise17_8(){

GraphicsEnvironment e=GraphicsEnvironment.getLocalGraphicsEnvironment();String[] s=e.getAvailableFontFamilyNames();for(int i=0;i<s.length;i++){

jcb1.addItem(s[i]);}for(int i=1;i<=100;i++){

jcb2.addItem(i);}JPanel p1=new JPanel(new BorderLayout(5,5));p1.add(new JLabel("Font Name"),BorderLayout.WEST);p1.add(jcb1,BorderLayout.CENTER);p1.setBorder(new LineBorder(Color.BLACK,1));JPanel p2=new JPanel(new BorderLayout(5,5));p2.add(new JLabel("Font Size"),BorderLayout.WEST);p2.add(jcb2,BorderLayout.CENTER);JPanel p=new JPanel(new BorderLayout(5,5));p.add(p1,BorderLayout.CENTER);p.add(p2,BorderLayout.EAST);p.setBorder(new LineBorder(Color.black,1));JPanel p3=new JPanel();p3.add(jck1);

Page 42: Exercise for Java Thirdyear

p3.add(jck2);p3.add(jck3);setLayout(new BorderLayout(5,5));add(p,BorderLayout.NORTH);add(c,BorderLayout.CENTER);add(p3,BorderLayout.SOUTH);

jck1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){

c.setCenter(jck1.isSelected());

}});jck2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

Font f=c.getFont();if(jck1.isSelected()){c.setFont(new Font(f.getName(),jck2.isSelected()? Font.BOLD :

Font.PLAIN ,f.getSize()));}else

c.setFont(new Font(f.getName(),jck2.isSelected()? Font.PLAIN : Font.PLAIN ,f.getSize()));

}});jck3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

Font f=c.getFont();if(jck3.isSelected())

c.setFont(new Font(f.getName(),jck2.isSelected()? Font.ITALIC : Font.PLAIN ,f.getSize()));

elsec.setFont(new Font(f.getName(),jck2.isSelected()?

Font.PLAIN : Font.PLAIN ,f.getSize()));

}});jcb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){String s=(String)jcb1.getSelectedItem();Font f=c.getFont();c.setFont(new Font(s,f.getStyle(),f.getSize()));

}});jcb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){int i=jcb2.getSelectedIndex();Font f=c.getFont();

Page 43: Exercise for Java Thirdyear

c.setFont(new Font(f.getName(),f.getStyle(),(i+1)));

}});jck1.setSelected(true);c.setCenter(true);jck2.setSelected(true);jcb1.setSelectedItem("SansSerif");jcb2.setSelectedItem(18);

}class Canvas extends JPanel{

private int xc=20;private int yc=20;private boolean center;private String message="Welcome to java";Canvas(String s){

message=s;}

public boolean isCenter() {return center;

}

public void setCenter(boolean center) {this.center = center;repaint();

}protected void paintComponent(Graphics g){

super.paintComponent(g);int xc=20;int yc=20;

if(center){FontMetrics fm=g.getFontMetrics();int sw=fm.stringWidth(message);int sa=fm.getAscent();xc=getWidth()/2-sw/2;yc=getHeight()/2-sa/2;

}g.drawString(message, xc, yc);

}

}

}______________________________________________________________________

Page 44: Exercise for Java Thirdyear

17.9 Write a program to let the user dynamically set the properties horizontalAlignment, verticalAlignment, horizontalTextAlignment, and verticalTextAlignment, as shown in Figure.

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;import javax.swing.border.TitledBorder;

import java.awt.event.*;public class Exercise17_9 extends JFrame{

public static void main(String[] args){Exercise17_9 frame=new Exercise17_9();frame.setTitle("Exercise17_9");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}private String[] hs={"LEFT","LEADING","CENTER","RIGHT","TRAILING"};private String[] vs={"TOP","CENTER","BOTTOM"};private JComboBox jcb1=new JComboBox(hs);private JComboBox jcb2=new JComboBox(vs);private JComboBox jcb3=new JComboBox(hs);private JComboBox jcb4=new JComboBox(vs);private JLabel l=new JLabel("Grapes");private ImageIcon ic=new ImageIcon("image/grapes.gif");

public Exercise17_9() {l.setIcon(ic);LineBorder lb=new LineBorder(Color.BLACK,2);JPanel p1=new JPanel(new GridLayout(2,1,5,5));p1.add(new JLabel("Horizontal"));p1.add(new JLabel("Vertical"));p1.setBorder(lb);JPanel p2=new JPanel(new GridLayout(2,1,5,5));p2.add(jcb1);p2.add(jcb2);p2.setBorder(lb);JPanel p=new JPanel(new BorderLayout(5,5));p.add(p1,BorderLayout.WEST);p.add(p2,BorderLayout.CENTER);p.setBorder(new TitledBorder("Horizontal Alignment"));JPanel p3=new JPanel(new GridLayout(2,1,5,5));p3.add(new JLabel("Horizontal"));p3.add(new JLabel("Vertical"));JPanel p4=new JPanel(new GridLayout(2,1,5,5));p4.add(jcb3);

Page 45: Exercise for Java Thirdyear

p4.add(jcb4);JPanel pp=new JPanel(new BorderLayout(5,5));pp.add(p3,BorderLayout.WEST);pp.add(p4,BorderLayout.CENTER);pp.setBorder(new TitledBorder("Text Position"));

JPanel Jp=new JPanel(new GridLayout(1,2,5,5));Jp.add(p);Jp.add(pp);Jp.setBorder(lb);setLayout(new GridLayout(2,1,5,5));add(l);add(Jp);l.setHorizontalAlignment(SwingConstants.LEFT);l.setVerticalAlignment(SwingConstants.TOP);l.setHorizontalTextPosition(SwingConstants.LEFT);l.setVerticalTextPosition(SwingConstants.TOP);

jcb1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){

switch(jcb1.getSelectedIndex()){case 0: l.setHorizontalAlignment(SwingConstants.LEFT);break;case 1: l.setHorizontalAlignment(SwingConstants.LEADING);break;case 2: l.setHorizontalAlignment(SwingConstants.CENTER);break;case 3: l.setHorizontalAlignment(SwingConstants.RIGHT);break;case 4: l.setHorizontalAlignment(SwingConstants.TRAILING);break;}

}});jcb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){switch(jcb2.getSelectedIndex()){case 0: l.setVerticalAlignment(SwingConstants.TOP);break;case 1: l.setVerticalAlignment(SwingConstants.CENTER);break;case 2: l.setVerticalAlignment(SwingConstants.BOTTOM);break;

}}

});jcb3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){switch(jcb3.getSelectedIndex()){case 0: l.setHorizontalTextPosition(SwingConstants.LEFT);break;case 1: l.setHorizontalTextPosition(SwingConstants.LEADING);break;case 2: l.setHorizontalTextPosition(SwingConstants.CENTER);break;case 3: l.setHorizontalTextPosition(SwingConstants.RIGHT);break;case 4: l.setHorizontalTextPosition(SwingConstants.TRAILING);break;}

}});jcb4.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){switch(jcb4.getSelectedIndex()){case 0: l.setVerticalTextPosition(SwingConstants.TOP);break;case 1: l.setVerticalTextPosition(SwingConstants.CENTER);break;

Page 46: Exercise for Java Thirdyear

case 2: l.setVerticalTextPosition(SwingConstants.BOTTOM);break;

}}

});

}}_________________________________________________________________17.11 Write a program that sets the horizontal-alignment and column-size properties of a text field dynamically, as shown in Figure.

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;import javax.swing.border.TitledBorder;

import java.awt.event.*;public class Exercise17_11 extends JFrame{

public static void main(String[] args){Exercise17_11 frame=new Exercise17_11();frame.setTitle("Exercise17_11");//frame.setSize(300,200);frame.pack();frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}private JTextField jtf1=new JTextField("Tye any thing");private JTextField jtf2=new JTextField("30");private JRadioButton l=new JRadioButton("Left");private JRadioButton c=new JRadioButton("Center");private JRadioButton r=new JRadioButton("Right");

public Exercise17_11() {ButtonGroup bg=new ButtonGroup();bg.add(l);bg.add(c);bg.add(r);JPanel p1=new JPanel(new GridLayout(1,3,5,5));p1.add(l);p1.add(c);p1.add(r);p1.setBorder(new TitledBorder("Horizontal Alignment"));JPanel p2=new JPanel(new GridLayout(1,2,5,5));p2.add(new JLabel("Column size"));p2.add(jtf2);

Page 47: Exercise for Java Thirdyear

p2.setBorder(new LineBorder(Color.BLACK,1));JPanel p=new JPanel(new BorderLayout(5,5));p.add(p1,BorderLayout.CENTER);p.add(p2,BorderLayout.EAST);

JPanel p4=new JPanel(new FlowLayout(FlowLayout.LEFT));

p4.add(new JLabel("Text Field"));p4.add(jtf1);setLayout(new BorderLayout(5,5));add(p4,BorderLayout.NORTH);add(p,BorderLayout.CENTER);c.setSelected(true);jtf1.setHorizontalAlignment(SwingConstants.CENTER);jtf1.setColumns(30);l.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){jtf1.setHorizontalAlignment(SwingConstants.LEFT);

}

});c.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){jtf1.setHorizontalAlignment(SwingConstants.CENTER);

}

});r.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){jtf1.setHorizontalAlignment(SwingConstants.RIGHT);

}

});jtf2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

jtf1.setColumns(Integer.parseInt(jtf2.getText()));validate();

}

});

}}____________________________________________________________17.12 Write a program that demonstrates the wrapping styles of the text area. The program uses a check box to indicate whether the text area is wrapped. In the case where the text area is wrapped, you need to specify whether it is wrapped by characters or by words, as shown in Figure.

Page 48: Exercise for Java Thirdyear

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.TitledBorder;

import java.awt.event.*;public class Exercise17_12 extends JFrame{

public static void main(String[] args){Exercise17_12 f=new Exercise17_12();f.setTitle("Exercise17_12");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JTextArea jta=new JTextArea();private JCheckBox jck=new JCheckBox("Wrap");private JRadioButton jrb1=new JRadioButton("Wrap Words");private JRadioButton jrb2=new JRadioButton("Wrap Characters");

Exercise17_12(){JScrollPane sp=new JScrollPane(jta);ButtonGroup bg=new ButtonGroup();bg.add(jrb1);bg.add(jrb2);JPanel p=new JPanel(new FlowLayout(FlowLayout.CENTER));p.add(jck);p.add(jrb1);p.add(jrb2);p.setBorder(new TitledBorder("Wrap Options"));setLayout(new BorderLayout(5,5));add(sp,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);jck.setSelected(true);jrb1.setSelected(true);jta.setLineWrap(true);jta.setWrapStyleWord(true);

jck.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){

if (jck.isSelected()) { jrb1.setEnabled(true); jrb2.setEnabled(true); } else { jrb1.setEnabled(false); jrb2.setEnabled(false);

Page 49: Exercise for Java Thirdyear

}

}});jrb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){jta.setWrapStyleWord(true);

}});jrb2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){jta.setWrapStyleWord(false);

}

});

}

}_______________________________________________________________17.14 Write a program that demonstrates selecting items in a list. The program uses a combo box to specify a selection mode, as shown in Figure 17.45. When you select items, they are displayed in a label below the list.

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;

import java.awt.event.*;public class Exercise17_14 extends JFrame{

public static void main(String[] args){Exercise17_14 f=new Exercise17_14();f.setTitle("Exercise17_14");//f.pack();f.setSize(500,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JComboBox jcb=new JComboBox(new Object[]

{"SINGLE_SELECTION","SINGLE_INTERVAL","MULTIPLE_INTERVAL_SELECTION"});

Page 50: Exercise for Java Thirdyear

private String[] name={"United State","United Kingdom","China","Germany","France"};private JList jl=new JList(name);private JLabel l=new JLabel();public Exercise17_14() {

LineBorder lb=new LineBorder(Color.black,1);JPanel p=new JPanel(new BorderLayout(5,5));p.add(new JLabel("Choose Selection Mode"),BorderLayout.WEST);p.add(jcb,BorderLayout.CENTER);p.setBorder(lb);l.setBorder(lb);JScrollPane sp=new JScrollPane(jl);sp.setBorder(lb);setLayout(new BorderLayout(3,3));add(p,BorderLayout.NORTH);add(sp,BorderLayout.CENTER);add(l,BorderLayout.SOUTH);jcb.setSelectedIndex(2);jcb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if(jcb.getSelectedIndex()==0)jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

else if(jcb.getSelectedIndex()==1)

jl.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);else

jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

}});jl.addListSelectionListener(new ListSelectionListener(){public void valueChanged(ListSelectionEvent e){

int[] indicies=jl.getSelectedIndices();String s="";for(int i=0;i<indicies.length;i++){

s=s+" "+name[indicies[i]];

}l.setText(s);

}});

}

}_____________________________________________________________________________17-15.Write a program that uses scroll bars to select the foreground color for a label, as shown in Figure 17.46.Three horizontal scroll bars are used for selecting the red, green, and blue components of the color. Use a title border on the panel that holds the scroll bars.

Page 51: Exercise for Java Thirdyear

package ch17;import java.awt.*;import javax.swing.*;import javax.swing.border.LineBorder;import javax.swing.border.TitledBorder;

import java.awt.event.*;public class Exercise17_15 extends JFrame{

public static void main(String[] args){Exercise17_15 f=new Exercise17_15();f.setTitle("Exercise17_15");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JLabel l=new JLabel("Show Colors");private JScrollBar jsb1=new JScrollBar(JScrollBar.HORIZONTAL);private JScrollBar jsb2=new JScrollBar(JScrollBar.HORIZONTAL);private JScrollBar jsb3=new JScrollBar(JScrollBar.HORIZONTAL);private Color c;public Exercise17_15() {

jsb1.setMaximum(255);jsb2.setMaximum(255);jsb3.setMaximum(255);l.setHorizontalAlignment(SwingConstants.CENTER);JPanel p1=new JPanel(new GridLayout(3,1,3,3));p1.add(new JLabel("Red"));p1.add(new JLabel("Green"));p1.add(new JLabel("Blue"));LineBorder lb=new LineBorder(Color.black,1);p1.setBorder(lb);JPanel p2=new JPanel(new GridLayout(3,1,2,2));p2.add(jsb1);p2.add(jsb2);p2.add(jsb3);p2.setBorder(lb);JPanel p=new JPanel(new BorderLayout(3,3));p.add(p1,BorderLayout.WEST);p.add(p2,BorderLayout.CENTER);p.setBorder(new TitledBorder("Choose colors"));add(l,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);jsb1.setValue(122);

Page 52: Exercise for Java Thirdyear

jsb2.setValue(80);jsb3.setValue(200); c=new Color(jsb1.getValue(),jsb2.getValue(),jsb3.getValue());l.setForeground(c);jsb1.addAdjustmentListener(new AdjustmentListener(){

public void adjustmentValueChanged(AdjustmentEvent e){

l.setForeground(new Color(jsb1.getValue(),jsb2.getValue(),jsb3.getValue()));}

});jsb2.addAdjustmentListener(new AdjustmentListener(){

public void adjustmentValueChanged(AdjustmentEvent e){l.setForeground(new Color(jsb1.getValue(),jsb2.getValue(),jsb3.getValue()));

}});jsb3.addAdjustmentListener(new AdjustmentListener(){

public void adjustmentValueChanged(AdjustmentEvent e){l.setForeground(new Color(jsb1.getValue(),jsb2.getValue(),jsb3.getValue()));

}

});

}

}___________________________________________________________________17.16 Revise the preceding exercise using sliders

package ch17;import java.awt.*;

import javax.swing.*;

import java.awt.event.*;import javax.swing.border.*;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;public class Exercise17_16 extends JFrame{

public static void main(String[] args){Exercise17_16 f=new Exercise17_16();f.setTitle("Exercise17_16");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

Page 53: Exercise for Java Thirdyear

}private JLabel l=new JLabel("Show Colors");private JSlider js1=new JSlider(JSlider.HORIZONTAL);private JSlider js2=new JSlider(JSlider.HORIZONTAL);private JSlider js3=new JSlider(JSlider.HORIZONTAL);private Color c;public Exercise17_16() {

js1.setMaximum(255);js2.setMaximum(255);js3.setMaximum(255);js1.setPaintTicks(true);

js2.setPaintTicks(true);

js3.setPaintTicks(true);l.setVerticalAlignment(SwingConstants.CENTER);l.setHorizontalAlignment(SwingConstants.CENTER);LineBorder lb=new LineBorder(Color.black,1);JPanel p1=new JPanel(new GridLayout(3,1,3,3));p1.add(new JLabel("Red"));p1.add(new JLabel("Green"));p1.add(new JLabel("Blue"));p1.setBorder(lb);JPanel p2=new JPanel(new GridLayout(3,1,3,3));p2.add(js1);p2.add(js2);p2.add(js3);p2.setBorder(lb);JPanel p=new JPanel(new BorderLayout(3,3));p.add(p1,BorderLayout.WEST);p.add(p2,BorderLayout.CENTER);p.setBorder(new TitledBorder("Choose Colors"));setLayout(new BorderLayout(5,5));add(l,BorderLayout.CENTER);add(p,BorderLayout.SOUTH);js1.setValue(150);js2.setValue(80);js3.setValue(200);l.setForeground(new Color(js1.getValue(),js2.getValue(),js3.getValue()));

SListener sl=new SListener();js1.addChangeListener(sl);js2.addChangeListener(sl);js3.addChangeListener(sl);

}class SListener implements ChangeListener{

private int r,g,b;public void stateChanged(ChangeEvent e) {

if(e.getSource()==js1)r=js1.getValue();

if(e.getSource()==js2); g=js2.getValue(); if(e.getSource()==js3)

Page 54: Exercise for Java Thirdyear

b=js3.getValue(); l.setForeground(new Color(r,g,b));

}}

}_____________________________________________________________________________

Chapter17

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

import java.awt.event.*;

import javax.swing.border.LineBorder;import javax.swing.event.*;public class Test extends JFrame{

public static void main(String[] args){Test f=new Test();f.setTitle("User Information");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JTextField jtf=new JTextField();private JTextField des=new JTextField("Other Information");private JComboBox jcb=new JComboBox();private JRadioButton jrb1=new JRadioButton("Male");private JRadioButton jrb2=new JRadioButton("Female");private JTextArea jta=new JTextArea();private JButton b=new JButton("Show Information");Test(){

des.setHorizontalAlignment(SwingConstants.CENTER);jta.setLineWrap(true);jta.setWrapStyleWord(true);for(int i=10;i<50;i++){

jcb.addItem(i);}ButtonGroup bg=new ButtonGroup();bg.add(jrb1);bg.add(jrb2);JPanel pp=new JPanel(new GridLayout(3,2,5,5));pp.add(new JLabel("User Name"));

Page 55: Exercise for Java Thirdyear

pp.add(jtf);pp.add(new JLabel("Age"));pp.add(jcb);pp.add(jrb1);pp.add(jrb2);

JPanel p=new JPanel(new BorderLayout(10,10));p.add(pp,BorderLayout.CENTER);p.add(des,BorderLayout.SOUTH);

p.setBorder(new LineBorder(Color.black,2));JPanel p1=new JPanel(new BorderLayout(10,10));p1.add(p,BorderLayout.CENTER);p1.add(b,BorderLayout.SOUTH);JScrollPane sp=new JScrollPane(jta);setLayout(new GridLayout(1,2,4,4));add(p1);add(sp);b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){String name=jtf.getText();jta.append("User Name is"+ name+"\n");int age=jcb.getSelectedIndex();jta.append("User age is"+ (age+10)+"\n");String gender="";if(jrb1.isSelected())

gender=jrb1.getText();else

gender=jrb2.getText();jta.append("User gender is"+gender+"\n");jta.append(des.getText());

}});

}

}_____________________________________________________________________

import java.awt.*;

Page 56: Exercise for Java Thirdyear

import javax.swing.*;

import java.awt.event.*;

import javax.swing.border.LineBorder;import javax.swing.event.*;public class Test2 extends JFrame{

public static void main(String[] args){Test2 f=new Test2();f.setTitle("List Example");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private String[] arr={"Canada","China","Denmark","France","Germany","India","Norway","United

Kingdom"};private JList jl=new JList(arr);private JTextArea jta=new JTextArea();private JButton b=new JButton("Show");Test2(){

jta.setLineWrap(true);jta.setWrapStyleWord(true);JScrollPane sp=new JScrollPane(jl);JScrollPane sp2=new JScrollPane(jta);JPanel p=new JPanel();p.setLayout(new BorderLayout(3,3));p.add(sp,BorderLayout.CENTER);p.add(b,BorderLayout.SOUTH);setLayout(new GridLayout(1,2));add(p);add(sp2);b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){int[] in=jl.getSelectedIndices();String s="";for(int i=0;i<in.length;i++){

s+=" "+ arr[in[i]];

}jta.setText(s);

}});

}}__________________________________________________________________

Page 57: Exercise for Java Thirdyear

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

import java.awt.event.*;

import javax.swing.border.LineBorder;import javax.swing.event.*;public class Test3 extends JFrame{

public static void main(String[] args){Test3 f=new Test3();f.setTitle("User InformationII");//f.pack();f.setSize(300,200);f.setLocationRelativeTo(null);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}private JTextField jtf1=new JTextField();private JTextField jtf2=new JTextField();private JTextField jtf3=new JTextField();private JTextArea jta=new JTextArea();private String[] gen={"Female","Male"};private JComboBox jcb=new JComboBox(gen);private JButton jbt=new JButton("Show");public Test3() {

JPanel p1=new JPanel(new FlowLayout(FlowLayout.RIGHT));p1.add(jbt);

JPanel p=new JPanel(new GridLayout(4,2,5,5));p.add(new JLabel("UserName"));p.add(jtf1);p.add(new JLabel("Gender"));p.add(jcb);p.add(new JLabel("Age"));p.add(jtf2);p.add(new JLabel("Class"));p.add(jtf3);

Page 58: Exercise for Java Thirdyear

JPanel p3=new JPanel(new BorderLayout());p3.add(p,BorderLayout.CENTER);p3.add(p1,BorderLayout.SOUTH);JScrollPane sp=new JScrollPane(jta);jta.setLineWrap(true);jta.setWrapStyleWord(true);setLayout(new GridLayout(2,1));add(p3);add(sp);jbt.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){String s="";s+="User Name is"+jtf1.getText();if(jcb.getSelectedIndex()==0)

s+="Gender is Female";else

s+="Gender is Male";s+="Age is"+jtf2.getText();s+="class is"+jtf3.getText();jta.setText(s);

}});}

}