Searching...
Sunday, June 1, 2014

Swing JPanel - 2

June 01, 2014
JPanels are not only used as a layer for the Content Pane, they are a generic container for widgets and can do all sorts of things. In the next part of this tutorial, we will show you how to add widgets to the Content Pane and teach you basic manipulation of a JPanel.            Now it is time to actually add something to the Window that you can see! "At last!" I hear you yell. This process is very simple. Let's look at the example previously and add some coloured panels to the content pane. PanelExample_Extended.java
package java9r.blogspot.com;

import javax.swing.*;

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

public class PanelExample_Extended{
   
     public JPanel createContentPane (){
       
        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
       
        // We set the Layout Manager to null so we can manually place
        // the Panels.
        totalGUI.setLayout(null);
       
        // Now we create a new panel, size it, shape it,color it red.
        // then add it to the bottom JPanel.
        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        redPanel.setLocation(10, 10);
        redPanel.setSize(50,50);
        totalGUI.add(redPanel);

        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        bluePanel.setLocation(220, 10);
        bluePanel.setSize(50, 50);
        totalGUI.add(bluePanel);
       
        // Finally we return the JPanel.
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("--------- There's 3 JPanels in here! ---------");
       
        //Create and set up the content pane.
        PanelExample_Extended demo = new PanelExample_Extended();
        frame.setContentPane(demo.createContentPane());
       
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
 Output

0 comments:

Post a Comment

ads2