Jumat, 15 Agustus 2025

JAVA - Point2D Animasi

 




/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package test2;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.geom.AffineTransform;

import java.awt.geom.Arc2D;

import java.awt.geom.Ellipse2D;

import java.awt.geom.GeneralPath;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;


public class Test2 {


    public static void main(String[] args) {

        new Test2();

    }


    public Test2() {

        EventQueue.invokeLater(new Runnable() {

            @Override

            public void run() {

                JFrame frame = new JFrame();

                frame.add(new TestPane());

                frame.pack();

                frame.setLocationRelativeTo(null);

                frame.setVisible(true);

            }

        });

    }


    public class TestPane extends JPanel {


        private GeneralPath gp = new GeneralPath();

        private double spinValue = 0;


        public TestPane() {

            gp.append(new Ellipse2D.Double(0, 0, 200, 200), true);


            for (double angle = 0; angle < 360; angle += 30) {

                Arc2D arc = new Arc2D.Double(0, 0, 200, 200,

                        angle,

                        30,

                        Arc2D.PIE);

                gp.append(arc, false);

            }


            Timer timer = new Timer(5, new ActionListener() {

                @Override

                public void actionPerformed(ActionEvent e) {

                    spinValue += 0.01;

                    repaint();

                }

            });

            timer.start();

        }


        @Override

        public Dimension getPreferredSize() {

            return new Dimension(300, 300);

        }


        @Override

        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            g2d.setRenderingHints(hints);


            Rectangle2D bounds = gp.getBounds2D();

            double x = (getWidth() - bounds.getWidth()) / 2d;

            double y = (getHeight() - bounds.getHeight()) / 2d;


            AffineTransform at = AffineTransform.getTranslateInstance(x, y);

            at.rotate(spinValue, bounds.getCenterX(), bounds.getCenterY());


            g2d.transform(at);

            g2d.draw(gp);

            g2d.dispose();

        }

    }


}


Kamis, 14 Agustus 2025

JAVA - Point2D


 


/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package testpane;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import java.awt.geom.Ellipse2D;

import java.awt.geom.GeneralPath;

import java.awt.geom.Point2D;

import javax.swing.JFrame;

import javax.swing.JPanel;


public class Test {


    public static void main(String[] args) {

        new Test();

    }


    public Test() {

        EventQueue.invokeLater(new Runnable() {

            @Override

            public void run() {

                JFrame frame = new JFrame();

                frame.add(new TestPane());

                frame.pack();

                frame.setLocationRelativeTo(null);

                frame.setVisible(true);

            }

        });

    }


    public class TestPane extends JPanel {


        private GeneralPath gp = new GeneralPath();


        public TestPane() {


            //GeneralPath gp = new GeneralPath();

            gp.append(new Ellipse2D.Double(0, 0, 200, 200), true);


            for (double angle = 0; angle < 180; angle += 30) {

                Point2D startPoint = pointOnCircle(angle, 100);

                Point2D endPoint = pointOnCircle(angle + 180, 100);


                gp.moveTo(startPoint.getX(), startPoint.getY());

                gp.lineTo(endPoint.getX(), endPoint.getY());

            }


        }


        protected Point2D pointOnCircle(double degrees, double radius) {

            double origin = radius;

            double rads = Math.toRadians(degrees);

            double x = origin + (Math.cos(rads) * radius);

            double y = origin + (Math.sin(rads) * radius);


            return new Point2D.Double(x, y);

        }


        @Override

        public Dimension getPreferredSize() {

            return new Dimension(300, 300);

        }


        @Override

        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            g2d.setRenderingHints(hints);

            g2d.translate(50, 50);

            g2d.draw(gp);

            g2d.dispose();

        }

    }


}


JAVA - Polyline3


 


/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package excercise13_12b;

import java.awt.BorderLayout;

import java.awt.Graphics;

import java.awt.Polygon;

import java.awt.Color;

import javax.swing.JFrame;

import javax.swing.JPanel;


public class Exercise13_12b extends JFrame {


public Exercise13_12b() {

setLayout(new BorderLayout());

add(new DrawSine(), BorderLayout.CENTER);

}


public static void main(String[] args) {

Exercise13_12b frame = new Exercise13_12b();

frame.setSize(400, 300);

frame.setTitle("Exercise13_12");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setVisible(true);


}


class DrawSine extends JPanel {


double f(double x) {

    return Math.sin(x);

}


double gCos(double y) {

    return Math.cos(y);

}


protected void paintComponent(Graphics g) 

{

    super.paintComponent(g);


    g.drawLine(10, 100, 380, 100);

    g.drawLine(200, 30, 200, 190);


    g.drawLine(380, 100, 370, 90);

    g.drawLine(380, 100, 370, 110);

    g.drawLine(200, 30, 190, 40);

    g.drawLine(200, 30, 210, 40);


    g.drawString("X", 360, 80);

    g.drawString("Y", 220, 40);


    Polygon p = new Polygon();

    Polygon p2 = new Polygon();


   for (int x = -170; x <= 170; x++) {

        p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2

                * Math.PI)));


    }


    for (int x = -170; x <= 170; x++) {

        p2.addPoint(x + 200, 100 - (int) (50 * gCos((x / 100.0) * 2

                * Math.PI)));


    }


    g.setColor(Color.red);

    g.drawPolyline(p.xpoints, p.ypoints, p.npoints);

    g.drawString("-2\u03c0", 95, 115);

    g.drawString("-\u03c0", 147, 115);

    g.drawString("\u03c0", 253, 115);  

    g.drawString("2\u03c0", 305, 115);

    g.drawString("0", 200, 115);


    g.setColor(Color.blue);

    g.drawPolyline(p2.xpoints, p2.ypoints, p2.npoints);


  }

 }

}

JAVA - Polyline2

 




/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package excercise13_12a;

import java.awt.BorderLayout;

import java.awt.Graphics;

import java.awt.Polygon;

import java.awt.Color;


import javax.swing.JFrame;

import javax.swing.JPanel;


public class Exercise13_12a extends JFrame {


public Exercise13_12a() {

    setLayout(new BorderLayout());

    add(new DrawSine(), BorderLayout.CENTER);

}


public static void main(String[] args) {

    Exercise13_12a frame = new Exercise13_12a();

    frame.setSize(400, 300);

    frame.setTitle("Exercise13_12");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLocationRelativeTo(null);

    frame.setVisible(true);


}


class DrawSine extends JPanel {


    double f(double x) {

        return Math.sin(x);

    }


    double gCos(double y) {

        return Math.cos(y);

    }


    protected void paintComponent(Graphics g) 

    {

        super.paintComponent(g);


        g.drawLine(10, 100, 380, 100);

        g.drawLine(200, 30, 200, 190);


        g.drawLine(380, 100, 370, 90);

        g.drawLine(380, 100, 370, 110);

        g.drawLine(200, 30, 190, 40);

        g.drawLine(200, 30, 210, 40);


        g.drawString("X", 360, 80);

        g.drawString("Y", 220, 40);


        Polygon p = new Polygon();

        Polygon p2 = new Polygon();


       for (int x = -170; x <= 170; x++) {

            p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2

                    * Math.PI)));


        }


        for (int x = -170; x <= 170; x++) {

            p2.addPoint(x + 200, 100 - (int) (50 * gCos((x / 100.0) * 2

                    * Math.PI)));


        }


        g.setColor(Color.red);

        g.drawPolyline(p.xpoints, p.ypoints, p.npoints);

        g.drawString("-2\u03c0", 95, 115);

        g.drawString("2\u03c0", 305, 115);

        g.drawString("0", 200, 115);


        g.setColor(Color.blue);

        g.drawPolyline(p2.xpoints, p2.ypoints, p2.npoints);


    }

 }

}


JAVA - POLYLINE

 



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package excercise13_12;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Polygon;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Exercise13_12 extends JFrame {

public Exercise13_12() {
    setLayout(new BorderLayout());
    add(new DrawSine(), BorderLayout.CENTER);
}

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

}

class DrawSine extends JPanel {

    double f(double x) {
        return Math.sin(x);
    }

    double g(double y) {
        return Math.cos(y);
    }

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

        g.drawLine(10, 100, 380, 100);
        g.drawLine(200, 30, 200, 190);

        g.drawLine(380, 100, 370, 90);
        g.drawLine(380, 100, 370, 110);
        g.drawLine(200, 30, 190, 40);
        g.drawLine(200, 30, 210, 40);

        g.drawString("X", 360, 80);
        g.drawString("Y", 220, 40);

        Polygon p = new Polygon();

        for (int x = -170; x <= 170; x++) {
            p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2
                    * Math.PI)));

        }

        g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
        g.drawString("-2\u03c0", 95, 115);
        g.drawString("2\u03c0", 305, 115);
        g.drawString("0", 200, 115);
    }
 }
}




Rabu, 13 Agustus 2025

JAVA - Membuat Tombol Sendiri



File : TMyButton.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tmybutton;
import javax.swing.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.event.*;
// 11. The component class MyButton is a subclass of JComponent.
class MyButton extends JComponent {    
    MyButtonModel model = null;
    String text = "";
    Font font = null;
    FontMetrics fontMetrics = null;
    int border = 10;
    boolean buttonPressed = false;
    
    // 12. MyButton constructor without any arguments.
    public MyButton() {
        this(null);
    }
    
    // 13. MyButton constructor that takes the text label argument.
    public MyButton(String text) {   
        // Assign the data model to the component.
        setModel(new DefaultMyButtonModel());
        // Initialize the text label.
        this.text = text;
        // Obtain the default font.
        font = getFont();
        // If there is no default font, assign a new font.
        if (font == null) {
            font = new Font("SanSerif", Font.BOLD, 14);
        }
        // Retrieve the font metrics of the font.
        fontMetrics = getFontMetrics(font);
        // Register a mouse listener.
        addMouseListener(new ButtonMouseListener());
        
        // Update the view of the button.
        updateUI();
    }
    // 14. Method definition of update.
    public void updateUI() {
        // Assign proper look-and-feel for the view depending on the
        // specified look-and-feel.
        if (MyUIManager.getLookAndFeel().equals("Default")) {
             super.setUI(new MyButtonUI());
        }
        else if (MyUIManager.getLookAndFeel().equals("Oval")) {
            super.setUI(new MyButtonOvalUI());
        }
    }

    // 15. This class is the UI delegate. It has been defined as an
    // inner class to simplify the program. This class provides the default 
    // view of the button.
    class MyButtonUI extends ComponentUI {
    
    // 16. Constructor.
    public MyButtonUI() {
        repaint(); // Call repaint for further actions.
    }
    
    // 17. Retrieve the minimum size of the component.
    public Dimension getMinimumSize() {
        int w = fontMetrics.stringWidth(text);
        int h = fontMetrics.getHeight();
        return new Dimension(w+2*border, h+2*border);
    }

    // 18. Retrieve the preferred size of the component.
    public Dimension getPreferredSize() {
        return getMinimumSize();
    }

    // 19. Retrieve the maximum size of the component.
    public Dimension getMaximumSize() {
        return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
    }

    // 20. The update method definition.
    public void update(Graphics g, JComponent c) {
        if (c.isOpaque()) {
           g.setColor(c.getBackground());
           g.fillRect(0,0,getWidth(), getHeight());
        }
        paint(g, c);
    }
    
    // 21. The paint method definition.
    public void paint(Graphics g, JComponent c) {
        g.setFont(font);

        if (buttonPressed == false) {
            buttonView(g, Color.lightGray, Color.black);
        }
        else {
            buttonView(g, Color.gray, Color.white);
        }
    }
    
    // 22. The buttonView method definition.
    public void buttonView(Graphics g, Color background, Color foreground) {
        g.setColor(background);
        g.fill3DRect(0,0, getSize().width, getSize().height, true);
        g.setColor(foreground);
        int x = (getSize().width-fontMetrics.stringWidth(text))/2;
        int y = (getSize().height+fontMetrics.getHeight()
                                 -fontMetrics.getDescent())/2;
        g.drawString(text, x, y);
    }
    }


    // 23. Implementation of oval shaped look-and-feel for MyButton.
    // This view of the button is used as an alternative to its default view.
    class MyButtonOvalUI extends ComponentUI {

    // 24. Constructor.
    public MyButtonOvalUI() {
        repaint();
    }

    // 25. Retrieve the minimum size of the component.
    public Dimension getMinimumSize() {
        int w = fontMetrics.stringWidth(text);
        int h = fontMetrics.getHeight();
        return new Dimension(w+2*border, h+2*border);
    }

    // 26. Retrieve the preferred size of the component.
    public Dimension getPreferredSize() {
        return getMinimumSize();
    }

    // 27. Retrieve the maximum size of the component.
    public Dimension getMaximumSize() {
return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
    }
    // 28. The update method definition.
    public void update(Graphics g, JComponent c) {
        if (c.isOpaque()) {
           g.setColor(c.getBackground());
           g.fillRect(0,0,getWidth(), getHeight());
        }
        paint(g, c);
    }

    // 29. The paint method definition.
    public void paint(Graphics g, JComponent c) {
        g.setFont(font);

        if (buttonPressed == false) {
            buttonView(g, Color.gray, Color.white);
        }
        else {
            buttonView(g, Color.lightGray, Color.black);
        }
    }

    // 30. The button view definition.
    public void buttonView(Graphics g, Color background, Color foreground) {
        g.setColor(background);
        g.fillOval(0,0, getSize().width, getSize().height);
        g.setColor(foreground);
        int x = (getSize().width-fontMetrics.stringWidth(text))/2;
        int y = (getSize().height+fontMetrics.getHeight()
                                 -fontMetrics.getDescent())/2;
        g.drawString(text, x, y);
    }
    }

    // 31. When the user presses or releases the mouse over a button,
    // the functionality from the implementation methods from this
    // mouse listener class are executed.
    class ButtonMouseListener extends MouseAdapter {
        public void mousePressed(MouseEvent evt) {
            requestFocus();
            buttonPressed = true;
            ((MyButton) evt.getSource()).repaint();
        }

        public void mouseReleased(MouseEvent evt) {
            buttonPressed = false;
            ((MyButton) evt.getSource()).repaint();
            ActionEvent actionEvent = new ActionEvent(
                                          MyButton.this,
                                          ActionEvent.ACTION_PERFORMED,
                                          MyButton.this.getActionCommand());
            processEvent(actionEvent);
        }
    }

    //Supports the action listener.
    ActionListener actionListener;

    // 32. Method to register an action listener with the button.
    public void addActionListener(ActionListener l) {
        actionListener = AWTEventMulticaster.add(actionListener, l);
    }
    // 33. To figure out the action events.
    protected void processEvent(AWTEvent evt) {
        if (evt instanceof ActionEvent) {
            processActionEvent((ActionEvent) evt);
        }
        else {
            super.processEvent(evt);
        }
    }
    // 34. To process the action events.
    protected void processActionEvent(ActionEvent evt) {
        if (actionListener != null) {
            // Execute the action performed from the listener class.
            actionListener.actionPerformed(evt);
        }
    }
    // 35. Method to assign the button model.
    public void setModel(MyButtonModel model) {
        this.model = model;
    }
    // 36. Retrieve the action model.
    public MyButtonModel getModel() {
        return model;
    }
    // 37. Assign the text label to the button.
    public void setText(String text) {
        this.text = text;
        invalidate();
        repaint();
    }
    // 38. Retrieve the text label of the button.
    public String getText() {
        return text;
}
    // 39. To assign the action command.
    public void setActionCommand(String actionCommand) {
getModel().setActionCommand(actionCommand);
    }
    // 40. To retrieve the action command.
    public String getActionCommand() {
        String ac = getModel().getActionCommand();
        if (ac == null) {
            ac = getText();
        }
        return ac;
    }
}

// 41. Define a simple button model interface.
interface MyButtonModel {
    public void setActionCommand(String actionCommand);
    public String getActionCommand();
}

// 42. Define the default button model class that implements the 
// MyButtonModel interface.
class DefaultMyButtonModel implements MyButtonModel {
    protected String actionCommand = null;
    // 43. Assign an action command.
    public void setActionCommand(String actionCommand) {
        this.actionCommand = actionCommand;
    }
    // 44. Retrieve the action command that has been assigned.
    public String getActionCommand() {
        return actionCommand;
    }
}
======================================================

File : MyUIManager.java

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package tmybutton;

class MyUIManager {

    // Store the look-and-feel string.

    static String lfType = "Default";

    // 46. Assign a new look-and-feel.

    static public void setLookAndFeel(String type) {

        lfType = type;

    }

    // 47. Retrieve the current look-and-feel.

    static public String getLookAndFeel() {

        return lfType; 

    }

}


 =========================================

File : MyButton.java

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package tmybutton;

import javax.swing.*;

import javax.swing.plaf.*;

import java.awt.*;

import java.awt.event.*;

// 11. The component class MyButton is a subclass of JComponent.

class MyButton extends JComponent {    

    MyButtonModel model = null;

    String text = "";

    Font font = null;

    FontMetrics fontMetrics = null;

    int border = 10;

    boolean buttonPressed = false;

    

    // 12. MyButton constructor without any arguments.

    public MyButton() {

        this(null);

    }

    

    // 13. MyButton constructor that takes the text label argument.

    public MyButton(String text) {   

        // Assign the data model to the component.

        setModel(new DefaultMyButtonModel());

        // Initialize the text label.

        this.text = text;

        // Obtain the default font.

        font = getFont();

        // If there is no default font, assign a new font.

        if (font == null) {

            font = new Font("SanSerif", Font.BOLD, 14);

        }

        // Retrieve the font metrics of the font.

        fontMetrics = getFontMetrics(font);

        // Register a mouse listener.

        addMouseListener(new ButtonMouseListener());

        

        // Update the view of the button.

        updateUI();

    }

    // 14. Method definition of update.

    public void updateUI() {

        // Assign proper look-and-feel for the view depending on the

        // specified look-and-feel.

        if (MyUIManager.getLookAndFeel().equals("Default")) {

             super.setUI(new MyButtonUI());

        }

        else if (MyUIManager.getLookAndFeel().equals("Oval")) {

            super.setUI(new MyButtonOvalUI());

        }

    }


    // 15. This class is the UI delegate. It has been defined as an

    // inner class to simplify the program. This class provides the default 

    // view of the button.

    class MyButtonUI extends ComponentUI {

    

    // 16. Constructor.

    public MyButtonUI() {

        repaint(); // Call repaint for further actions.

    }

    

    // 17. Retrieve the minimum size of the component.

    public Dimension getMinimumSize() {

        int w = fontMetrics.stringWidth(text);

        int h = fontMetrics.getHeight();

        return new Dimension(w+2*border, h+2*border);

    }


    // 18. Retrieve the preferred size of the component.

    public Dimension getPreferredSize() {

        return getMinimumSize();

    }


    // 19. Retrieve the maximum size of the component.

    public Dimension getMaximumSize() {

        return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);

    }


    // 20. The update method definition.

    public void update(Graphics g, JComponent c) {

        if (c.isOpaque()) {

           g.setColor(c.getBackground());

           g.fillRect(0,0,getWidth(), getHeight());

        }

        paint(g, c);

    }

    

    // 21. The paint method definition.

    public void paint(Graphics g, JComponent c) {

        g.setFont(font);


        if (buttonPressed == false) {

            buttonView(g, Color.lightGray, Color.black);

        }

        else {

            buttonView(g, Color.gray, Color.white);

        }

    }

    

    // 22. The buttonView method definition.

    public void buttonView(Graphics g, Color background, Color foreground) {

        g.setColor(background);

        g.fill3DRect(0,0, getSize().width, getSize().height, true);

        g.setColor(foreground);

        int x = (getSize().width-fontMetrics.stringWidth(text))/2;

        int y = (getSize().height+fontMetrics.getHeight()

                                 -fontMetrics.getDescent())/2;

        g.drawString(text, x, y);

    }

    }



    // 23. Implementation of oval shaped look-and-feel for MyButton.

    // This view of the button is used as an alternative to its default view.

    class MyButtonOvalUI extends ComponentUI {


    // 24. Constructor.

    public MyButtonOvalUI() {

        repaint();

    }


    // 25. Retrieve the minimum size of the component.

    public Dimension getMinimumSize() {

        int w = fontMetrics.stringWidth(text);

        int h = fontMetrics.getHeight();

        return new Dimension(w+2*border, h+2*border);

    }


    // 26. Retrieve the preferred size of the component.

    public Dimension getPreferredSize() {

        return getMinimumSize();

    }


    // 27. Retrieve the maximum size of the component.

    public Dimension getMaximumSize() {

return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);

    }

    // 28. The update method definition.

    public void update(Graphics g, JComponent c) {

        if (c.isOpaque()) {

           g.setColor(c.getBackground());

           g.fillRect(0,0,getWidth(), getHeight());

        }

        paint(g, c);

    }


    // 29. The paint method definition.

    public void paint(Graphics g, JComponent c) {

        g.setFont(font);


        if (buttonPressed == false) {

            buttonView(g, Color.gray, Color.white);

        }

        else {

            buttonView(g, Color.lightGray, Color.black);

        }

    }


    // 30. The button view definition.

    public void buttonView(Graphics g, Color background, Color foreground) {

        g.setColor(background);

        g.fillOval(0,0, getSize().width, getSize().height);

        g.setColor(foreground);

        int x = (getSize().width-fontMetrics.stringWidth(text))/2;

        int y = (getSize().height+fontMetrics.getHeight()

                                 -fontMetrics.getDescent())/2;

        g.drawString(text, x, y);

    }

    }


    // 31. When the user presses or releases the mouse over a button,

    // the functionality from the implementation methods from this

    // mouse listener class are executed.

    class ButtonMouseListener extends MouseAdapter {

        public void mousePressed(MouseEvent evt) {

            requestFocus();

            buttonPressed = true;

            ((MyButton) evt.getSource()).repaint();

        }


        public void mouseReleased(MouseEvent evt) {

            buttonPressed = false;

            ((MyButton) evt.getSource()).repaint();

            ActionEvent actionEvent = new ActionEvent(

                                          MyButton.this,

                                          ActionEvent.ACTION_PERFORMED,

                                          MyButton.this.getActionCommand());

            processEvent(actionEvent);

        }

    }


    //Supports the action listener.

    ActionListener actionListener;


    // 32. Method to register an action listener with the button.

    public void addActionListener(ActionListener l) {

        actionListener = AWTEventMulticaster.add(actionListener, l);

    }

    // 33. To figure out the action events.

    protected void processEvent(AWTEvent evt) {

        if (evt instanceof ActionEvent) {

            processActionEvent((ActionEvent) evt);

        }

        else {

            super.processEvent(evt);

        }

    }

    // 34. To process the action events.

    protected void processActionEvent(ActionEvent evt) {

        if (actionListener != null) {

            // Execute the action performed from the listener class.

            actionListener.actionPerformed(evt);

        }

    }

    // 35. Method to assign the button model.

    public void setModel(MyButtonModel model) {

        this.model = model;

    }

    // 36. Retrieve the action model.

    public MyButtonModel getModel() {

        return model;

    }

    // 37. Assign the text label to the button.

    public void setText(String text) {

        this.text = text;

        invalidate();

        repaint();

    }

    // 38. Retrieve the text label of the button.

    public String getText() {

        return text;

}

    // 39. To assign the action command.

    public void setActionCommand(String actionCommand) {

getModel().setActionCommand(actionCommand);

    }

    // 40. To retrieve the action command.

    public String getActionCommand() {

        String ac = getModel().getActionCommand();

        if (ac == null) {

            ac = getText();

        }

        return ac;

    }

}


// 41. Define a simple button model interface.

interface MyButtonModel {

    public void setActionCommand(String actionCommand);

    public String getActionCommand();

}


// 42. Define the default button model class that implements the 

// MyButtonModel interface.

class DefaultMyButtonModel implements MyButtonModel {

    protected String actionCommand = null;

    // 43. Assign an action command.

    public void setActionCommand(String actionCommand) {

        this.actionCommand = actionCommand;

    }

    // 44. Retrieve the action command that has been assigned.

    public String getActionCommand() {

        return actionCommand;

    }

}


JAVA - BOX 2

 




/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package tbox2;

import javax.swing.*;

import java.awt.*;


public class TBox2 extends JApplet {

    Container container = null;

    

    public void init() {

        // 1. Get the handle on the applets' content pane

        // and set the background color to white.

        container = getContentPane();

        container.setBackground(Color.white); 

        

        // 2. Create a horizontal box and add it to the applet.

        Box baseBox = Box.createHorizontalBox();

        container.add(baseBox);


        // 3. Create a vertical box and add it to the base box.

        Box vBox = Box.createVerticalBox();

        baseBox.add(vBox);


        // 4. Create button B1 and add it to vBox.

        JButton b1 = new JButton("B1");

        b1.setAlignmentX(Component.CENTER_ALIGNMENT);

        b1.setMaximumSize(new Dimension(150,150));

        vBox.add(b1);


        // 5. Create a horizontal box and add it to vBox.

        Box hBox = Box.createHorizontalBox();

        vBox.add(hBox);


        // 6. Create button B2 and add it to hBox.

        JButton b2 = new JButton("B2");

        b2.setAlignmentY(Component.CENTER_ALIGNMENT);

        b2.setMaximumSize(new Dimension(75,100));       

        hBox.add(b2);


        // 7. Create another button B3 and add it to hBox.

        JButton b3 = new JButton("B3");

        b3.setAlignmentY(Component.CENTER_ALIGNMENT);

        b3.setMaximumSize(new Dimension(75,100));    

        hBox.add(b3);


        // 8. Create the vertical box (vBox1) and

        // add it to the base box.

        Box vBox1 = Box.createVerticalBox();

        baseBox.add(vBox1);


        // 9. Create the button B4 and add it to vBox1.

        JButton b4 = new JButton("B4");

        b4.setAlignmentX(Component.CENTER_ALIGNMENT);

        b4.setMaximumSize(new Dimension(100,250));     

        vBox1.add(b4); 

    }

}