Jfc/swing Ingenious series of custom jlist display

Source: Internet
Author: User
Tags object interface locale printf readable return string tostring
Show

  Click here to download the source file

   Introduction

In the graphical user interface (GUI), Java has been unable to compete with C + +, PB, Delphi and so on, the use of the early JAVA/AWT package developed by the interface is really people dare not to compliment. With the maturing of jfc/swing, it is no longer an "impossible task" to develop a GUI comparable to C + +. In addition to its rich interface components, the following excellent features make swing even more powerful. Swing is implemented in 100% pure Java and is based on the JDK 1.1 lightweight UI framework, without native code, independent of the operating system, based on MVC design patterns, with a pluggable look and feel (pl&f), which makes us feel her charm.

The full JFC is huge, and swing is just one of them, and this article will focus on the jlist components in the swing package and how to customize the display.

   jlist Basic Knowledge

The swing list represented by the JList class displays a list of optional objects that support three selection modes: Single selection, single interval selection, multiple interval selection.

Based on the idea of MVC construction, the JList class does not maintain a reference to the objects it displays, but instead delegates the data management work to an object that implements the Listmodel interface; the JList class does not track and maintain the selection of its display objects. Instead, the work of selecting management is delegated to an object that implements the ListSelectionModel interface; the JList class does not draw the objects it displays, but instead delegates the drawing work of the list unit to an object that implements the Listcellrenderer interface.

The JList component gives three main tasks (data processing, list item selection, Unit drawing) to other objects, and each instance of JList maintains references to the above objects, thus greatly reducing the coupling of each functional module, and is easy to expand and maintain.

   jlist How do I display a list of objects?

By default, the JList object displays the icon and string objects as-is, and for all other objects, only the return value of the object ToString () method is displayed. For example, there is an application that displays a list of Java.util.Locale objects to the user, who can change the locale of the application by selecting items in the list.

Imagine how jlist would display a data model that contained a locale object? JList delegate Javax.swing.ListCellRenderer to display these objects. As we expected, Listcellrenderer will display the return value of the object ToString () method. However, the locale object returns ISO code, and such a display is certainly inconsistent with the "interface-friendly" principle. By default, the content displayed by JList is confusing to most users, as shown in the following illustration:


Looking at the following example, it is more appropriate to illustrate that the default display of the JList object does not provide any meaningful data to the user. Suppose a drawing program provides a list of color choices, and you might choose a color for filling, perhaps for drawing lines, or whatever. Although the practice of putting the Java.awt.Color object instance into the JList is a very modest one, the user cannot get any help from it, which is a departure from our original intention. As shown in the following illustration:


The Color object ToString () method returns the brightness values of the three primary colors of red, green, and Blue (RGB) components, regardless of the specific color it represents. Unless the user knows that the sixth row 0, 255, 0 represents the green color, or we should be in this position to show some more useful information to the user.

Admittedly, you might be able to place an instance of a Java.lang.String object in a jlist to replace an instance of a color object, but that would give up the purpose of using JList: The user is choosing a color from the list instead of selecting a text description.

When you use a Color object, the listener of the jlist change returns the color that the user actually sees. If you replace it with a string object, JList will return the string object to the listener, and then the listener can then match the corresponding color to complete the fill operation, a little superfluous feeling.

  Find Solutions

As a user, we hope that the application of the interface is clear, rather than the locale object of the ISO code or color RGB values display, interface-friendly software to attract users. ISO code or RGB values may be useful to programmers, but they are not suitable for end users.

Fortunately, the locale object has a DisplayName attribute that is suitable for displaying information to the user. We can use this property instead of the ToString () method for jlist display, which makes jlist more readable. Compare the ToString () method of the Locale object in the following code fragment with the return value of the GetDisplayName method:

Locale[] locales = {new Locale ("en", "US"), New Locale ("fr", "fr"),
New Locale ("th", "th"), New Locale ("Es", "MX"),
New Locale ("Ja", "JP")};
System.out.printf ("%-10s\t%s\n", "toString", "GetDisplayName");
System.out.printf ("%-10s\t%s\n", "--------", "--------------");
for (Locale l:locales)
{
System.out.printf ("%-10s\t%s\n", l.tostring (), L.getdisplayname ());
}


On a machine that will have Chinese Windows XP, the results of the run are as follows:

ToString GetDisplayName
-------- --------------
en_US English (USA)
FR_FR French (France)
th_th Swahili (Thailand)
ES_MX Spanish (Mexico)
JA_JP Japanese (Japan)

The Locale object's DisplayName properties are more readable and closer to the user. If the jlist in the application uses the DisplayName attribute, it will look like this:


So how is this effect achieved? In order for the list to perform better in the user interface, we create our own listcellrenderer, so in the example above we can override the default ToString () method's return value by displayname attribute.

Similarly, if we choose color applications, we can also use custom listcellrenderer to display the corresponding names and colors of the color objects. As shown in the following illustration:


Let's take a look at how Listcellrenderer works, the Listcellrenderer interface defines only one method, and the method returns a component:

Public abstract Component getlistcellrenderercomponent (JList list,object value,int Index,boolean
Boolean cellhasfocus)


The component returned by getlistcellrenderercomponent acts like a leather stamp, which draws the component to the area of the list item in the list. The point to note is that the list unit does not contain this component, and the component is drawn to the list cell only. This is important because the component cannot be manipulated, and only the visible representatives of this component can be used to draw the list cells.

By default, an instance of JList is fitted with a drawing device, which is a simple implementation of the Listcellrenderer interface, the Defaultlistcellrenderer class. This class extends the JLabel class and can display strings or icons, but cannot display both strings and icons in one cell.

Although the custom listcellrenderer can inherit any component, the solution we choose for the above application is good for defaultlistcellrenderer, because inheriting JLabel, you can easily set text, color, Even pictures. Refer to the following code:

Public Component getlistcellrenderercomponent (JList list, Object value,
int index, Boolean isselected, Boolean cellhasfocus)
{
Super.getlistcellrenderercomponent (list, value, index, isselected,cellhasfocus);
Locale L = (Locale) value;
SetText (L.getdisplayname ());
return this;
}


Renderer first calls its superclass's getlistcellrenderercomponent () method to draw the component, and then you just need to make some simple settings, where we use the GetDisplayName of the selected locale object () method to set the text by the return value of the

With custom Listcellrenderer, it's simpler to jlist to use this new renderer, calling the JList object's Setcellrenderer () Method and passing the newly created Listcellrenderer instance as a parameter is sufficient. The JList object will display each locale object in the list with a custom renderer. Refer to the following code fragment:

Listcellrenderer localerenderer = new Localerenderer ();
Localelist.setcellrenderer (Localerenderer);


The example of customizing the color picker is somewhat different from the locale example. The difference is that the adorner not only sets the text content of the option cell, but also sets its color and corresponding background colors. Because there is no built-in text name in the Color object itself, we need to establish a mapping relationship between the color name and the color. Here we use HashMap to complete the mapping operation. See Resources for specific code examples.

   Concluding remarks

Finally, let's mention how the object is displayed in the JList. You do not have to rely on the ToString () method provided by the object because we can use Listcellrenderer to display any text associated with the object that you want to display. In addition, we can use any color or graphic to draw on the selected components as Listcellrenderer. We can also apply the same drawing device to JComboBox. With custom listcellrenderer, you can use the JList and JComboBox components to write user-interface more user-friendly applications.



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.