Swing and AWT access to the version
Abstract: access to the version of Swing and AWT
</ Td> </ tr> <tr> <td width="373" height="35" valign="top" class="ArticleTeitle">
Import javax.swing .*;
(Public class Version
Public static void main (String args []) (
JLabel l = new JLabel ();
Package p = Package.getPackage ( "javax.swing");
If (p! = Null) (
System.out.print ( "Swing Version:");
System.out.println (p.getSpecificationVersion ());
)
P = Package.getPackage ( "java.awt");
If (p! = Null) (
System.out.print ( "AWT Version:");
System.out.println (p.getSpecificationVersion ());
)
)
)
The result:
C: \ java> java Version
Swing Version: 1.4
AWT Version: 1.4
C: \ java>
</ Td> <td width="311" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑ Back
Swing Guide to Getting Started
Abstract: Getting Started Guide Swing
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle">
This handbook is for the beginner Swing. You may know that other people are using it, or you use the application had seen it. Or you may have to try using it personally. No matter what the situation is, this tutorial will take your experience to build a basic Swing application process, starting with the most common HelloWorld application started. When you run on their machines after it, we will introduce you to some of the Swing of knowledge: the creation of a flight booking system, and gradually add to them, until you get a basic, but it is fully capable of the work of the application.
<table Width="731" height="45" border="0"> <tr> <td> </ td> </ tr> </ table>
</ Td> </ tr> <tr>
↑ Back
I studied with the Game Design Java Swing
Abstract: I studied with the Game Design Java Swing
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="677" border="0"> <tr> <td width = " 395 ">
Who knows sky tower of Babylon spent a number of gravel? Who knows Rome experienced the completion of the number of day and night? We only know that there is no one piece of masonry features, there will be no winding Miles of the Great Wall; no boulder clay and the accumulation, there is no time immemorial unchanged pyramid. Thus, the basic knowledge for learning anything we are of the utmost importance, then, let us recognize Swing from some of the basic features, we have started the construction of Rome's great project!
Foreword
Java cafe has opened a lot of time, if you are already fond of the Java cup of coffee flavor, often to remember oh. This time, we all prepared for a large cup aromatic coffee - will be the development of a "Lianliankan" modelled on the game, and we learn together in Java Swing usage, when you taste carefully cup of coffee, you will found that not only Java cup of coffee also have some other flavor, but also learned the professional game development, is the best of both worlds!
</ Td> <td width="272" align="center"> </ td> </ tr> </ table>In order to let everyone see in advance the facilities, the chart is the title game. Members can download the game demo (download games; download source files), then use the command line mode java-jar kyodai.jar to run. In addition, I can go to the Home http://www.ismyway.com download stand-alone version of the game as well as a demo version of mobile phones (see Figure 1).
Java cafe previously introduced AWT knowledge, Swing and AWT then what is the difference? Learning Java people may have heard or seen a heavyweight controls and controls lightweight word AWT is that we usually referred to the heavyweight controls, it is lightweight Swing controls. We all know that Java is the slogan of "one preparation, running everywhere," which will require our procedures, to make the best use of pure Java code. Unfortunately, AWT rely on the local interface platform, therefore, in different operating systems, making use of AWT interface may seem there are some subtle differences. Swing is completely different, using pure Java Swing is prepared, therefore, prepared by the use of Swing interface can be guaranteed in all platforms have the same appearance. There is also a Tips: JDK, in order to facilitate the distinction between all Swing controls all capital letters J to the beginning, for instance, JButton (AWT in the corresponding Button is), so you can easily distinguish between AWT Swing controls and controls the.
Swing early experience
For those who want to learn Swing programming friends, we are all specially prepared for some tips. First, download and read the code is very necessary. Since this is a tutorial on the Swing, therefore, we are just as much as possible on some of the contents of the Swing, Swing has nothing to do with the content of the general will not be involved, for example, some algorithm. Secondly, to space restrictions, it will not be possible here will be part of the code is written in every End integrity of the whole, therefore, we also need to control integrity of the code. Finally, in order to make it easier for you to concentrate on Swing learning, we will also required in game development resources on the downloaded file, you can download after compiler operation, to see the results.
1. Top containers
What is the top containers? When we use graphical programming Java, where plans drawn? We need to provide a graphic containers, the containers are called top-level containers, and you can imagine it as a window. Top container is the foundation for graphical programming, and all graphical things will inevitably included in the top container. In Swing, we have the top three can be used in containers, they are:
JFrame: similar to the Windows operating system used to design window in the form of applications.
JDialog: JFrame and similar, but JDialog is used to design the dialog box.
JApplet: design can be used in embedded in the Web page Java applets.
If you need to use a window of Swing production processes, we should be the code looks like this:
Import javax.swing .*; Public class KyodaiUI (Extends JFrame …… )
2. Control
Control is an Application Program Interface of the basic elements, buttons, text boxes, such as the progress of these controls are. Controls (here we only discuss visualization Control) containers can be divided into control and non-control containers. From the literal meaning of understanding, containers can contain other controls that controls the special controls, for example, in Java JPanel controls on the type of vessel control, we can JPanel placed buttons, text boxes, and other non-container control , you can even further in the JPanel placed several JPanel Control (It is worth noting that the top container-type containers also controls every window in the application and there can be only one top containers controls, in other words , the top containers could not be included in the other controls).
Java containers in a lot of controls, in addition to the JPanel just mentioned, there are JTabbedPane, JScrollPane, a non-container control JButton, JLabel, such as JTextField. If you need to control a certain type of containers to add controls, you can use the add (Component comp) method to achieve, such as:
JPanel panel = new JPanel (); JButton button = new JButton (); Panel.add (button);
3. Layout
What is the layout? Java is the layout of controls are used to control the location of an interface management system. The use of other visual programming language Java in the initial contact interface design, always feel very uncomfortable Java interface design: there were no controls to provide WYSIWYG settings coordinate method! However, facts have proved that the layout of Java itself provide the same management system can be successfully fulfilled our needs, but also in cross-platform performance when there are more advantages.
The layout of commonly used are:
BorderLayout: interface will be divided into upper and lower middle, as well as about a regional management system, in BorderLayout layout, the most you can only put five controls, if more than five controls, the proposed distribution or use other systems it.
GridLayout: GridLayout user interface is the same cutting board for the distribution management system. If we are to design a similar built-in calculator in Windows software, GridLayout is undoubtedly the best option.
FlowLayout: FlowLayout layout with the above-mentioned two types of management systems do not, as in FlowLayout, you do not have to specify on which each control, you need only to control into FlowLayout, FlowLayout will, in accordance with you to add controls Controls placed the order, if the space is insufficient, will be automatically newline.
In the layout of this management system has several basic understanding, we have to design an interface to enter it. QQ in the careful observation of the game "Lianliankan" settings, we can be found, the entire interface is divided into three zones, is the top menu system, the area is the largest user games, in addition to a user Interactive areas, in each region by the number of control components.
So many controls, where we start with the beginning? The containers can be placed in the control of other controls, therefore, we have only to make sure the containers placed controls on it. Since it has been aware of the need to control the number of containers used, let us enter the next distribution management system. With GridLayout? Seems to be some reluctance by FlowLayout? There are better options? Right, I think you have thought of is BorderLayout bar, as shown in Figure 2.
Before hands, we must pay attention to is that the interface design must consider good size, is the main program interface regardless of the size or the size of each region, in the absence of good design appropriate size, with future changes will be very painful.
Below is the corresponding source:
Import java.awt .*; Import javax.swing .*; Public class KyodaiUI extends JFrame ( Public KyodaiUI () ( This.setSize (780, 500) / / set to form the size of 780 * 500 This.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); This.setResizable (false); / / size of the form can not be changed This.setTitle ( "Lianliankan"); / / Set Title JPanel toolBar = new JPanel (); ToolBar.setBackground (Color.white); ToolBar.setPreferredSize (new Dimension (780, 48)); JPanel actionPanel = new JPanel (); / / JPanel new type of control ActionPanel.setBackground (Color.yellow); / / Set the background color ActionPanel.setPreferredSize (new Dimension (160, 380)); / / size settings JPanel contentPanel = new JPanel (); ContentPanel.setBackground (Color.blue); ContentPanel.setPreferredSize (new Dimension (620, 380)); This.getContentPane (). Add (toolBar, BorderLayout.NORTH); This.getContentPane (). Add (actionPanel, BorderLayout.EAST); This.getContentPane (). Add (contentPanel, BorderLayout.CENTER); ) Public static void main (String [] args) throws HeadlessException ( KyodaiUI kyodaiUI = new KyodaiUI (); KyodaiUI.show (); ) )
Let us look at the above is how this process operates. First of all, this extends JFrame that is inherited from the JFrame, JFrame top container is the most basic controls. In fact, in the JDK, beginning with the letter J controls are Swing controls. And then set up a container attributes, including setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) is used to tell the Java Virtual Machine, when users click on the upper right corner of the form "off" button, the process of closing the window. If we do not do so, you will find that although you can be dispatched window closed, but did not withdraw from the process. In the next code, we added three top containers Panel containers. It should be noted that in the AWT, we can write directly to add (toolBar, BorderLayout.NORTH), and it must be in the Swing wrote getContentPane (). Add (toolBar, BorderLayout.NORTH), otherwise the process will be wrong.
Now we can look at the operation on the compiler, and I was not running the same as (see Figure 3)?
4. Borders
Although we use different Jianjingse to distinguish between different regions, but did not layered with beautiful borders will be many.
In Java, all J beginning of the Swing controls can be used for setBorder ways to set up their own borders. There are many types of borders, linear, convex, Waxia, air, and you can even free combination formed personal style. All Border javax.swing.BorderFactory must be provided in the use of the static method to create, for example:
Border border = BorderFactory.createBevelBorder (BevelBorder.LOWERED, New Color (45, 92, 162), New Color (43, 66, 97), New Color (45, 92, 162), New Color (84, 123, 200));
Now, we will toolBar.setBackground (Color.white) to toolBar.setBorder (border), the three-dimensional effect is not there have been?
Actual combat - write their own name
Now we have a functioning interface, although it do anything, but please Biehuang, Rome was not built in one day.
Let us now in the area to provide a menu "on the" menu, the procedures used to display information, can you do not want to let others know your name? Swing itself provides a ready JButton button control, we only need to create a new button: JButton about = new JButton ( ""); how this button into the menu area and not elsewhere? We can join the following code: toolBar.add (about); Yi, how push of a button does not respond? This is because you have not told the procedures to be done at the click of a button is what happened. Add the button to respond to the incident, first of all, need to use about.addActionListener (this) to tell procedures eavesdropping button pressed the incident, due ActionListener is a procedural interface Therefore, we stated in the category have to do a bit of local small Laws: public class KyodaiUI extends JFrame implements ActionListener {…} achieve ActionListener interface to tell the procedures I have to carry out the deal with the incident. Of course, we must add the final response to the incident code:
Public void actionPerformed (ActionEvent e) ( If (e.getSource () == about) ( JOptionPane.showMessageDialog (this, "My name", "on", JOptionPane.INFORMATION_MESSAGE); Return; ) )
Among them, e.getSource () that controls the current trigger events, as we often have procedures in a number of the above controls, these controls are likely to produce the event, we must use this method to find an issues Control.
Summary
Let us together look at the content of today: First, we know the top-level containers, know that the control is divided into control and non-container vessel control, but also noted that the use of frames, finally, we also deal with minor a touch of a button events.
When learning of the school and not between also said that, let me leave small operations to help consolidate what we have learned today: Add button above us in the middle of the menu bar is not handsome, please put Try the right or left.
Next: Java Swing with me in the game design (2)
Remember "plays an activist miner" as in the Wizard shuttle traffic in Hollywood in the Minicooper? Makewoerbage and Shali Sialon is driving its enemies under the nose removed 10 million worth of gold. However, if one can not now Minicooper appearances on the Mercedes-Benz in front of you, how would you treat it? It is the same ease of migration wizard? Today, let us point to 1.1 for这辆Minicooper parts on the assembly and let it run up.
Foreword
Starting from this issue, we provide you with complete source code of the game (click to download). Java cafe advocacy we both theory and practice, we will introduce series of key technologies and the realization of ideas, and friends, read the article with their own source code, like the side of a cup of coffee while reading newspapers, and this is never drops of aromatic Italy do.
Game layout
"Lianliankan" is a two-dimensional Zhanji games, it is necessary to design the chessboard of the game, should be GridLayout Mr Chong. Now let us look at a GridLayout to the constructor function:
GridLayout (): the default case, the layout of the region into the size of 1 * 1
GridLayout (int rows, int cols): designation of the regional distribution of horizontal and vertical grid of
GridLayout (int rows, int cols, int hgap, int vgap): Ditto, and also designated each lattice spacing between the horizontal and vertical spacing vgap hgap
Do not let the three million constructor function deterred you to the fact, as long as you like, can rest assured bold use of any one of which, if not carefully used "wrong", also after adjustment approach. Only need to pay attention to that, in addition GridLayout control, the default order is from the upper left to lower right were added.
Let us now to determine the number of games lattice. Lattice how many more appropriate? Too little will reduce the difficulty of the game, too much will cause visual impact. Therefore, we should, through a constant for the future even if changes are Jushouzhilao.
In Java, the constant need for the definition of public final static written in the form of the game if we stipulate that the board has eight in the horizontal grid, there are also eight vertical lattice, then we should take this definition:
Public final static int ROW = 8; Public final static int COLUMN = 8;
Then, we use the second constructor function GridLayout to create layout:
GridLayout gridLayout = new GridLayout (ROW, COLUMN);
Finally, we also need to play area (contentPanel) to the layout of the layout:
ContentPanel.setLayout (gridLayout);
If you compile and run a program at this time, you may be surprised: Interface how there had not been any change, which is not wrong? Although we designated the layout, but also did not add any controls, of course, to see changes. Let us together in the layout on the Add button bar:
For (int i = 0; i <ROW * COLUMN; i + +) ( JButton button = new JButton ( "Kyodai"); ContentPanel.add (button); )
Try to run a program, and I was not the same (see Figure 1)?
Using make a fuss about JButton
JButton is a button control, it is common in Swing are not ordinary longer controls, nevertheless, we still need to spend some effort to understand and use it, because when you can skillfully use JButton, you will find that other Swing Control is also so similar.
If you have written operating procedures used, you will find: the game is always a very full button, and it is very real inconvenience to the operation of the game, so we have to find ways to let out some air lattice. GridLayout layout of what is good, adding that the controls when not skip a certain lattice, Yanxiage how do?
In fact, this will not be difficult, since GridLayout from Skip, if we allow the addition of a lattice GridLayout layout of the controls and the integration background, so that the visual reach a consensus on the results. In addition, if people accidentally click on this lattice, the button still will be reversed and we have to try to not let the button is clicked, and this requires the use JButton setEnabled () method. Finally, can click on the button, and when they are clicked, we need to distinguish between what is out which button was clicked on.
In the last to achieve the "on" function, we used the e.getSource () method to determine your mouse, click on the source of the incident, however. That good name has been on the controls more effective. Here, the use of an array of buttons that is the best way to, first of all, let us amend the above code:
JButton [] = new JButton dots [ROW * COLUMN]; For (int i = 0; i <ROW * COLUMN; i + +) ( Dots [i] = new JButton ( "Kyodai"); Dots [i]. SetActionCommand ( "" + i); ContentPanel.add (dots [i]); Dots [i]. AddActionListener (this); )
Do not forget to write in the circle of dots on the [i] = new JButton ( "Kyodai"), although in the previous definition, the use of a group of dots, but it is only just told procedures we need to use some of JButton, but these JButton but still have not been initialized. At the same time, we not only use setActionCommand () for the development of the incident button name, also used the addActionListener () method for each button with the incident response handling.
On the incident response code, we can in the original actionPerformed () code inserted after the incident:
If (e.getSource () instanceof JButton) ( JButton button = (JButton) e.getSource (); Int offset = Integer.parseInt (button.getActionCommand ()); Int row, col; Row = Math.round (offset / COLUMN); Col = offset - row * COLUMN; JOptionPane.showMessageDialog (this, "ROW =" + + row, "COL =" + Col, "button", JOptionPane.INFORMATION_MESSAGE); )
In the above code, e.getSource () instanceof JButton used to determine whether the incident is JButton the type of control, and then the source will produce the event-type controls to mandatory conversion, re-use Integer.parseInt (button.getActionCommand ()) method to obtain the name of the incident into integer, as the code will make the trip and the integer reduction in the information.
Well, operational procedures, and then click each button to see whether there will be any of the dialog box as pictured?
Attention Oh, our next objective is to start from zero.
Swing in the use of picture
At present we have solved the problem of the user operation. To handsome interface, we need to use the picture to replace text. Have the time and patience of friends can do their own personalized picture, but should pay attention to each picture the same size, otherwise difficult Kanla. Think it can be easy to use packages downloaded directly in the picture.
In Swing, you can use setIcon (Image image) method to set up JButton picture, which is that the parameters of image we want to set the picture object, and this object can be a number of ways:
Use Toolkit class to be:
Image = Toolkit.getDefaultToolkit (). GetImage (url);
Use ImageIcon class getImage () method to obtain:
Image = new ImageIcon (getClass (). GetResource (filename)). GetImage ();
Here we use the first method. In order to facilitate future access to the Image object again, we can write this as a function:
Image getImage (String filename) ( URLClassLoader urlLoader = (URLClassLoader) this.getClass (). GetClassLoader (); URL url = null; Image image = null; Url = urlLoader.findResource (filename); Image = Toolkit.getDefaultToolkit (). GetImage (url); Return image; )
With this function, the picture later on to use more convenient, is not it?
Picture now have, then we would be in the source code package Map.Java map information in the form of performance using picture out. Because this section of the game is code algorithm code, it is no longer listed code, and here is broadly explain how specific do! In Map.Java, we used two-dimensional array map [] [] to preserve picture information, and we also use the one-dimensional images [] array to preserve a picture of each object, a map of each element are have a value, this value has not only shown that in the game interface buttons corresponding value, this button also shows that the use of images in the picture [] array of numbers, it is running pretty many interface.
Summary
Today, we introduced the Swing of JButton controls. For most Swing controls, the use of JButton can copy the past. Do not underestimate this JButton, when you can grasp it very well when you have the Swing on the foundation of the upgrade to a higher level. In addition, we also learned in Java loading image files are two methods. Finally, we will be part of the contents of the above two together and created a beautiful interface of the game. Although I am not here to write integrity of the code, but I believe that the reference to the source, through its own efforts, we can achieve our goals. If they can not solve the problems, you can contact me leftmoon@163.com Box
↑ Back
Windows system tray icon Practice (Swing)
Abstract: Windows system tray icon Practice (Swing)
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="675" border="0"> <tr> <td width = " 493 "> Below is the same case with trayicon-1.7.9b, Swing tray icon interface features, please refer to the source code examples.
Look at the "Hello World!" Procedures:
Import java.awt .*;
Import javax.swing .*;
Import java.awt.event .*;
Public class TrayIconTest extends JFrame (
JLabel lab = new JLabel ( "Hello World !!!");
Public TrayIconTest () (
GetContentPane (). Add (lab);
SetSize (400,300);
AddWindowListener (new MywindowListener ());
)
(Class MywindowListener extends WindowAdapter
Public void windowClosing (WindowEvent e) (
System.exit (0);
)
)
Public static void main (String [] args) (
TrayIconTest test = new TrayIconTest ();
Test.show ();
)
)
Below are added tray icon after the procedure (to use the run-time images, such as packet please download my folder,
Procedures for reference purposes only):
Import java.awt .*;
Import java.awt.event .*;
Import java.io. *;
Import javax.swing .*;
Import javax.swing.border .*;
Import com.jeans.trayicon .*; </ td> <td width="172" valign="top"> </ td> </ tr> </ table>
/ / Demo app for Java Tray Icon
Public class SwingTrayIcon extends JFrame (
Protected WindowsTrayIcon icon;
JLabel lab = new JLabel ( "Hello World !!!");
Public SwingTrayIcon () throws TrayIconException, InterruptedException (
Super ( "SwingTrayIcon");
WindowsTrayIcon.setWindowsMessageCallback (new WindowsMessageCallback ());
SetIconImage (loadImage ( "Duke16.gif"));
GetContentPane (). Add (lab);
Image france = loadImage ( "Duke16.gif"); / / loading image
Icon = new WindowsTrayIcon (france, 16, 16) / / tray icon
Icon.setToolTipText ( "Hello ");// care settings icon tool tips
Icon.setPopup (makePopup ());// to the tray icon and pop-up menus
TestMouseListener mouse = new TestMouseListener ();
Icon.addMouseListener (mouse); / / Double-click the tray icon moves
Icon.setVisible (true); / / enable tray icon visible.
WindowsTrayIcon.keepAlive ();
AddWindowListener (new WindowClosingListener ());// point window closed window button hidden
Pack ();
)
Public TrayIconPopup makePopup () (/ / pop-up menu structure
TrayIconPopup popup = new TrayIconPopup ();
TrayIconPopupSimpleItem item = new TrayIconPopupSimpleItem ( "& Show");
Item.setDefault (true);
/ / Each menu item can have it's own ActionListener
Item.addActionListener (new RestoreListener ());
Popup.addMenuItem (item);
Item = new TrayIconPopupSimpleItem ( "& About");
Item.addActionListener (new AboutListener ());
Popup.addMenuItem (item);
Popup.addMenuItem (new TrayIconPopupSeparator ());
/ / Add exit item
Item = new TrayIconPopupSimpleItem ( "E & xit");
Item.addActionListener (new ExitListener ());
Popup.addMenuItem (item);
Return popup;
)
/ / Load a gif image (used for loading the 16×16 icon gifs)
Public static Image loadImage (String fileName) (
Return Toolkit.getDefaultToolkit (). GetImage ( "demo" File.separator + + "images" + + File.separator fileName);
)
/ / Use native windows look & feel
Public static void setLookAndFeel () (
Try (
UIManager.setLookAndFeel ( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
) Catch (Exception ex) ()
)
/ / Main function
Public static void main (String [] args) (
Try (
SetLookAndFeel ();
TR.load ( "demo" File.separator + + "swing" File.separator + + "menu.eng");
String appName = "SwingTray";
WindowsTrayIcon.sendWindowsMessage long result = (appName, 1234);
If (result! = -1) (
System.out.println ( "[Already running other instance of" appName + + "(returns:" + result +")].");
Return;
)
/ / Init the Tray Icon library given the name for the hidden window
WindowsTrayIcon.initTrayIcon (appName);
SwingTrayIcon tray = new SwingTrayIcon ();
SwingTrayIcon.centerDialog (tray);
Tray.setSize (400,300);
Tray.setVisible (true);
) Catch (TrayIconException e) (
System.out.println ( "Error:" + e.getMessage ());
) Catch (IOException e) (
System.out.println ( "Error:" + e.getMessage ());
) Catch (InterruptedException e) ()
)
/ / Screen in the dialog box
Public static void centerDialog (Window frame) (
Dimension dialogSize = frame.getSize ();
Dimension screenSize = Toolkit.getDefaultToolkit (). GetScreenSize ();
Frame.setLocation (screenSize.width / 2 - dialogSize.width / 2,
ScreenSize.height / 2 - dialogSize.height / 2);
)
Private class WindowsMessageCallback implements TrayIconCallback (
Public int callback (int param) (
System.out.println ( "[Other instance started (parameter:" + param +")].");
SetVisible (true); toFront (); requestFocus ();
/ / Return integer value to other process
Return 4321;
)
)
Private class ExitListener implements ActionListener (
Public void actionPerformed (ActionEvent evt) (
DoExit ();
)
)
Public class WindowClosingListener extends WindowAdapter (/ / hide window
Public void windowClosing (WindowEvent e) (
SetVisible (false);
)
)
Public void doExit () (
WindowsTrayIcon.cleanUp ();
System.exit (0);
)
/ / Callback listener handles about button
Private class AboutListener implements ActionListener (
Public void actionPerformed (ActionEvent evt) (
System.out.println ( "[About selected ].");
/ / TestTrayIcon.this instead of this $ 0 for Java 1.3 compatibility
AboutBox box = new AboutBox (SwingTrayIcon.this);
CenterDialog (box);
Box.setVisible (true);
)
)
/ / Callback listener handles restore (click left on any icon / show popup menu)
Private class RestoreListener implements ActionListener (
Public void actionPerformed (ActionEvent evt) (
SetVisible (true);
ToFront (); requestFocus ();
)
)
/ / Mouse double-click events
Public class TestMouseListener extends MouseAdapter (
Public void mousePressed (MouseEvent evt) (
If ((evt.getModifiers () & MouseEvent.BUTTON1_MASK)! = 0 & & evt.getClickCount () == 2) (
SetVisible (true);
)
)
)
)
/ / Stupid about box for demo app
(Class AboutBox extends JDialog
/ / Create new about box given parent frame
Public AboutBox (JFrame parent) (
/ / Make modal dialog given parent and title
Super (parent, "About TrayIcon", true);
/ / Layout stuff
JPanel panel = new JPanel ();
Panel.setLayout (new BorderLayout (3,3));
JPanel txt = new JPanel ();
Txt.setLayout (new GridLayout (0,1));
Txt.add (new JLabel ( "TrayIcon version:" + WindowsTrayIcon.TRAY_VERSION));
Txt.add (new JLabel ( "OS version:" + WindowsTrayIcon.getWindowsVersionString ()));
Txt.add (new JLabel ( "Written by Jan Struyf
Panel.add (txt, BorderLayout.CENTER);
JPanel buttons = new JPanel ();
Buttons.setLayout (new FlowLayout ());
JButton button = new JButton ( "OK");
Buttons.add (button, BorderLayout.CENTER);
Panel.add (buttons, BorderLayout.SOUTH);
/ / Close listeners for OK button and window button
Button.addActionListener (new CloseListener ());
AddWindowListener (new CloseWindowListener ());
Panel.setBorder (new EmptyBorder (4,4,4,4));
SetContentPane (panel);
Pack ();
)
Private class CloseListener implements ActionListener (
Public void actionPerformed (ActionEvent evt) (
Dispose ();
)
)
/ / Close listener for windows button
Private class CloseWindowListener extends WindowAdapter (
Public void windowClosing (WindowEvent evt) (
Dispose ();
)
)
)
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back
Swing timer used to achieve data regularly updated Jtable
Abstract: Swing timer data updated regularly achieve Jtable
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="282" height="86" align="center" valign="top"> </ td> <td width="402" valign="top">
Program is divided into three parts, the main program categories SuperTable.java, the framework of SuperTableFrame.java, data template SuperTableModel.java category.
SuperTable.java main program categories, as follows:
Package supertable.swing;
Import javax.swing .*;
(Public class SuperTable
Public static void main (String [] args) (
JFrame frame = new SuperTableFrame ();
Frame.show ();
)
)
</ Td> </ tr> </ table>
SuperTableFrame.java framework category, as follows:
Package supertable.swing;
Import java.awt.Container;
Import java.awt.event.ActionEvent;
Import java.awt.event.ActionListener;
Import java.awt.event.WindowAdapter;
Import java.awt.event.WindowEvent;
Import javax.swing.JButton;
Import javax.swing.JFrame;
Import javax.swing.JPanel;
Import javax.swing.JScrollPane;
Import javax.swing.JTable;
Import javax.swing.table.TableModel;
Import javax.swing.Action;
Import javax.swing.AbstractAction;
Import javax.swing.Timer;
/ *
* Date created 2005-3-21
* /
/ **
* @ Author Administrator
*
* /
Public class SuperTableFrame extends JFrame (
Private JTable table = null;
Private Timer timer = null;
Public SuperTableFrame () (
Timer = new Timer (300, updateTableAction);
SetTitle ( "SuperTable");
SetSize (300,200);
AddWindowListener (new WindowAdapter () (
Public void windowClosing (WindowEvent e) (
System.exit (0);
)
));
TableModel model = new SuperTableModel (30,5,10);
Table = new JTable (model);
JPanel p = new JPanel ();
AddButton (p, "Update", the new ActionListener () (
Public void actionPerformed (ActionEvent evt) (
Table.validate ();
Table.updateUI ();
)
));
AddButton (p, "Start", the new ActionListener () (
Public void actionPerformed (ActionEvent evt) (
Timer.start ();
)
));
AddButton (p, "Stop", the new ActionListener () (
Public void actionPerformed (ActionEvent evt) (
Timer.stop ();
)
));
Container contentPane = getContentPane ();
ContentPane.add (new JScrollPane (table), "Center");
ContentPane.add (p, "South");
)
Public void addButton (Container c, String title, ActionListener a) (
JButton b = new JButton (title);
C.add (b);
B.addActionListener (a);
)
Private Action updateTableAction = new AbstractAction () (
Public void actionPerformed (ActionEvent e) (
Table.validate ();
Table.updateUI ();
)
);
)
SuperTableModel.java template data types, as follows:
Package supertable.swing;
Import java.text.NumberFormat;
Import javax.swing.table.AbstractTableModel;
Public class SuperTableModel extends AbstractTableModel (
Private int years;
Private int minRate;
Private int maxRate;
Private static final double INITAL_BALANCE = 100000.0;
Public SuperTableModel (int y, int r1, int r2) (
Years = y;
MinRate = r1;
MaxRate r2 =;
)
Public int getRowCount () (
Return years;
)
Public int getColumnCount () (
Return maxRate-minRate +1;
)
Public Object getValueAt (int r, int c) (
/ / Double rate = (c + minRate) / 100.0;
/ / Int nperiods = r;
/ / * Double futureBalance INITAL_BALANCE Math.pow = (1 + rate, nperiods);
Double rate = Math.random ();
Return NumberFormat.getCurrencyInstance (). Format (rate);
)
Public String getColumnName (int c) (
Double rate = (c + minRate) / 100.0;
Return NumberFormat.getPercentInstance (). Format (rate);
)
)
Graph:
</ Td> </ tr> <tr> ↑ Back
Swing layout management - OverlayLayout
Abstract: Swing layout management - OverlayLayout
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="282" height="86" align="center" valign="top"> </ td> <td width="402" valign="top">
OverlayLayout are overlapping components for the layout manager. It is the use of some alignment of the components some point benchmarks placed in the layout of the stacked containers.
The horizontal and vertical axis components of the alignment between 0.0 and 1.0 points between. The horizontal axis (X-axis) on behalf of 0.0 components on the left side of face, 1.0 representatives of the right components; longitudinal axis (Y axis), 0.0 and 1.0 respectively on behalf of the components top and bottom.
Constructor function
Public OverlayLayout (Container target)
Because constructor function will not target object installation results layout manager, we must also call setLayout () to accomplish this function.
</ Td> </ tr> </ table>
JPanel p1 = new JPanel ();
OverlayLayout overlay = new OverlayLayout (p1);
P1.setLayout (overlay);
In OverlayLayout layout manager, each component has a horizontal longitudinal coordinates, only the location of each component and its own longitudinal coordinates of the horizontal, in other words component to his own position as the benchmark, 0.0 and 1.0 on the horizontal axis representing components of the left and right side; 0.0 and 1.0 on the vertical axis representing the top and bottom parts, and containers position-independent. If a component alignmentX attribute set to 0.5, the left side of the original location corresponding 0.0, a 0.5, then the location of components will now shift to the left of width / 2 the distance to the left of the location of the response now 0.0. The vertical axis itself, understand?
In order to easily understand our point of view, "Java Swing" on the section of the sample OverlayLayout procedures, it may be compiled operation. Figure, you can adjust the input box containers in the three buttons X, Y-axis value of their containers in the position to change, to try, you can fully understand OverlayLayout.
/ / OverlayTest.java
/ / A test of the OverlayLayout manager allowing experimentation.
/ /
Import java.awt .*;
Import java.awt.event .*;
Import javax.swing .*;
Public class OverlayTest extends JFrame (
Public OverlayTest () (
Super ( "OverlayLayout Test");
SetSize (500, 300);
SetDefaultCloseOperation (EXIT_ON_CLOSE);
GetContentPane final Container c = ();
C.setLayout (new GridBagLayout ());
Final JPanel p1 = new GridPanel ();
Final OverlayLayout overlay = new OverlayLayout (p1);
P1.setLayout (overlay);
Final JButton jb1 = new JButton ( "B1");
Final JButton jb2 = new JButton ( "B2");
Final JButton jb3 = new JButton ( "B3");
Dimension b1 = new Dimension (60, 50);
Dimension b2 = new Dimension (80, 40);
Dimension b3 = new Dimension (100, 60);
Jb1.setMinimumSize (b1);
Jb1.setMaximumSize (b1);
Jb1.setPreferredSize (b1);
Jb2.setMinimumSize (b2);
Jb2.setMaximumSize (b2);
Jb2.setPreferredSize (b2);
Jb3.setMinimumSize (b3);
Jb3.setMaximumSize (b3);
Jb3.setPreferredSize (b3);
SimpleReporter reporter = new SimpleReporter ();
Jb1.addActionListener (reporter);
Jb2.addActionListener (reporter);
Jb3.addActionListener (reporter);
P1.add (jb1);
P1.add (jb2);
P1.add (jb3);
JPanel p2 = new JPanel ();
P2.setLayout (new GridLayout (2,6));
P2.add (new JLabel ( "B1 X" JLabel.CENTER));
P2.add (new JLabel ( "B1 Y", JLabel.CENTER));
P2.add (new JLabel ( "B2 X" JLabel.CENTER));
P2.add (new JLabel ( "B2 Y", JLabel.CENTER));
P2.add (new JLabel ( "B3 X" JLabel.CENTER));
P2.add (new JLabel ( "B3 Y", JLabel.CENTER));
P2.add (new JLabel (""));
Final JTextField x1 = new JTextField ( "0.0", 4); / / Button1 x alignment
Final JTextField y1 = new JTextField ( "0.0", 4); / / Button1 y alignment
Final JTextField x2 = new JTextField ( "0.0", 4);
Final JTextField y2 = new JTextField ( "0.0", 4);
Final JTextField x3 = new JTextField ( "0.0", 4);
Final JTextField y3 = new JTextField ( "0.0", 4);
P2.add (x1);
P2.add (y1);
P2.add (x2);
P2.add (y2);
P2.add (x3);
P2.add (y3);
GridBagConstraints constraints = new GridBagConstraints ();
C.add (p1, constraints);
Constraints.gridx = 1;
JButton updateButton = new JButton ( "Update");
UpdateButton.addActionListener (new ActionListener () (
Public void actionPerformed (ActionEvent ae) (
Jb1.setAlignmentX (
Float.valueOf (x1.getText (). Trim ()). FloatValue ());
Jb1.setAlignmentY (
Float.valueOf (y1.getText (). Trim ()). FloatValue ());
Jb2.setAlignmentX (
Float.valueOf (x2.getText (). Trim ()). FloatValue ());
Jb2.setAlignmentY (
Float.valueOf (y2.getText (). Trim ()). FloatValue ());
Jb3.setAlignmentX (
Float.valueOf (x3.getText (). Trim ()). FloatValue ());
Jb3.setAlignmentY (
Float.valueOf (y3.getText (). Trim ()). FloatValue ());
P1.revalidate ();
)
));
C.add (updateButton, constraints);
Constraints.gridx = 0;
Constraints.gridy = 1;
Constraints.gridwidth = 2;
C.add (p2, constraints);
)
Public static void main (String args []) (
OverlayTest ot = new OverlayTest ();
Ot.setVisible (true);
)
Public class SimpleReporter implements ActionListener (
Public void actionPerformed (ActionEvent ae) (
System.out.println (ae.getActionCommand ());
)
)
Public class GridPanel extends JPanel (
Public void paint (Graphics g) (
Super.paint (g);
Int w = getSize (). Width;
Int h = getSize (). Height;
G.setColor (Color.red);
G.drawRect (0,0, w-1 h-1);
G.drawLine (w / 2,0, w / 2, h);
G.drawLine (0, h / 2, w, h / 2);
)
)
)
Finally reminded, use OverlayLayout layout manager key to remember X, Y-axis position corresponding components, and containers does not matter. As long as aware of this point, or use a very simple and convenient, I used OverlayLayout layout manager clone a PhotoShop tools panel.
</ Td> </ tr> <tr>
↑ Back
Swing in the getContentPane () method
Abstract: The Swing getContentPane () method
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="271" height="86" align="center" valign="top"> </ td> <td width="413" valign="top"> in the past J2SE version of components (components) can not be directly added to the most senior (top level) Swing containers, these containers include: JFrame, JDialog, JWindow, JApplet and JInternalFrame. for example, there is now a JFrame instance of the named aFrame. We should add a named aComponent components (such as a JPanel) to the JFrame Lane. We need to call before the getContentPane JFrame () method. As follows:
AFrame.getContentPane (). Add (aComponent)
In J2SE5.0, we can add components directly to the most senior Swing containers, containers can be installed directly in the layout of Management (Layout Manager), and delete components. This change allows us to omit the call getContentPane () directly in the containers and the application of add (), setLayout () and remove (). However, we can not ignore the ContentPane, even if we may not be used to add components to ContentPane containers.
</ Td> </ tr> <tr> <td height="20" colspan="2">
We look at the past in a previous version J2SE1.4 and often applied to the case. We should set up a JFrame layout management and add some parts to the JFrame. Show api on JFrame document can be found, JFrame java.awt.Container inherited from the add () method. That add () is used to add a component to the JFrame containers. Container in the category also includes setLayout () method, the setLayout ( ) is used to set successor (such as the above JFrame containers) layout manager.
Here is a simple example:
Import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.GridLayout; import java.awt.Color; public class FrameTest extends JFrame (/ / attention to the previous version 1.4 and can be compiled, but the problems run / / Version 5.0 operating normally FrameTest () (super (the "Test"); setBackground (Color.BLACK); setLayout (new GridLayout (6,6,2,2)); / / 1.4 of a problem for (int i = 0; i <36; i + +) (JPanel jPanel = new JPanel (); jPanel.setBackground (new Color ((int) (Math.random () * 16777215))); add (jPanel); / / 1.4 in question 2 ) setSize (400400); setVisible (true);) public static void main (String [] args) (new FrameTest ();))
Output of all:
Then we note that the above output JFrame background color is not black but white, that is to say above setBackground (Color.BLACK) compiled after the JFrame the background color and not be displayed, if the background color is black JFrame — - grid between black color also need to call getContentPane (),
GetContentPane (). SetBackground (Color.BLACK);
As in the following output:
Details of the new version of the swing operation, visit sun java forum for … </ td> </ tr> </ table> function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document.getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td > </ tr> <tr>
↑ Back
Use Java Swing create an XML Editor
Abstract: Java Swing create an XML Editor
: From: yesky
I think you must understand the XML, you may now also eager to write XML text of this section, but can now find the cross-platform, a free XML Editor too little. Therefore, in this paper, I would like to brief you or take you step-by-step development of a simple XML editor, of course, we should use some of the most common components of the Java 2 Swing, but these are free, some are JDK in, and some can be downloaded from the Internet. I think through this, you can create one of your own XML editor.
Let me brief you on the idea of writing this series. First of all, I would like to briefly discuss why XML and tree structure more suitable to display XML, and then we look at the JAXP API how to build up the necessary XML type environment, then we will learn to display a graphical tree JTree Swing components; Finally, we will create a succession JTree component of the class can be reused, can be used to analyze an XML document, and the data show that in a Jtree.
As XML (eXtensible Markup Languge), people tended to it as a new Web browser for the markup language, the same as HTML or CSS. In fact, XML is a data representation language, which lets you use a very effective way to describe your data. XML enables you to define such as "these three words constitutes a heading" such statements. XML allows you to declare any type of data, rather than for the data shown in these pages.
Please take a look at the following examples of XML:
<article>
<header>
<title> Use Java Swing create an XML Editor <subtitle> first part of </ subtitle>
</ Title>
<author> Wayne </ author>
<header>
This is the text <content> </ content>
</ Article>
Please note that these elements and the standard HTML language is different, but they look more like HTML, it is because HTML and XML language comes from SGML. The difference is that HTML tags are pre-defined set of XML syntax, and many of flexibility, it allows you to use the name of the table labeled as <author> to include data on both sides. You should pay attention to, all the elements are subordinate to the root element (in the case of <article "), there is some element of their elements, such as is <subtitle> <title> sub-elements. Such data organization has three advantages: Table intended to be more data, data and more easily protect data more easily, as a tree structure shown, and this is why we object to the use of JTree XML data show why. If you would like to have a deeper understanding of XML, please refer to the relevant天æžonline tutorial.
JAXP is used with XML, Java API, which enables analysis and applications into XML documents, and its function somewhat like JDBC API are to function as a function of the abstract methods. Apache web site you can go to find the latest Xerces parser, which contains the latest JAXP, downloaded after you put it in the category directory.
Let us look at how to use JTree Swing components.
We all know that in nature, a tree usually have a very thick tree trunks, there are many tree branches bifurcation. Each tree and the tree forking forking the link between a certain, because they have the same source: the trunk. This inheritance relationship is not only in branches in the human lineage also follow the same rule. From their parents, to their children and to their children's children, it is so far until countless. Similarly, in data storage, is the concept of a tree using the same method as human genealogical tree stored data. Each tree as a tree forking nodes, each node of a parent node called nodes, all the nodes of the public called the root node is the father. JTree component of a tree is a simple data structure visualization manifestations.
Almost all the XML Editor includes a visualization of the tree structure, and allow you to edit an XML document elements. We will soon build a editor, but in the meantime, let us find out JTree component. A node in a tree somewhere storage of the data, in order to store data, we must know that any one of them the father of nodes and nodes. Javax.swing.tree package some very useful definition of the interface, providing a common method of constructing and operating a tree structure.
TreeNode method used to access the node tree information
MutableTreeNode methods used in a variable tree (to add or delete sub-nodes)
TreeModel methods for the creation and management of trees and related data model.
Next, we will build a successor JTree class, providing analysis and the use of XML documents JTree component of the visualization nodes displayed function.
XTree create components
XTree category by a constructor function and composition of the three methods, for the sake of simplicity we can only build a Xtree components in the creation of a good tree can not be dealing with it after the node. Let us look at a below this category.
Domain:
Private DefaultMutableTreeNode treeNode members of this variable storage TreeNode objects for storage JTree model.
Javax.swing.tree DefaultMutableTreeNode category, which is defined in the default interface provides a realization of MutableTreeNode.
Private DocumentBuilderFactory dbf
Private DocumentBuilder db
Private Document doc members of the three variables is part of JAXP to analyze text and translated into XML DOM (Document Object Model) objects.
Constructor function
Public XTree (String text)
This constructor function through the use of transmission to the constructor to create a version of XML XTree object. Initialized in some categories and with the JTree ultra-DOM object analysis shows that the basic attributes, the constructor function generates a TreeModel object to create an actual visual tree. By DOM objects sent to createTreeNode () method to create a root node, createTreeNode () method returns a DefaultMutableTreeNode type of object. This object is then used to create tree TreeModel.
Methods
Private DefaultMutableTreeNode createTreeNode (Node root)
This method using a DOM node, and then sub-node recursive until all have been added to the contact in DefaultMutableTreeNode. This is a recursive method, in order to find the root of each sub-nodes, which each have their own call. JTree then DefaultMutableTreeNode object can be used, because it is a tree.
Private String getNodeType (Node node)
This method was createTreeNode () linked to a string and a type of node.
Private Node parseXml ()
This method is used to analyze XML text string, it returned to the Node type of object can be transferred to createTreeNode () method.
Below I give the java code for your analysis and study.
/ / To all of the W3C's DOM
Import org.w3c.dom .*;
/ / JAXP for DOM I / O type
Import javax.xml.parsers .*;
/ / Standard Java class
Import javax.swing .*;
Import javax.swing.tree .*;
Import javax.swing.event .*;
Import java.awt .*;
Import java.awt.event .*;
Import java.io. *;
Public class XTree extends JTree
(
/ **
* The members of variables stored TreeNode objects for storage JTree model.
* DefaultMutableTreeNode category, which is defined in the javax.swing.tree
* The default interface provides a realization of MutableTreeNode.
* /
Private DefaultMutableTreeNode treeNode;
/ **
* This is JAXP three members of the variable part is used to analyze text and translated into XML DOM (Document Object Model) objects.
* /
Private DocumentBuilderFactory dbf;
Private DocumentBuilder db;
Private Document doc;
/ **
* This constructor function through the use of transmission to the constructor to create a version of XML object XTree
* @ Parameter is the text of an XML format text XML
* @ ParserConfigurationException If abnormal function of the non-normal tectonic settings analyzer, it will throw an error
* /
Public XTree (String text) throws ParserConfigurationException
(
Super ();
/ / Set up the basic attributes Tree exaggerated
GetSelectionModel (). SetSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
SetShowsRootHandles (true);
SetEditable (false); / / allow the tree can edit
/ / Initialization through the DOM object to the analysis
Dbf = DocumentBuilderFactory.newInstance ();
Dbf.setValidating (false);
Db = dbf.newDocumentBuilder ();
/ / Use DOM root and turn it into a model JTree tree
TreeNode = createTreeNode (parseXml (text));
SetModel (new DefaultTreeModel (treeNode));
) File: / / suspension XTree ()
/ **
* This method of using a DOM node, and then sub-node recursive until all have been added to the contact in DefaultMutableTreeNode.
* This is a recursive method, in order to find the root of each sub-nodes, which each have their own call.
* JTree then DefaultMutableTreeNode object can be used, because it is a tree.
*
* @ Parameters root org.w3c.Node.Node
*
* @ Return value to return to a target based on the root DefaultMutableTreeNode
* /
Private DefaultMutableTreeNode createTreeNode (Node root)
(
DefaultMutableTreeNode treeNode = null;
String type, name, value;
NamedNodeMap attribs;
Node attribNode;
/ / Data obtained from the root node
Type = getNodeType (root);
Name = root.getNodeName ();
Root.getNodeValue value = ();
TreeNode = new DefaultMutableTreeNode (root.getNodeType () == Node.TEXT_NODE? Value: name);
/ / Display Properties
Attribs = root.getAttributes ();
If (attribs! = Null)
(
For (int i = 0; i <attribs.getLength (); i + +)
(
AttribNode = attribs.item (i);
Name = attribNode.getNodeName (). Trim ();
AttribNode.getNodeValue value = (). Trim ();
If (value! = Null)
(
If (value.length ()> 0)
(
TreeNode.add (new DefaultMutableTreeNode ( "Attribute ->" + name + "= \" "+ value +" \ ""));
) File: / / end if (value.length ()> 0)
) File: / / end if (value! = Null)
) File: / / end for (int i = 0; i <attribs.getLength (); i + +)
) File: / / end if (attribs! = Null)
/ / If the existence of nodes, recursive
If (root.hasChildNodes ())
(
NodeList children;
Int numChildren;
Node node;
String data;
Root.getChildNodes children = ();
/ / If the nodes of the non-empty, only recursive
If (children! = Null)
(
NumChildren = children.getLength ();
For (int i = 0; i <numChildren; i + +)
(
Node = children.item (i);
If (node! = Null)
(
If (node.getNodeType () == Node.ELEMENT_NODE)
(
TreeNode.add (createTreeNode (node));
) File: / / end if (node.getNodeType () == Node.ELEMENT_NODE)
Data = node.getNodeValue ();
If (data! = Null)
(
Data.trim data = ();
If (! Data.equals ( "\ n") & &! Data.equals ( "\ r \ n") & & data.length ()> 0)
(
TreeNode.add (createTreeNode (node));
) File: / / end if (! Data.equals ( "\ n") & &! Data.equals ( "\ r \ n") & & data.length ()> 0)
) File: / / end if (data! = Null)
) File: / / end if (node! = Null)
) File: / / end for (int i = 0; i <numChildren; i + +)
) File: / / end if (children! = Null)
) File: / / end if (root.hasChildNodes ())
Return treeNode;
) File: / / end createTreeNode (Node root)
/ **
* This method was createTreeNode () linked to a string and a type of node.
*
* @ Parameter node org.w3c.Node.Node
*
* @ Return shows that the return value of the string node
* /
Private String getNodeType (Node node)
(
String type;
Switch (node.getNodeType ())
(
Case Node.ELEMENT_NODE:
(
Type = "Element";
Break;
)
Case Node.ATTRIBUTE_NODE:
(
Type = "Attribute";
Break;
)
Case Node.TEXT_NODE:
(
Type = "Text";
Break;
)
Case Node.CDATA_SECTION_NODE:
(
Type = "CData section";
Break;
)
Case Node.ENTITY_REFERENCE_NODE:
(
Type = "Entity reference";
Break;
)
Case Node.ENTITY_NODE:
(
Type = "Entity";
Break;
)
Case Node.PROCESSING_INSTRUCTION_NODE:
(
Type = "Processing instruction";
Break;
)
Case Node.COMMENT_NODE:
(
Type = "Comment";
Break;
)
Case Node.DOCUMENT_NODE:
(
Type = "Document";
Break;
)
Case Node.DOCUMENT_TYPE_NODE:
(
Type = "Document type";
Break;
)
Case Node.DOCUMENT_FRAGMENT_NODE:
(
Type = "Document fragment";
Break;
)
Case Node.NOTATION_NODE:
(
Type = "Notation";
Break;
)
Default:
(
Type = "???";
Break;
)
) / / End switch (node.getNodeType ())
Return type;
) File: / / End getNodeType ()
/ **
* This method is used to analyze XML text string, it returned to the Node type of object can be transferred to createTreeNode () method.
*
* @ Parameters of a text string XML documents show
* @ Return value to return to a target org.w3c.Node.Node
* /
Private Node parseXml (String text)
(
ByteArrayInputStream byteStream;
ByteStream = new ByteArrayInputStream (text.getBytes ());
Try
(
Doc = db.parse (byteStream);
)
Catch (Exception e)
(
E.printStackTrace ();
System.exit (0);
)
Return (Node) doc.getDocumentElement ();
) File: / / End parseXml ()
) File: / / end of class XTree
Code 2 XTreeTester.java
Import javax.xml.parsers .*;
/ / GUI category
Import javax.swing .*;
Import java.awt .*;
Import java.awt.event .*;
File: / / standard Java class
Import java.io. *;
Public class XTreeTester extends JFrame
(
/ / XTree object, used to display XML JTree
Private XTree xTree;
/ / JScrollPane is JTree containers
Private JScrollPane jScroll;
Private WindowListener winClosing;
/ / Set up the framework of a wide and high
Private static final int FRAME_WIDTH = 400;
Private static final int FRAME_HEIGHT = 300;
/ *
* Constructors construct a framework consists of JScrollPane,
* To a string of XML-based object XTree spread in the constructor function
* /
Public XTreeTester (String title, String xml) throws ParserConfigurationException
(
Super (title);
Toolkit toolkit;
Dimension dim, minimumSize;
Int screenHeight, screenWidth;
/ / Initialize the basic layout attributes
SetBackground (Color.lightGray);
GetContentPane (). SetLayout (new BorderLayout ());
Toolkit.getDefaultToolkit toolkit = ();
Toolkit.getScreenSize dim = ();
ScreenHeight = dim.height;
ScreenWidth = dim.width;
SetBounds ((screenWidth-FRAME_WIDTH) / 2, (screenHeight-FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
/ / Object Construction XTree
XTree = new XTree (xml);
File: / / Packaging to the XTree JScroll, JFrame could make it to the screen from top to bottom in the rolling.
JScroll = new JScrollPane ();
JScroll.getViewport (). Add (xTree);
/ / Add to the framework of the rolling
GetContentPane (). Add (jScroll, BorderLayout.CENTER);
Validate ();
SetVisible (true);
/ / Add WindowListener to Close Window
WinClosing = new WindowAdapter ()
(
Public void windowClosing (WindowEvent e)
(
Exit ();
)
);
AddWindowListener (winClosing);
)
/ / Beginning of the implementation process from here. Xml must be an extension of the XML document sent to this method, the format for java XTreeTester yourxmlfilename.xml
Public static void main (String [] args)
(
String fileName = "";
BufferedReader reader;
String line;
StringBuffer xmlText;
XTreeTester xTreeTester;
/ / Create an XML document based on specific Document Object
Try
(
If (args.length> 0)
(
FileName = args [0];
If (fileName.substring (fileName.indexOf ( '.')). Equals (. "Xml"))
(
Reader = new BufferedReader (new FileReader (fileName));
XmlText = new StringBuffer ();
While ((line = reader.readLine ())! = Null)
(
XmlText.append (line);
)
/ / End of Document Object document will be rewritten
Reader.close ();
/ / Construction GUI components
XTreeTester = new XTreeTester ( "XTree test" xmlText.toString ());
)
Else
(
Help ();
)
)
Else
(
Help ();
)
)
Catch (FileNotFoundException fnfEx)
(
System.out.println ( "not found" fileName + + "document.");
Exit ();
)
Catch (Exception ex)
(
Ex.printStackTrace ();
Exit ();
)
)
File: / / Help
Private static void help ()
(
System.out.println ( "\ n Method of Use: java XTreeTester yourxmlfilename.xml");
System.exit (0);
)
/ / Exit
Private static void exit ()
(
System.out.println ( "\ n Thank you use XTree");
System.exit (0);
)
)
Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd
↑ Back
My debut - Notepad program (with Swing achieve, incidental source code)
Abstract: My debut - Notepad program (with Swing achieve, incidental source code)
Content: the diary I wrote this procedure is the first feature complete the procedure is completely written out of the interest. Has been basically achieve a general diary should have some features, such as: preservation, find, Undo / Redo, such as change fonts.
In addition, in accordance with their own learning MVC design model of the knowledge acquired, procedures will be a certain degree of division, but also because the first time, a breakdown in the not too coherent, please apologize!
Following is the procedure I wrote:
Download File Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd the diary I wrote this procedure is the first feature complete the procedure is completely written out of the interest. Has been basically achieve a general diary should have some features, such as: preservation, find, Undo / Redo, such as change fonts.
In addition, in accordance with their own learning MVC design model of the knowledge acquired, procedures will be a certain degree of division, but also?
↑ Back
Java Swing authoritative guide: Spinner Model Controls
Abstract: Java Swing authoritative guide: Spinner Model Controls
:
Disclaimer: Matrix authorized access to any site, reprint, you must identify the form of hyperlinks to the original source and author of the article and the information statement Author: John Zukowski; glorywine
Original Address: http://www.javaworld.com/javaworld/jw-08-2005/jw-0829-jspinner.html
Chinese Address: http://www.matrix.org.cn/resource/article/44/44000_Java_Swing.html
Key words: Java Swing Spinner Model Controls
JSpinner to work is like JList or had been placed in the middle of a JComboBox JFormattedTextField. In the JList or JComboBox, users can set well in advance of the value to be imported. JSpinner also provide such a mechanism. Another part of this control is JFormattedTextField. How can not be imported and the control of the small grid control, such as JList. On the contrary, through JFormattedTextField to enter or through the edge of two small arrow can be used to browse different values.
Exhibit 1 shows the Spinner with different input type is what kind. Picture shows the top of the JSpinner 1 is a week to show French, through SpinnerListModel. The middle is a date of the show through SpinnerDateModel JSpinner. SpinnerNumberModel is at the bottom of the use of the JSpinner. Each is a way through their mysterious, in the back of this paper we will be learning.
Exhibit 1. JSpinner examples
To create and manipulate JSpinner, many categories will be called, the most important thing is JSpinner own. The most important of the two sets of prospective including SpinnerModel interface, including alternative set of options, and, JSpinner.DefaultEditor the realization used to capture all the options. Fortunately, many other calls are in the background of the work of, for example, once you provide to SpinnerNumberModel the scope of the figures, and use this category to assist Spinner, your work is actually completed.
Create controls JSpinner
JSpinner category includes two constructor to initialize control:
Public JSpinner ()
JSpinner spinner = new JSpinner ();
Public JSpinner (SpinnerModel model)
SpinnerModel model = new SpinnerListModel (args);
JSpinner spinner = new JSpinner (model);
At the beginning of the data model can not, it can be used to back track JSpinner method. Another method, in the creation of the control of the use of a complete model to achieve SpinnerModel interface, there are three specific categories of use: SpinnerDateModel, SpinnerListModel and SpinnerNumberModel, along with their father abstract category AbstractSpinnerModel. If not by name model, then SpinnerNumberModel will default. And display and edit controls is JFormattedTextField, edit, the basic function is through a series of internal JSpinner realized: DateEditor, ListEditor and NumberFormat, and the father category DefaultEditor support.
JSpinner attribute
In addition to creating a JSpinner object, you can also form one of the nine properties in a configuration to carry out.
Table 1. JSpinner attribute
Attribute value in the value of the current controls allow you to change the settings, and nextValue perviousValue allows you to look at different models in the direction of the entrance.
ChangeListener used to monitor JSpinner events
JSpinner direct support of a monitor events: changeListener. In other places, when commitEdit () method is called, this incident will be the trigger spinner tell you the value of change. To that list a link to a custom ChangeListener, and icons associated with a procedure.
Table 1. JSpinner with ChangeListener
Import java.awt .*;
Import javax.swing .*;
Import javax.swing.event .*;
Import java.text .*;
Import java.util .*;
(Public class SpinnerSample
Public static void main (String args []) (
Runnable runner = new Runnable () (
Public void run () (
JFrame frame = new JFrame ( "JSpinner Sample");
Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
DateFormatSymbols symbols =
New DateFormatSymbols (Locale.FRENCH);
ChangeListener listener = new ChangeListener () (
Public void stateChanged (ChangeEvent e) (
System.out.println ( "Source:" + e.getSource ());
)
);
String days symbols.getWeekdays [] = ();
SpinnerModel model1 = new SpinnerListModel (days);
JSpinner spinner1 = new JSpinner (model1);
Spinner1.addChangeListener (listener);
JLabel label1 = new JLabel ( "French Days / List");
JPanel panel1 = new JPanel (new BorderLayout ());
Panel1.add (label1, BorderLayout.WEST);
Panel1.add (spinner1, BorderLayout.CENTER);
Frame.add (panel1, BorderLayout.NORTH);
SpinnerModel model2 = new SpinnerDateModel ();
JSpinner spinner2 = new JSpinner (model2);
Spinner2.addChangeListener (listener);
JLabel label2 = new JLabel ( "Dates / Date");
JPanel panel2 = new JPanel (new BorderLayout ());
Panel2.add (label2, BorderLayout.WEST);
Panel2.add (spinner2, BorderLayout.CENTER);
Frame.add (panel2, BorderLayout.CENTER);
SpinnerModel model3 = new SpinnerNumberModel ();
JSpinner spinner3 = new JSpinner (model3);
Spinner3.addChangeListener (listener);
JLabel label3 = new JLabel ( "Numbers");
JPanel panel3 = new JPanel (new BorderLayout ());
Panel3.add (label3, BorderLayout.WEST);
Panel3.add (spinner3, BorderLayout.CENTER);
Frame.add (panel3, BorderLayout.SOUTH);
Frame.setSize (200, 90);
Frame.setVisible (true);
)
);
EventQueue.invokeLater (runner);
)
This procedure can run Model listener usage (of course, you will discover more about ChangeListener meaningful methods).
Customize the appearance of JSpinner
Swing with all the controls in the different systems JSpinner definition of look-and-feel types, with different appearance, such as show Figure 2. This controls the opening looks like a textfield, drew a different point two arrows.
Show Figure 2. JSpinner under different look-and-feel types
Set in the 11 UIResource attributes listed in Form 2, limited text field and the method of drawing arrows.
Table 2. JSpinner UIResource elements
SpinnerModel Interface
Up to now, we have seen how JSpinner category with a main link interface is SpinnerModel controls data model, SpinnerModel is defined as follows:
(Public interface SpinnerModel
/ / Properties
Public Object getValue ();
Public void setValue (Object);
Public Object getNextValue ();
Public Object getPreviousValue ();
/ / Listeners
Public void addChangeListener (ChangeListener);
Public void removeChangeListener (ChangeListener);
)
SpinnerModel directly in the six drawn JSpinner, and the method of indirect call JSpinner module approach in monitoring the situation, the incident will be linked to sniffers.
AbstractSpinnerModel category
AbstractSpinnerModel basic categories to be achieved is SpinnerModel interface, which provides management and monitoring notification list must implement the interface of the four methods, the three SpinnerModel concrete realization of the following: SpinnerDateModel, SpinnerListModel and SpinnerNumberModel.
SpinnerDateModel type can be inferred from the name, SpinnerDateModel provide data options. This class structure has two functions: a default choice of all the data, and the other is the scope of your request.
Public SpinnerDateModel ()
SpinnerModel model = new SpinnerDateModel ();
JSpinner spinner = new JSpinner (model);
Public SpinnerDateModel (Date value, Comparable start, Comparable end,
Int calendarField)
Calendar cal = Calendar.getInstance ();
Date now cal.getTime = ();
Cal.add (Calendar.YEAR, -50);
Date startDate = cal.getTime ();
Cal.add (Calendar.YEAR, 100);
Date endDate = cal.getTime ();
SpinnerModel model =
New SpinnerDateModel (now, startDate, endDate, Calendar.YEAR);
JSpinner spinner = new JSpinner (model);
If we do not name any parameters, there is no start and end points. The following examples show the use of parameters to indicate the scope of 100 years. Finally variables should be a member of the Calendar is a fixed value:
Calendar.AM_PM
Calendar.DAY_OF_MONTH
Calendar.DAY_OF_WEEK
Calendar.DAY_OF_WEEK_IN_MONTH
Calendar.DAY_OF_YEAR
Calendar.ERA
Calendar.HOUR
Calendar.HOUR_OF_DAY
Calendar.MILLISECOND
Calendar.MINUTE
Calendar.MONTH
Calendar.SECOND
Calendar.WEEK_OF_MONTH
Calendar.WEEK_OF_YEAR
Calendar.YEAR
NOTE: Calendar SpinnerDateModel does not contain any type of time domain, can not be reversed in SpinnerDateModel in JSpinner.
Table 3 lists the three attributes SpinnerModel, four on SpinnerDateModel.
Table 3. SpinnerDateModel attribute
Typically, the only new attributes you will be used to obtain the ultimate date, although all the results were wrapped in getValue (), an appropriate data type. If the constructor function provided that the scope of the data, then the value of previous and next will be null, in the border conditions.
SpinnerListModel
SpinnerListModel provide an entrance from the list of choices or at least a string expression, this category has three constructor function:
Public SpinnerListModel ()
SpinnerModel model = new SpinnerListModel ();
JSpinner spinner = new JSpinner (model);
Public SpinnerListModel (List <-> values)
List
SpinnerModel model = new SpinnerListModel (list);
JSpinner spinner = new JSpinner (model);
Public SpinnerListModel (Object [] values)
SpinnerModel model = new SpinnerListModel (args);
JSpinner spinner = new JSpinner (model);
When there is no parameters, the model includes a elements: empty string. List edition retains one pair of list are cited. Instead of the copy list. If the list has changed, then the model will also change the list. Array version of the creation of a private internal categories, and a list of examples. And the array version of the list, the initial choice is the first element, or they will throw an IllegalArgumentException anomaly.
4 shows such as forms, add the attribute is set, and get list.
Table 4. SpinnerListModel attribute
SpinnerNumberModel category
SpinnerNumberModel provided from an open or closed interval interval selection of digital models, digital will enable all categories Number of categories, including Integer and Double. He has four constructor function.
Public SpinnerNumberModel ()
SpinnerModel model = new SpinnerNumberModel ();
JSpinner spinner = new JSpinner (model);
Public SpinnerNumberModel (double value, double minimum, double maximum,
Double stepSize)
SpinnerModel model = new SpinnerNumberModel (50, 0, 100, .25);
JSpinner spinner = new JSpinner (model);
Public SpinnerNumberModel (int value, int minimum, int maximum, int stepSize)
SpinnerModel model = new SpinnerNumberModel (50, 0, 100, 1);
JSpinner spinner = new JSpinner (model);
Public SpinnerNumberModel (Number value, Comparable minimum, Comparable maximum,
Number stepSize)
Number value = new Integer (50);
Number min = new Integer (0);
Number max = new Integer (100);
Number step = new Integer (1);
SpinnerModel model = new SpinnerNumberModel (value, min, max, step);
JSpinner spinner = new JSpinner (model);
If the maximum or minimum null, is open interval. For no parameters, the initial value is 1, Step 1. Stepping is plastic, if you set .333, will not be completed.
Form 5 displayed SpinnerNumberModel attributes:
Table 5. SpinnerNumberModel attribute
Since the definition model
Generally speaking, the available JSpinner model has been sufficient, there is no need to create a sub-class of his. However, not all occasions will be entertained. For example, you may want to use a packaged SpinnerListModel model to replace the stop in the first or last element, the other end of the packaging. In Table 2 gives a concrete realization:
Listing 2. RolloverSpinnerListModel category
Import javax.swing .*;
Import java.util .*;
Public class RolloverSpinnerListModel extends SpinnerListModel (
Public RolloverSpinnerListModel (List values) (
Super (values);
)
Public RolloverSpinnerListModel (Object [] values) (
Super (values);
)
Public Object getNextValue () (
Object returnValue = super.getNextValue ();
If (returnValue == null) (
ReturnValue = getList (). Get (0);
)
Return returnValue;
)
Public Object getPreviousValue () (
Object returnValue = super.getPreviousValue ();
If (returnValue == null) (
List list = getList ();
ReturnValue = list.get (list.size () - 1);
)
Return returnValue;
)
)
JSpinner Editor
JSpinner available for each model, with the support of a minor, an internal JSpinner category. Nevertheless, the control module can control whether or not optional, JSpinner editor allows you to control how to display and edit the value of each option.
JSpinner.DefaultEditor category
JSpinner the setEditor () method allows you to be any Jcomponent as JSpinner editor, of course, you could do that more typical, you will be used for JSpinner.DefaultEditor subclass operation. JformattedTextField to a simple editor, will provide all the basic functions you need. It includes a basic constructor function:
Public JSpinner.DefaultEditor (JSpinner spinner)
JSpinner spinner = new JSpinner ();
JComponent editor = JSpinner.DefaultEditor (spinner);
Spinner.setEditor (editor);
6 in the table can be seen, there are two attributes:
Table 6. JSpinner.DefaultEditor properties
In use do not know which model is the work of the circumstances, at this level you can do is to change the text JformattedTextField show. More typical is that you will change the model editor since some definitions.
JSpinner.DateEditor category
DateEditor allows you to customize different dates displayed, the use of java.text package SimpleDateFormat category. Javadoc see more information available on the SimpleDateFormat format model. If you do not like the default display mode, the function can be passed to the constructor of the second parameter transmission of a new parameter to change display modes.
Public JSpinner.DateEditor (JSpinner spinner)
SpinnerModel model = new SpinnerDateModel ();
JSpinner spinner = new JSpinner (model);
JComponent editor = JSpinner.DateEditor (spinner);
Spinner.setEditor (editor);
Public JSpinner.DateEditor (JSpinner spinner, String dateFormatPattern)
SpinnerModel model = new SpinnerDateModel ();
JSpinner spinner = new JSpinner (model);
JComponent editor = JSpinner.DateEditor (spinner, "MMMM yyyy");
Spinner.setEditor (editor);
By default, the format is M / d / yy h: mm a representative or 12/25/04 12:34 PM 2004 as a Christmas time. Examples will be back in 2004 December.
Editor's two properties in Form 7.
Table 7. JSpinner.DateEditor attribute
When using SpinnerListModel JSpinner.ListEditor type of work, ListEditor do not support any particular format. Rather, it provides a pre-type support. Since the modules are aware at all entrances, and the editor will try to match user input characters. Here there is only one constructor function, but less than you might almost.
Public JSpinner.ListEditor (JSpinner spinner)
In the Form 8 ListEditor will see only one attribute:
JSpinner.NumberEditor category
DateEditor NumberEditor and working methods are similar, allowing you to enter a customized display mode. Replace SimpleDateFormat work can help java.text NumberEditor included in the category DecimalFormat. Like DateEditor, he constructed two functions:
Public JSpinner.NumberEditor (JSpinner spinner)
SpinnerModel model = new SpinnerNumberModel (50, 0, 100, .25);
JSpinner spinner = new JSpinner (model);
JComponent editor = JSpinner.NumberEditor (spinner);
Spinner.setEditor (editor);
Public JSpinner.NumberEditor (JSpinner spinner, String decimalFormatPattern)
SpinnerModel model = new SpinnerNumberModel (50, 0, 100, .25);
JSpinner spinner = new JSpinner (model);
JComponent editor = JSpinner.NumberEditor (spinner, "#,## 0 .###");
Spinner.setEditor (editor);
The second constructor function using the default format string. If the figures too, will use a comma. If the result is a complete number will not be displayed with the metric system.
Table 9, showed that the two attributes editor.
Table 9. JSpinner.NumberEditor attribute
Aggregate
In this article, you learn to Swing in the JSpinner controls. When you choose to control certain areas in certain, JSpinner through the roller allows you to choose the values. You learn how to provide these options to the value of: through the use of SpinnerDateModel and DateEditor, SpinnerListModel and ListEditor, SpinnerNumberModel NumberEditor and to set the date.
Resources
Javaworld.com: javaworld.com
Matrix-Java developer community: http://www.matrix.org.cn/
This article adapted from The Definitive Guide to Java Swing, Third Edition, John Zukowski (Apress, June 2005; ISBN: 1590594479):
Http://www.apress.com/book/bookDisplay.html?bID=393
About the author