Kamis, 14 Agustus 2025

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); 

    }

}


JAVA - Box

 





/*

 * 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 tbox1;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.*;


public class TBox1 extends JApplet {

    Container container = null;

    

    public void init() {

        // 1. Get the handle on the applet's content pane.

        container = getContentPane();


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

        Box baseBox = Box.createVerticalBox();

        container.add(baseBox);

             

        // 3. Create the demo panel1 with box layout to display

        // buttons B1 and B2.

        // a) Create the panel and set the box layout.

        JPanel glueDemoPanel1 = new JPanel();

        glueDemoPanel1.setLayout(new BoxLayout(glueDemoPanel1, 

                                     BoxLayout.X_AXIS));

        // b) Set the title border around the panel.

        TitledBorder border1 = new TitledBorder(

                                  new LineBorder(Color.black),

                                  "Glue Component: Demo-1");

        border1.setTitleColor(Color.black);

        glueDemoPanel1.setBorder(border1);

        // c) Add the buttons B1 and B2 with a glue component

        // between them.

        glueDemoPanel1.add(new JButton("B1"));

        glueDemoPanel1.add(Box.createHorizontalGlue());

        glueDemoPanel1.add(new JButton("B2"));


        // d) Add the panel to the base box.

        baseBox.add(glueDemoPanel1);

                

        // 4. Create the demo panel-2, assign box layout and add

        // buttons B3 and B4.

        // a) Create the glue panel 2 and assign the box layout.

        JPanel glueDemoPanel2 = new JPanel();

        glueDemoPanel2.setLayout(new BoxLayout(glueDemoPanel2, 

                                     BoxLayout.X_AXIS));


        // b) Add a titled border to the panel.

        TitledBorder border2 = new TitledBorder(

                                  new LineBorder(Color.black),

                                  "Glue Component: Demo-2");

        border2.setTitleColor(Color.black);

        glueDemoPanel2.setBorder(border2);


        // c) Add the buttons B3 and B4 to the panel; also add

        // the glue components between the buttons, and the

        // buttons and panel.

        glueDemoPanel2.add(Box.createHorizontalGlue());      

        glueDemoPanel2.add(new JButton("B3"));

        glueDemoPanel2.add(Box.createHorizontalGlue());

        glueDemoPanel2.add(new JButton("B4"));

        glueDemoPanel2.add(Box.createHorizontalGlue());


        // d) Add the panel to the base box.

        baseBox.add(glueDemoPanel2);


        // 5. Create a filler panel and add buttons B5 and B6.

        // a) Create the panel object and assign box layout.

        JPanel fillerDemoPanel = new JPanel();

        fillerDemoPanel.setLayout(new BoxLayout(fillerDemoPanel, 

                                     BoxLayout.X_AXIS));


        // b) Set the titled border to the above panel.

        TitledBorder border3 = new TitledBorder(

                                  new LineBorder(Color.black),

                                  "Filler Component Demo");

        border3.setTitleColor(Color.black);

        fillerDemoPanel.setBorder(border3);


        // c) Add buttons B5 and B6 to the panel; also add the

        // filler component between the buttons.

        fillerDemoPanel.add(new JButton("B5"));

        fillerDemoPanel.add(new Box.Filler(

                            new Dimension(50,75), // Minimum Size

                            new Dimension(50,75), // Preferred Size

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

                                                    // Maximum Value 

        fillerDemoPanel.add(new JButton("B6"));


        // Attach the panel to the base box.

        baseBox.add(fillerDemoPanel);

                      

        // 6. Create rigid area panel and add buttons B7 and B8.

        // a) Create a panel and assign the box layout.

        JPanel rigidADemoPanel = new JPanel();

        rigidADemoPanel.setLayout(new BoxLayout(rigidADemoPanel, 

                                     BoxLayout.X_AXIS));


        // b) Assign the title border around the panel.

        TitledBorder border4 = new TitledBorder(

                                  new LineBorder(Color.black),

                                  "Rigid Area Component Demo");

        border4.setTitleColor(Color.black);

        rigidADemoPanel.setBorder(border4);


        // c) Add buttons B7 and B8 to the rigid area panel.

        // Also add a rigid area in the middle of the buttons.

        rigidADemoPanel.add(new JButton("B7"));

        rigidADemoPanel.add(Box.createRigidArea(new

Dimension(150,0)));

        rigidADemoPanel.add(new JButton("B8"));


        // d) Add the panel to the base box.

        baseBox.add(rigidADemoPanel);

        

        // 7. Create the strut panel, assign the box layout, and

        // add the buttons B9 and B10.

        // a) Create the panel and assign the box layout

        JPanel strutDemoPanel = new JPanel();

        strutDemoPanel.setLayout(new BoxLayout(strutDemoPanel, 

                                     BoxLayout.X_AXIS));


        // b) Set the titled border around the panel.

        TitledBorder border5 = new TitledBorder(

                                  new LineBorder(Color.black),

                                  "Strut Component Demo");

        border5.setTitleColor(Color.black);


        // c) Add the buttons B9 and B10 to the panel. Also assign

        // the horizontal strut in the middle of the buttons.

        strutDemoPanel.setBorder(border5); 

        strutDemoPanel.add(new JButton("B9"));

        strutDemoPanel.add(Box.createHorizontalStrut(150));

        strutDemoPanel.add(new JButton("B10"));


        // d) Add the panel to the base box.

        baseBox.add(strutDemoPanel);         

    }

}


JAVA - Grid Bag Layout

 




/*

 * 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 tgridbaglayout;

import javax.swing.*;

import java.awt.*;


public class TGridBagLayout extends JApplet {

    Container container = null;


    public void init() {

        // 1. Get a handle on the applet's content pane.

        container = this.getContentPane();


        // 2. Set the container to the grid bag layout and

        // define a constraint object.

        GridBagLayout gridbag = new GridBagLayout();

        container.setLayout(gridbag);

        GridBagConstraints c = new GridBagConstraints();


        // 3. Common settings for constraint object instant variables.

        c.fill = GridBagConstraints.BOTH;


        // 4. Settings for button B1.

        c.insets = new Insets(5,5,5,5);

        c.gridx = 0; c.gridy = 0;

        c.gridwidth = 2; c.gridheight = 2;

        c.weightx = 1.0; c.weighty = 1.0;

        makeButton("B1", gridbag, c);


        // 5. Settings for button B2.

        c.insets = new Insets(0,0,0,0);

        c.gridx = 2; c.gridy = 0;

        c.gridwidth = 1; c.gridheight = 3;

        makeButton("B2", gridbag, c);


        // 6. Settings for button B3.

        c.gridx = 0; c.gridy = 2;

        c.gridwidth = 1; c.gridheight = 1;

        c.weightx = 1.0; c.weighty=0.5;

        makeButton("B3", gridbag, c);


        // 7. Settings for button B4.

        c.gridx = 1; c.gridy = 2;

        makeButton("B4", gridbag, c);

    }


    // 8. Define the function to create and add a button

    // according to the constraints.

    public void makeButton(String name,

                           GridBagLayout gridbag,

                           GridBagConstraints c) {

        JButton button = new JButton(name);

        gridbag.setConstraints(button, c);

        container.add(button);

    }

}


JAVA - Card Layout






 /*

 * 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 tcardlayout;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.net.*;


public class TCardLayout extends JApplet {

    // 1. Declare some panel and button references.

    JPanel controlPanel;

    JPanel cardsPanel, swCompPanel, aeroCompPanel;

    JButton nextButton, previousButton;

    JButton javasoftButton, sunButton,

            ibmButton, netscapeButton;

    JButton nasaButton, boeingButton,

            lockheedButton, northropButton;

    URL currentSite = null;


    // 2. Define the string arrays for the sites and site urls.

    String[] swCompSites = {"JavaSoft", "Sun",

                            "IBM", "NetScape"};

    String[] aeroCompSites = {"NASA", "Boeing",

                              "Lockheed", "Northrop"};

    String[] siteURLs = { "http://www.javasoft.com/",

                          "http://www.sun.com/",

                          "http://www.ibm.com/",

                          "http://www.netscape.com/" };


    Container container = null;


    public void init() {

       // 3. Get a handle on the applet's content pane.

       container = this.getContentPane();


       // 4. Create a control panel object.

       controlPanel = new JPanel();

       controlPanel.setLayout(new GridLayout(1,2,10,10));


       // 5. Create and add the next and previous control buttons.

       ButtonListener listener = new ButtonListener();

       nextButton = new JButton("Next Card");

       nextButton.setActionCommand("Next Button");

       nextButton.addActionListener(listener);

       controlPanel.add(nextButton);

       previousButton = new JButton("Previous Card");

       previousButton.setEnabled(false);

       previousButton.setActionCommand("Previous Button");

       previousButton.addActionListener(listener);

       controlPanel.add(previousButton);


       // 6. Create a panel to contain the cards.

       /* Each card will display a set of buttons to

          visit a specific Web site. */

       cardsPanel = new JPanel();

       cardsPanel.setLayout(new CardLayout());

       swCompPanel = new JPanel();

       aeroCompPanel = new JPanel();

       swCompPanel.setLayout(new GridLayout(2,2,10,10));

       aeroCompPanel.setLayout(new GridLayout(2,2,10,10));


       // 7. Add buttons to the these cards.

       for (int i=0; i<swCompSites.length; i++) {

           JButton b = new JButton(swCompSites[i]);

           b.addActionListener(listener);

           b.setActionCommand(swCompSites[i]);

           swCompPanel.add(b);

       }


       for (int i=0; i<aeroCompSites.length; i++) {

           JButton b = new JButton(aeroCompSites[i]);

           b.addActionListener(listener);

           b.setActionCommand(aeroCompSites[i]);

           aeroCompPanel.add(b);

       }


       // 8. Add the company-list panels to cards panel.

       cardsPanel.add("Next Card", swCompPanel);

       cardsPanel.add("Previous Card", aeroCompPanel);


       // 9. Finally, add the control and the cards panels to

       // the applet's content pane.

       ((BorderLayout)container.getLayout()).setVgap(10);

       container.add("North", controlPanel);

       container.add("Center", cardsPanel);

    }


    // 10. Functionality to be executed when the next-button

    // is activated.

    public void showNextCard() {

       nextButton.setEnabled(false);

       ((CardLayout) cardsPanel.getLayout()).next(cardsPanel);

       previousButton.setEnabled(true);

    }


    // 11. Functionality to be executed when the previous-button

    // is activated.

    public void showPreviousCard() {

       previousButton.setEnabled(false);

       ((CardLayout) cardsPanel.getLayout()).previous(cardsPanel);

       nextButton.setEnabled(true);

    }


    // 12. Functionality to display the specific Web page.

    public void toDestination(String aSite) {

       System.out.println("Connecting to the web site...");

       try {

           currentSite = new URL(aSite);

       }

       catch (MalformedURLException e) {

          System.out.println("Unknown URL Address: " + aSite);

       }

       getAppletContext().showDocument(currentSite);

    }


    // 13. The action listener class.

    class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {

            JButton tempButton = (JButton) ae.getSource();


            // 14. If the next or previous buttons are pressed...

            if (tempButton.getActionCommand() == "Next Button") {

                showNextCard();

            }

            else if (tempButton.getActionCommand() == "Previous Button") {

                showPreviousCard();

            }


            // 15. If the Web site buttons are pressed...

            for (int i=0; i<swCompSites.length; i++) {

                if (tempButton.getActionCommand() == swCompSites[i])

                    toDestination(siteURLs[i]);

            }

        }

    }

}


JAVA - BORDER LAYOUT

 




/*

 * 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 tborderlayout;

import java.awt.*;

import javax.swing.*;


public class TBorderLayout extends JApplet {

    Container container = null;


    public void init() {

       //1. Get a handle on the applet's content pane.

       container = this.getContentPane();

       // container.setLayout(new BorderLayout());

       /* Note: Don't have to explicitly set border layout,

          because the content pane uses border layout

          by default */


       // 2. Give some horizontal and vertical gaps between buttons.

       ((BorderLayout) container.getLayout()).setHgap(2);

       ((BorderLayout) container.getLayout()).setVgap(2);


       // 3. Array that contains border layout constants.

       String[] borderConsts = { BorderLayout.NORTH,

                                 BorderLayout.SOUTH,

                                 BorderLayout.EAST,

                                 BorderLayout.WEST,

                                 BorderLayout.CENTER };


       // 4. Array that contains button names.

       String[] buttonNames = { "North Button", "South Button",

                                "East Button", "West Button",

                                "Center Button" };


       // 5. Create and add buttons to the container.

       for (int i=0; i<borderConsts.length; i++) {

          JButton button = new JButton(buttonNames[i]);


          // You may wish to reset the preferred size of the east

          // and west buttons to display wide labels.

          if (buttonNames[i] == "East Button" ||

              buttonNames[i] == "West Button") {

              button.setPreferredSize(new Dimension(115, 25)); 

              // width=115, height=25

          }

          container.add(button, borderConsts[i]);

       }

    }

}







JAVA - Grid Layout

 




/*

 * 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 tgridlayout;

import javax.swing.*;

import java.awt.*;


public class TGridLayout extends JApplet {

    Container container = null;


    public void init() {

       // 1. Get a handle on the applet's content pane.

       container = this.getContentPane();


       // 2. Assign the grid layout to the content pane.

       GridLayout grid = new GridLayout(3,2, 5,5);

           // rows = 3, cols = 2, horizontal gap =5, vertical gap = 5

       container.setLayout(grid);


       // 3. Create and add components to the content pane.

       for (int i=0; i<6; i++)

          container.add(new JButton("Button"+(i+1)));

    }

}


JAVA - Flow Layout

 





/*

 * 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 tflowlayout;

import javax.swing.*;

import java.awt.*;


public class TFlowLayout extends JApplet {

    Container container = null;


    public void init() {

       // 1. Get the handle on applet's content pane.

       container = this.getContentPane();


       // 2. Create the flow layout object and set it for the applet.

       FlowLayout fl = new FlowLayout(FlowLayout.LEFT, 5, 10);

                 // horizontal gap = 5 pixels, vertical gap = 10 pixels

                          

       container.setLayout(fl);


       // 3. Create and add some buttons to the applet.

       for (int i=0; i<4; i++) {

          JButton button = new JButton("Button"+(i+1));

          button.setPreferredSize(new Dimension(100,25)); // width=100, height=25

          container.add(button);

       }

    }

}


JAVA - Tabbed Pane

 


/*

 * 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 tjtabbedpane;

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;


public class TJTabbedPane extends JApplet {

    JTabbedPane tabbedPane;

    String[] aircraft = {"Aircraft1.jpg",

                         "Aircraft2.jpg",

                         "Aircraft3.jpg"};

    String[] tips = {"Cruise", "Banking", "Take-off"};


    public void init() {

        // 1. Create a tabbed pane object.

        tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);

        tabbedPane.addChangeListener(new TabbedPaneListener());


        // 2. Add tabs to the tabbed pane. Each tab displays

        // an aircraft. 

        for (int i=0; i<aircraft.length; i++) {

           JLabel label = new JLabel(new ImageIcon(aircraft[i]));

           tabbedPane.addTab("Aircraft-"+(i+1), // Tab text

                             new ImageIcon("smiley.gif"), // Tab icon

                             label,  // component to be displayed 

                             tips[i]); // Some tip at the tab  

        }


        // 3. Add the tabbed pane to the applet.

        getContentPane().add(tabbedPane);

    }


    // 4. Tabbed Pane listener class.

    class TabbedPaneListener implements ChangeListener {

        int selectedIndex = -1; // -1 = default number less than 0

        JTabbedPane tp;


        public void stateChanged(ChangeEvent ce) {

            tp = (JTabbedPane) ce.getSource();


            // 5. Code to disable a tab that has been selected, and

            // enable the tab that has already been disabled. 

           if (selectedIndex == -1 || // if pressed for first time

                selectedIndex != tp.getSelectedIndex()) {

                tp.setEnabledAt(tp.getSelectedIndex(), false);

                if (selectedIndex != -1) // if not the first press

                   tp.setEnabledAt(selectedIndex, true);

            }

            // Store the index of the newly selected tab.

            selectedIndex = tp.getSelectedIndex();

        }

    }

}


JAVA - Split Pane



/*
 * 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 tjsplitpane;
import javax.swing.*;
import java.awt.*;

public class TJSplitPane extends JApplet {
    static int HORIZSPLIT = JSplitPane.HORIZONTAL_SPLIT;
    static int VERTSPLIT = JSplitPane.VERTICAL_SPLIT;
    boolean continuousLayout = true;
    Icon icon1 = new ImageIcon("a.gif");
    Icon icon2 = new ImageIcon("a.gif");
    Icon icon3 = new ImageIcon("a.gif");

    public void init() {
        // 1. Create a label to display icon1 and add it to a scroll pane.    
        JLabel label1 = new JLabel(icon1);
        JScrollPane topLeftComp = new JScrollPane(label1);
        
        // 2. Create another lable to display icon2 and add it to another scroll pane.
        JLabel label2 = new JLabel(icon2);
        JScrollPane bottomLeftComp = new JScrollPane(label2);
        
        // 3. Create a third label to display icon3 and add it to one more scroll pane.
        JLabel label3 = new JLabel(icon3);
        JScrollPane rightComp = new JScrollPane(label3);
    
        // 4. Add the scroll panes displaying icon1 and icon2 to a split pane.
        JSplitPane splitPane1 = new JSplitPane(VERTSPLIT,
                                          continuousLayout,
                                          topLeftComp,
                                          bottomLeftComp);
        splitPane1.setOneTouchExpandable(true); // Provide a collapse/expand widget.
        splitPane1.setDividerSize(2); // Divider size.
        splitPane1.setDividerLocation(0.5); // Initial location of the divider.
        
        // 5. Add the previous split pane and the scroll pane displaying 
        // icon3 to an outer split pane.
        JSplitPane splitPane2 = new JSplitPane(HORIZSPLIT,                                        
                                          splitPane1, // left comp
                                          rightComp);
        splitPane2.setOneTouchExpandable(true); // Provide a collapse/expand widget.
        splitPane2.setDividerLocation(0.4); // divider size 
        splitPane2.setDividerSize(2); // Initial location of the divider.
           
        // 6. Add the outer split pane to the content pane of the applet.                             
        getContentPane().add(splitPane2);                                 
    }
}