Sunday, October 7, 2012

Custom JComponent

javax.swing.JComponent is the base class for all Swing components except top-level containers.

Example to create custom JComponent:

Custom JComponent

package javaswing;

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestSwing {
    
    static JFrameWin jFrameWindow;
    
    public static class MyComponent extends JComponent{
       
        Dimension myDimension = new Dimension(300, 100);

        @Override
        public Dimension getPreferredSize() {
            return myDimension;
        }

        @Override
        public Dimension getMaximumSize() {
            return myDimension;
        }

        @Override
        public Dimension getMinimumSize() {
            return myDimension;
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.drawLine(0, 0, getWidth()-1, getHeight()-1);
            g.drawLine(0, getHeight()-1, getWidth()-1, 0);
            g.drawRect(0, 0, getWidth()-1, getHeight()-1);
        }

    }
    
    public static class JFrameWin extends JFrame{
        public JFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(350, 250);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
            MyComponent myComponent1 = new MyComponent();
            MyComponent myComponent2 = new MyComponent();
             
            Box verticalBox = Box.createVerticalBox();

            verticalBox.add(myComponent1);
            verticalBox.add(myComponent2);
            this.add(verticalBox);
        }
    }
    

    public static void main(String[] args){
        Runnable doSwingLater = new Runnable(){
            public void run() {
                jFrameWindow = new JFrameWin();
                jFrameWindow.setVisible(true);
            }
        };
        
        SwingUtilities.invokeLater(doSwingLater);
        
    }

}


No comments:

Post a Comment