Java Practical Experience Swing Summary __java

Source: Internet
Author: User

Reprint: http://blog.csdn.net/chenzhiya/article/details/2274181

Java Practical Experience Swing summary

Objective

This article preface some of my feelings, if you are only interested in the Java practical skills described in this article, you can skip the preface to see the content of the text directly.

The writing motivation of this paper comes from a small program that has been recently written to help people write, which is mainly used to manage a series of management of installment payment, including the record of overdue money, the calculation of the interest of the overdue payment, and some rebate rewards for the users who pay in advance, etc. In order to complete the task as soon as possible, I naturally chose the most I used Java to achieve. After 2 weeks of work, successfully completed the task, tomorrow can be done, but this moment I suddenly have some other ideas. It is true that this kind of work belongs to manual labor, similar to the work I have done more than once, for many high man, there is nothing to mention, before I was just a job to collect money, but this time I have a number of ideas, so I do not spit unhappy.

In the process of implementation, I encountered a small problem, is to calculate the difference of two dates. Since most of the methods used in the date class were marked "Deprecate", I decided to use calender as the main force for calculating dates. But most reference books are made up of date formats about calender, locale settings, the meaning of constants and so on, but how can not find such a simple but commonly used tasks how to achieve (note: This can not blame me lazy, as such a program, if there is a correct and mature method, Who's going to spend a lot of time looking at the API more carefully? Anyway, this class may not be used in the next few months or even years, and now remember to forget L. So after I Google for a good while, finally on someone's blog found the use of calender to calculate the date difference method. At that moment I really have a sense of Kyogo. The blogger may have been on the spur of the moment, and it may have been an interest, but whatever the reason, his work has provided me with great convenience. With his code example, I can no longer go to the Java-doc inside the API, and then pick out a few to try to solve the problem, and finally write a demo to verify the complexity of the process.

Recall the process of completing this program, because I have done some similar programs before, I can put many parts of the inside to directly apply to this program, saving a lot of time, so I can focus more on the core business implementation. However, perhaps out of laziness, perhaps no time, and perhaps the original blog is not a lot of attention, I do not have these most people may be used to put things on the internet.

Then think of foreign open source workers on the Chinese programmer's evaluation-"only get, do not contribute," feel that people are very right. You can use the free j2sdk language, free Eclipse, free jfreechart, free jasperreport ..., but never be able to contribute even one line of code to others. That would be fine, but something like what you can do, such as the small problems that every Java programmer might encounter, the little tricks, the mistakes that often occur, why can't I just post them for sharing? You might be able to help a guy solve a big problem, and it's more likely that your words will save someone a few minutes or even a few hours. If everyone can post some of their experiences in their spare time, trust that more people will benefit from it. When you encounter problems, you can be comfortable to go to Google or Baidu. Believe that this is the Technical Forum and Technology blog's original intention, after all, the world is not only money is the most important driving force.


1 Change the default font/font size for swing applications

People who often use swing as a program UI may notice that the Swing component defaults to display text with a font size of 11. This is no problem with the English display, but if you use this font size to display Chinese, such a small size will make the program become very difficult to see. I used to use IReport0.56 when I found his menu bar and pop-up dialog in the word is very difficult to see, but the size of the increase after a lot better. Although this font problem seems to be fixed in the most recent version of JDK, if your program has to use a previous version of the JDK, the problem needs to be addressed, and here's a good solution:

Font vfont = new font ("Dialog", Font.plain, 13);

Uimanager.put ("Tooltip.font", Vfont);

Uimanager.put ("Table.font", Vfont);

Uimanager.put ("Tableheader.font", Vfont);

Uimanager.put ("Textfield.font", Vfont);

Uimanager.put ("Combobox.font", Vfont);

Uimanager.put ("Textfield.font", Vfont);

Uimanager.put ("Passwordfield.font", Vfont);

Uimanager.put ("Textarea.font", Vfont);

Uimanager.put ("Textpane.font", Vfont);

Uimanager.put ("Editorpane.font", Vfont);

Uimanager.put ("Formattedtextfield.font", Vfont);

Uimanager.put ("Button.font", Vfont);

Uimanager.put ("Checkbox.font", Vfont);

Uimanager.put ("Radiobutton.font", Vfont);

Uimanager.put ("Togglebutton.font", Vfont);

Uimanager.put ("Progressbar.font", Vfont);

Uimanager.put ("Desktopicon.font", Vfont);

Uimanager.put ("Titledborder.font", Vfont);

Uimanager.put ("Label.font", Vfont);

Uimanager.put ("List.font", Vfont);

Uimanager.put ("Tabbedpane.font", Vfont);

Uimanager.put ("Menubar.font", Vfont);

Uimanager.put ("Menu.font", Vfont);

Uimanager.put ("Menuitem.font", Vfont);

Uimanager.put ("Popupmenu.font", Vfont);

Uimanager.put ("Checkboxmenuitem.font", Vfont);

Uimanager.put ("Radiobuttonmenuitem.font", Vfont);

Uimanager.put ("Spinner.font", Vfont);

Uimanager.put ("Tree.font", Vfont);

Uimanager.put ("Toolbar.font", Vfont);

Uimanager.put ("Optionpane.messagefont", Vfont);

Uimanager.put ("Optionpane.buttonfont", Vfont);

This code is used at the beginning of the program to effectively set the Swing component's display font to what we set in Vfont. 1.1 to Better center the window

Whether it's a top-level component JFrame or a dialog box JDialog, it's a common problem to have their windows centered, because they always bounce from the top left corner, which is too bad. For this issue, the JBuilder Application Generation Wizard gives the solution:

Dimension screensize = Toolkit.getdefaulttoolkit (). Getscreensize ();

Dimension framesize = Frame.getsize ();

if (Framesize.height > Screensize.height)

Framesize.height = Screensize.height;

if (Framesize.width > Screensize.width)

Framesize.width = Screensize.width;

Frame.setlocation ((screensize.width-framesize.width)/2,screensize.height-framesize.height)/2);

This method is sufficient for most window components, but there are other problems, such as resolution and display size will cause the application window "deformation", clearly in the 17-inch display 1024*768 resolution display a good window to the 19-inch 1280*800 widescreen will be "pull "Very long." As a result, although there is a layout manager to help us manage the placement of the components after stretching, but still can not solve the elongated after the aesthetic problems. My experience is that for some windows, because it is "stretched", the gap between its internal components becomes so large that it looks ugly. So you should set a suitable display size for them. In the center of the display when only adjust the position without changing the size, so that the window does not affect the appearance. So we just need to change the code to the above, take JFrame as an example:

Dimension screensize = Toolkit.getdefaulttoolkit (). Getscreensize ();

ScreenSize = Toolkit.getdefaulttoolkit (). Getscreensize ();

Frame.setpreferredsize (New Dimension (512,450));

int framewidth = This.getpreferredsize (). width;

int frameheight = This.getpreferredsize (). Height;

Frame.setsize (Framewidth, frameheight);

Frame.setlocation ((screensize.width-framewidth)/2, (Screensize.height-frameheight)/2); 2 Custom JFrame shutdown events

Sometimes, when the user closes the application window, we may want the program to save some necessary data before it ends. For this kind of demand, we have two options: 2.1 Get the "hook" that the program closes

Runtime.getruntime (). Addshutdownhook (Shutdownhook);

protected Thread Shutdownhook = new Platformshutdownhook ();

Protected class Platformshutdownhook extends Thread {

public void Run ()

{

Some cleanup work is done here ...

}

}

In this way, we can get notifications at the end of the program to do some saving or cleanup work. The disadvantage of this approach, however, is that when the program receives the end notification, all UI components have been destroyed and the user sees at this point that the program has ended. In fact, if it takes a long time for a program to be saved, the user can't get any information, which is a bad user experience. Because if the user shuts down, the program is likely to lose unsaved information, and for all this, users do not know. 2.2 Handling JFrame shutdown events

In order to receive a message that the program ends before the UI is destroyed, we need to handle the event that the window closes. Note that we have not adopted addActionListener (...) here. method, because doing so only allows us to be notified after the window is closed, which is no different from the method above.

We need to set up in the JFrame constructor:

Set flags to allow mainframe to receive window events themselves

EnableEvents (Awtevent.window_event_mask);

And then implement the following function:

protectedvoid processwindowevent (final windowevent pevent) {

if (Pevent.getid () = = windowevent.window_closing) {

/** prevents users from clicking the "Close" button multiple times to create a duplicate save **/

if (!isclosing) isclosing = true;

Else return;

Handling JFrame shutdown Events ...

}Else{

Ignore other events and give JFrame treatment

Super. processWindowEvent (pevent);

}

}

In this way, we can notify the user that the program is saving the data before the window is closed, such as what Infiniteprogresspanel can display later. conflict between selected components and JDialog for the 3rd issue

Because many applications require the user to enter the date, but fear that the user entered the wrong date format, so the date selection component came into being. Although we need it very much, most of the components on the Internet need to be paid. Before I found SWINGX, the only calendar component I found that was free to use was a jdialog named Datechooser:

Looks very good, it supports Chinese, for today's highlighting, you can adjust the year and month ... Everything is in line with the requirements. But such a good component cannot be used in my program because in my program, the component that calls this component is also a jdialog and set Setalwaysontop (true)-that is always displayed on the front end. Since Datechooser is also set to display at the front end, this causes it to conflict with the display of its parent component, and the end result is that Datechooser is not displayed properly. For this issue, I end up using SWINGX component DatePicker to replace Datechooser finish the task of choosing the date, wont datepicker use I will in the "Swingx use Details" mentioned, here is no longer detailed. But this question still deserves our attention, that is, if a window component is set to always display at the top of the JDialog, then do not use this jdialog as the parent component to eject other jdialog, to avoid the occurrence of conflicts.

4 Practical tips for jtable

It's not uncommon for an application to display data in tabular form. So JTable became our most indispensable friend in all swing components. For jtable operations, most of the cases can be done without a fake request, because the JDK's own example SwingSet2 show us enough functionality.

In this example, we can change the spacing of cells, row heights, select Type (Selection Style), show horizontal lines, and even print out the contents of a table. In addition to the text, the table can contain other components and content, such as SwingSet2 to add the color of the JComboBox and favorite food represents the picture.

But there are times when we have other needs. For example, to protect our eyes, we want the contents of the table to be spaced, such as odd rows showing blue, and even rows showing white. Or we want the contents of some columns in the table to be editable, and the contents of his columns are not editable. or let the columns in the table have a sort function, so that we can click the header to arrange itself in order from low to high or from high to low. Finally we want the table header and cell gree content to be centered. Let's implement these features one at a while. 4.1 interval color table and cell/header Center display

The JTable API does not provide us with the ability to change the color of a table row or column. But we know that table headers and content rendering forms are controlled by the corresponding renderer, so we only need to inherit the cell default renderer and make the corresponding changes to achieve the purpose:

Because the interface is implemented

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.