Jfc/swing Ingenious Create custom image components

Source: Internet
Author: User
Tags define object constructor contains event listener final return string
Create

  Introduction

This article describes how to apply the jfc/swing image component to create a fully customizable image-based user interface.

Most swing applications are provided through standard VMS, or the look and feel (l&f) provided by the customer to obtain their external display. L&f is a complete architecture, the VM needs to do a lot of internal work, and it's not fully customizable. For example, in the context of l&f, we can create a button that looks a bit like a "red light" on a traffic post, and all the buttons in your application have the appearance. But sometimes what we really need is a button that looks exactly like the image on the web.

To get a better idea of what we're going to introduce, let's look at the final display, as shown in the following illustration: A panel pane (Frame) contains a label, a button, a check box (checkbox). panels, labels, and buttons are completely drawn from the image and are completely unused to standard l&f. The checkbox is a standard checkbox, but it will be designed to be transparent to match the image background.



   The first step is to create a background panel

To complete this "paradise" project, the first thing we have to do is create an image background. Because of the high reusability (reusable) of such components, we created a subclass of the JPanel class called Imagepanel, referring to the following code example:

Example code 1:

Package com.demo.jcomponents;

Import java.awt.*;
Import javax.swing.*;

/**
* Create Image panel
* @author Xiazhi
*/
public class Imagepanel extends JPanel
{
/**
* Drawing objects
*/
Private Image img;

/**
* Constructor
*
* @param img Image Object
*/
Public Imagepanel (String img)
{
This (new ImageIcon (IMG). GetImage ());
}

/**
* Constructor
*
* @param img Image Object
*/
Public Imagepanel (Image img)
{
This.img = img;

Define Image Dimensions
Dimension size = new Dimension (Img.getwidth (null), img.getheight (null));
Setpreferredsize (size);
Setminimumsize (size);
Setmaximumsize (size);
SetSize (size);

Define Layout Method Empty
SetLayout (NULL);
}

/**
* Redraw the canvas
*/
public void Paintcomponent (Graphics g)
{
G.drawimage (IMG, 0, 0, NULL);
}
}
The constructor uses an instance of image as a parameter and saves the drawn image in the variable img for later use. The SetSize () and Setpreferredsize () methods are then invoked with the dimensions of the image as parameters. This ensures that the panel size is identical to the size of the image. The next step is important to specify the preferred, maximum, and minimum dimensions of the Panel, because the parent class and subclasses of the Panel class may not use absolute layout.

   Tip: As we all know, Swing uses layout manager (Layout Manager) to control the location of components, and absolute layout means not using Layout Manager to control the location of components. (You can specify an absolute layout by using the setlayout (null) method)

In this case, displaying the specified size and position will be used (through the setsize () and setlocation () methods). The preferred,minimum and maximum dimensions may be used when the specified layout manager is used. To accommodate all of the above, we simply set the four methods mentioned above.

Now that the Panel has set the appropriate size, we can paint the image by overloading the Paintcomponent () method:

public void Paintcomponent (Graphics g)
{
G.drawimage (IMG, 0, 0, NULL);
}
   Tip: Here we overload the Paintcomponent () method, not the paint () method, which is important, otherwise the subclass will not be redrawn.

Now to test the results of our work, we add the customized panel to a frame and then display the frame, referring to the following code example:

Example code 2:

Package com.demo.jcomponents;

Import javax.swing.*;

/**
* Test Image Panel Component
* @author Xiazhi
*/
public class ImageTest1
{
public static void Main (string[] args)
{

Imagepanel panel = new Imagepanel (Createimageicon ("Images/background.png"). GetImage ());

JFrame frame = new JFrame ("jfc/swing: Creating an image-themed component");
Frame.getcontentpane (). Add (panel);

Frame.pack ();
Frame.setvisible (TRUE);
}

protected static ImageIcon Createimageicon (String path)
{
Java.net.URL Imgurl = ImageTest1.class.getResource (path);
if (Imgurl!= null)
{
return new ImageIcon (Imgurl);
}
Else
{
SYSTEM.ERR.PRINTLN ("Cannot find the specified file:" + path);
return null;
}
}
}
After the program is run, the display effect is as follows:

   The second step is to create an image label

Now the background of the drawing work has been completed. Next, the focus will be shifted to the label "Activate reactor" production. Here is just a static image placed in the appropriate position in the background. We can certainly use another Imagepanel instance to do this, but since the words "Activate reactor" are actually just a label, we have created another subclass Imagelabel, refer to the following code example:

Example Code 3:

Package com.demo.jcomponents;

Import javax.swing.*;

/**
* Image Label
* @author Xiazhi
*/
public class Imagelabel extends JLabel
{
/**
* Constructor
*
* @param img Image Object
*/
Public Imagelabel (String img)
{
This (new ImageIcon (IMG));
}

/**
* Constructor
*
* @param icon Image Object
*/
Public Imagelabel (ImageIcon icon)
{
Set label icon
SetIcon (icon);
Set the spacing between the label icon and the text
Seticontextgap (0);
Set border
SetBorder (NULL);
Set text
SetText (NULL);
SetSize (Icon.getimage (). GetWidth (null), Icon.getimage (). GetHeight (null));
}
}
Like Imagepanel, we need to match the size of the label to the size of the image. All we need to do here is call the SetSize () method, because label itself handles other settings. Next, set the icon to the image we specified so that label itself handles the drawing of the image. By setting the text interval to 0 and setting the border blank, setting the text blank will remove any extra space for the image, which will cause the label to mesh perfectly with the background. The Setopaque (False) method tells the label not to draw the background itself. If you fill a label with an image, the problem is small, but if the image contains transparent areas (most of the PNG types of images will look like this), then the background in the transparent area will be displayed.

Now let's Test our results! Add a label based on the test above and refer to the following code example:

Example Code 4:

Imagelabel label = new Imagelabel (Createimageicon ("images/reactor.png"));
Positioning label
Label.setlocation (29, 37);
Add a hint to the label
Label.settooltiptext ("Did you see it?") ");
Add a label to a panel
Panel.add (label);
After the program is run, the display effect looks like this:

   Step three Create the image button

The next step is to create a custom button. Because the button has flip and state characteristics, it requires some skill to draw a button. We created a subclass of the JButton class again, referring to the following code example:

Example code 5:

Package com.demo.jcomponents;

Import java.awt.*;
Import javax.swing.*;

/**
* Image button
* @author Xiazhi
*/
public class ImageButton extends JButton
{
/**
* Constructor
*
* @param img Image instance
*/
Public ImageButton (String img)
{
This (new ImageIcon (IMG));
}

/**
* Constructor
*
* @param icon Image
*/
Public ImageButton (ImageIcon icon)
{
Set icon
SetIcon (icon);
Set blank spacing
SetMargin (New Insets (0, 0, 0, 0));
Set the spacing between text and icons
Seticontextgap (0);
Specify whether to draw borders
Setborderpainted (FALSE);
Set border
SetBorder (NULL);
Set text
SetText (NULL);
SetSize (Icon.getimage (). GetWidth (null), Icon.getimage (). GetHeight (null));
}
}
This code is almost exactly the same as the JLabel code that was previously customized to display. The only difference is that the calls to the SetMargin () and SetBorder () methods are added. Most l&f use borders (Border) and Boundaries (Margin) to indicate whether the button has been selected. Because the label cannot be selected, there is no such method. Anyway, we can just close these two properties.

Now let's Test our results! Add a button based on the above test, and refer to the following code example:

Example code 6:

Final ImageButton button = new ImageButton (Createimageicon ("images/button.png"));
Positioning button
Button.setlocation (60,74);
Add a button to the panel
Panel.add (button);
After the program is run, the display effect looks like this:


Now that the button has been added to the panel, all that remains is to add the flip and other state attributes to the button. Fortunately, these jobs do not require us to add any new code to the subclass. JButton has provided images to characterize flip, press, select, fail, and Fail-select Properties. We just need to use the usual set method to add various state variables, refer to the following code example:

Button.setpressedicon (Createimageicon ("images/button-down.png"));
Button.setrollovericon (Createimageicon ("images/button-over.png"));
Button.setselectedicon (Createimageicon ("images/button-sel.png"));
button
. Setrolloverselectedicon (Createimageicon ("images/button-sel-over.png"));
Button.setdisabledicon (Createimageicon ("images/button-disabled.png"));
button
. Setdisabledselectedicon (Createimageicon ("images/button-disabled-selected.png"));
After adding the above code, run the program again, showing the effect as follows:



Choose

Not selected

Here we use an image with an aperture to indicate that the button is selected, blur the image to indicate that the button is disabled, and the rectangular bar in the middle of the image to indicate the button is selected, in addition to the color change, but also the effect of the glow.

To fully demonstrate all States, we added a standard jcheckbox to the lower part of the button, which would normally draw a gray background (or a striped background on the Mac) and we call Setopaque (false) method to force the requirement that it not be drawn. Calling the Checkbox.setsize (Checkbox.getpreferredsize ()) method is necessary when the parent class does not use the layout manager, so that the checkbox can be given the appropriate size, as in the example in this article:

Example Code 7:

Final Jcheckbox checkbox = new Jcheckbox ("Disable");
Checkbox.setlocation (70, 150);
Force checkbox not to draw your own background
Checkbox.setopaque (FALSE);
Set the size of a checkbox
Checkbox.setsize (Checkbox.getpreferredsize ());
Add to Panel
Panel.add (checkbox);
Add Event Listener
Checkbox.addactionlistener (New ActionListener ()
{
public void actionperformed (ActionEvent evt)
{
Button.setenabled (!checkbox.isselected ());
}
});
To this sample program is complete, after the program is run, the overall display effect looks like this:



   Concluding remarks

At this point, we have created a fully customizable image-based component, Jfc/swing has a huge structure, how to better understand, and clarify the delicate relationship between components, is the key to learn swing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.