- Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory()
Wednesday, March 29, 2006
Memoria libre y ocupada en el sistema
Tuesday, March 28, 2006
XMLEncoder
XMLEncoder
SwingX Online Components Store
Aquí tenéis unas cuantas capturas de pantalla de los componentes. Seguro que encontráis algo que puede seros útil.
Sunday, March 26, 2006
Lanzar un navegador desde java
Bare Bones Browser
Launch for Java
Use Default Browser to Open a Web Page from a Swing Application
Java is often touted as the programing language of the Internet, so you would think Java might include a standard platform-independent mechanism to launch the user's default web browser. Unfortunately, this commonly needed feature is left to the application developer to build, and it's not easy. Two open source projects exist specifically to address this problem -- BrowserLauncher and BrowserLauncher2. The BrowserLauncher2 project is more current and is an industrial strength solution packed with advanced features and even supports old browsers and old OSes.Bare Bones
The Bare Bones Browser Launch solution, on the other hand, is intended for those with much simpler requirements or those just looking for an educational "Hello, World" type tutorial on the subject. This solution is appropriate when a compact lightweight method will suffice which limits support to the most current browsers and OSes. Bare Bones is free and works on Mac OS X, GNU/Linux, Unix (Solaris), and Windows XP.
Let's jump straight to the code:
BareBonesBrowserLaunch.java
///////////////////////////////////////////////////////// // Bare Bones Browser Launch // // Version 1.5 // // December 10, 2005 // // Supports: Mac OS X, GNU/Linux, Unix, Windows XP // // Example Usage: // // String url = "http://www.centerkey.com/"; // // BareBonesBrowserLaunch.openURL(url); // // Public Domain Software -- Free to Use as You Like // ///////////////////////////////////////////////////////// import java.lang.reflect.Method; import java.util.Arrays; import javax.swing.JOptionPane; public class BareBonesBrowserLaunch { private static final String errMsg = "Error attempting to launch web browser"; public static void openURL(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class}); openURL.invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); else { //assume Unix or Linux String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; String browser = null; for (int count = 0; count < browser ="="" browser =" browsers[count];" browser ="="">Launch the user's default browser from your Java Swing application with the following line of code:
MyApp Test Program
You can try out the cross-platform Bare Bones Browser Launch with this small standalone test program:
MyApp.java
import java.awt.event.*; import javax.swing.*; public class MyApp { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); final JTextField urlField = new JTextField("http://www.centerkey.com "); JButton webButton = new JButton("Web Trip"); webButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { BareBonesBrowserLaunch.openURL(urlField.getText().trim()); } } ); frame.setTitle("Bare Bones Browser Launch"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel.add(new JLabel("URL:")); panel.add(urlField); panel.add(webButton); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }Tutorial
Put both the "BareBonesBrowserLaunch.java" and "MyApp.java" files into a folder, and issue the following command line instructions:
$ java MyApp
A window like the following will be displayed:
Click the "Web Trip" button to launch the default browser.
Of course, you'll need the Java JDK for this work, and you may also need to specify the full path to the Java commands. On Windows for example, the "javac" command above would become something like:
JAR Library
Instead of putting the Bare Bones Browser Launch code directly in your project, you can alternatively use it as an external JAR library [file: BareBonesBrowserLaunch.jar, v1.5, 21KB] complete with source code and Javadoc. Tell your IDE, such as Eclipse or NetBeans, to include the JAR file into your project and then add the following "import" statement to the class responsible for opening a web page:
The steps for including an external JAR into your project will vary depending on your IDE. In Eclipse, open your project and navigate through these menus and options (screenshot):
Llamar a otros programas
By John O'Conner, February 2006 |
With the default graphical user interface (GUI) look and feel, printing, and performance, the Java platform has come a long way in its effort to minimize the difference between the performance and integration of native applications and Java applications. Version 6 of the Java Platform, Standard Edition (Java SE), code-named Mustang, continues to narrow the gap with new system tray functionality, better print support for JTable
, and now the Desktop API (java.awt.Desktop
API). This article describes the new Desktop API, which allows Java applications to interact with the default applications associated with specific file types on the host platform. In order to describe the API more effectively, the article also features a simple application called DesktopDemo.
This new functionality is provided by the java.awt.Desktop
class. The API is adopted from the JDesktop Integration Components (JDIC) project. The goal of that project is to make "Java technology-based applications first-class citizens" of the desktop, enabling seamless integration. Specifically, the new Desktop API allows your Java applications to do the following:
- Launch the host system's default browser with a specific Uniform Resource Identifier (URI)
- Launch the host system's default email client
- Launch applications to open, edit, or print files associatedwith those applications
The Desktop API uses your host operating system's file associations to launch applications associated with specific file types. For example, if OpenDocument text (.odt
) file extensions are associated with the OpenOffice Writer application, your Java application could launch OpenOffice Writer to open, edit, or even print files with that association. Depending on your host system, different applications may be associated with each different action.
DesktopDemo is a simple Java application that uses Mustang's Desktop API. The application has one main window that exposes the entire API, allowing you to do three things:
- Launch the default browser with a specific URI.
- Launch the default email client with a mail recipient.
- Launch an associated application to open, edit, or print a file.
Figure 1 shows the user interface (UI).
|
You can run this application by downloading the application source and JAR
files, changing your console's active directory to the application project's dist
directory, and executing the following command using a Mustang JDK:
java -jar DesktopDemo.jar |
Before launching the browser, email client, or any application, DesktopDemo must determine whether your platform supports the API. First, however, DesktopDemo disables all the graphical text fields and buttons. It enables these graphical components after determining that the platform supports them.
After instantiating the UI, the application's constructor quickly disables the few components of this application as shown in the following code:
public DesktopDemo() { |
Use the Desktop.isDesktopSupported()
method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false
. After determining that the API is supported, that is, the isDesktopSupported()
returns true
, the application can retrieve a Desktop
instance using the static method getDesktop()
.
Desktop desktop = null; |
If your application doesn't check for API support using isDesktopSupported()
before calling getDesktop()
, it must be prepared to catch an UnsupportedOperationException
, which is thrown when your application requests a Desktop
instance on a platform that does not support these features. Additionally, if your application runs in an environment without a keyboard, mouse, or monitor (a "headless" environment), the getDesktop()
method will throw a java.awt.HeadlessException
.
Once retrieved, the Desktop
instance allows your application to browse, mail, open, edit, or even print a file or URI, but only if the retrieved Desktop
instance supports these activities. Each of these activities is called an action, and each is represented as a Desktop.Action
enumeration instance:
BROWSE
. Represents a browse action performed by the host's default browserMAIL
. Represents a mail action performed by the host's default email clientOPEN
. Represents an open action performed by an application associated with opening a specific file typeEDIT
. Represents an edit action performed by an application associated with editing a specific file typePRINT
. Represents a print action performed by an application associated with printing a specific file type
Before invoking any of these actions, an application should determine whether the Desktop
instance supports them. This is different from determining whether a Desktop
instance is available. The Desktop.isDesktopSupported()
method tells you whether an instance can be created. Once a Desktop
object is acquired, you can query the object to find out which specific actions are supported. If the Desktop
object does not support specific actions, or if the Desktop API itself is unsupported, DesktopDemo simply keeps the affected graphical components disabled. As Figure 2 indicates, the components cannot be used to invoke Desktop features in the disabled state.
|
Using a new Desktop
instance, the following code checks each Desktop.Action
for support and enables the appropriate graphical components:
public DesktopDemo() { |
Once the application determines the supported actions, it enables the appropriate graphical components. If all components are enabled, the UI should look like Figure 3.
|
Calling the following instance method will open your host's default browser:
public void browse(URI uri) throws IOException |
Because DesktopDemo's UI components are enabled only if the associated Desktop.Action
is supported, this simple demo application doesn't need to check support again before actually calling the browse()
method. However, checking action support before each invocation may be more robust in real-world applications:
if (desktop.isSupported(Desktop.Action.BROWSE)) { |
DesktopDemo adds a java.awt.event.ActionListener
to each button. When enabled, the Launch Browser button invokes the following method through its ActionListener
:
private void onLaunchBrowser(java.awt.event.ActionEvent evt) { |
The browse()
method can throw a variety of exceptions, including a NullPointerException
if the URI is null, an UnsupportedOperationException
if the BROWSE
action is unsupported, an IOException
if the default browser or application can't be found or launched, and a SecurityException
if a security manager denies the invocation.
If all goes well, however, the listener retrieves the text from the associated text field in Figure 4, creates a URI, and invokes the browse()
method. The code above launches the default browser on your system and instructs the browser to load the URI, as Figure 5 shows.
|
|
Applications can launch the host's default email client, if that action is supported, by calling this Desktop
instance method:
public void mail(URI uri) throws IOException |
DesktopDemo has an ActionListener
for the Launch Mail button. In this case, the listener invokes the following method:
private void onLaunchMail(java.awt.event.ActionEvent evt) { |
The onLaunchMail()
method retrieves the email recipient from the associated text field, creates the URI with a mailto
scheme argument if a recipient exists, and then invokes the mail()
method. The mail()
method is overloaded, so you can call it with or without a URI that represents its mailto
recipient (see Figure 6).
|
You can use more than just a single email recipient when creating this URI. The mailto
scheme supports CC
, BCC
, SUBJECT
, and BODY
fields as well. For example, the following text could be used to create a mailto
URI:
mailto:duke@sun.com?SUBJECT=Happy New Year!&BODY=Happy New Year, Duke! |
Figure 7 shows the result.
|
You can, of course, invoke mail()
without an argument. In this case, your email client will launch a new email window without specifying a recipient, subject, or body message.
Java applications can open, edit, and print files from their associated application using a Desktop
object's open()
, edit()
, and print()
methods, respectively (see Figure 8). Again, DesktopDemo allows these actions only if the Desktop
instance supports them, so in this application scenario, it is not necessary to check for support again.
|
Each of DesktopDemo's radio buttons has its own ActionListener
as well. In this case, each sets an instance variable so that it represents the most recently selected button's associated Desktop.Action
:
Desktop.Action action; |
When you press the Launch Default Application button, it invokes its own listener, which calls the following method:
private void onLaunchDefaultApplication(java.awt.event.ActionEvent evt) { |
This method determines which Desktop.Action
is selected and invokes the appropriate Desktop
instance method, either open()
, edit()
, or print()
. Each method requires a File
argument, which will be used to perform the requested action.
Interestingly, different applications may be registered for these different actions even on the same file type. For example, the Firefox browser may be launched for the OPEN
action, Emacs for the EDIT
action, and yet a different application for the PRINT
action. Your host desktop's associations are used to determine what application should be invoked. The ability to manipulate desktop file associations is not possible with the existing Desktop API in Mustang, and those associations can be created or changed only with platform-dependent tools at this time.
Desktop integration is an important Mustang theme. One way that Mustang supports this theme is through the java.awt.Desktop
API. This API allows Java applications to launch the host's default browser and email client. Additionally, Java applications can launch applications associated with specific file types to open, edit, and print files. Although Java applications cannot manipulate, create, or change file associations, the Desktop API does allow Java applications to launch the default associated applications. This article provides a sample application that demonstrates the API, which you can download from this site.
Note: Any API additions or other enhancements to the Java SE platform specification are subject to review and approval by the JSR 270 Expert Group.
The following information may help you learn more about Mustang's integration features as well as related topics:
Thursday, March 23, 2006
Stripes, un Framework web ligero y facil de usar
Para estos casos me he encontrado recientemente con Stripes. Se trata de un framework que no requiere cientos de líneas de ficheros XML de configuración, puesto que se configura mediante sencillas anotaciones J2SE 5.0 (que configuraran los llamados ActionBeans) y usa JSTL para comunicar las vistas con los controladores.
El propio autor reconoce que Spring o WebWork 2 son frameworks más robustos y complejos, pero eso no quita para que Stripes sea bastante útil en algunas ocasiones, en la web podréis ver un Quick Start Guide que os explica como hacer una sencilla calculadora en unos minutos.
Wednesday, March 22, 2006
Cluster y replicación de Base de datos
revolucionaria solución para la replicación y
duplicación de base de datos cuyo funcionamiento es
totalmente independiente tanto de la red/es local/es
como del/os sistema/s operativo/s en el/los que se
quiera implantar.
Características:
Multiplataforma, se puede instalar en cualquier Sistema
Operativo y versión existente en el mercado,
funcionando con Windows 2000, Windows XP, LINUX, etc.
pudiendo, incluso, conectarse varios ordenadores con
Eurocluster que estén instalados en S.O. diferentes
Funciona con cualquier Base De Datos existente en el
mercado que cumpla con las normas ANSI SQL, entre ellas
Access, SQL Server, MySql y Oracle
Número de usuarios ilimitados, se pueden conectar
tantos como soporte el servidor al que esta conectado.
Número de servidores interconectados en cluster o en
servidores de replicación ilimitado.
Las conexiones entre servidores pueden ser locales o a
través de internet.
Librería de etiquetas JSP para acceder a Google maps
La librería se distribuye bajo una licencia libre y la versión disponible actualmente todavía no es estable; es una beta y el autor advierte que todavía puede haber cambios en ella que rompan la compatibilidad con la versión actual.
¿Cuántos de vosotros habéis construido una aplicación que haga uso de Google maps? ¿Que API empleasteis?
Sunday, March 19, 2006
Saturday, March 18, 2006
Swing Tab order
import javax.swing.*;
import java.awt.*;
public class focusExample extends JFrame {
protected JTextField tf1, tf2, tf3, tf4, tf5, tf6;
protected MyPanel panel;
protected MyFocusTraversalPolicy focusTraversalPolicy;
public focusExample() {
tf1 = new JTextField(10);
tf2 = new JTextField(10);
tf3 = new JTextField(10);
tf4 = new JTextField(10);
tf5 = new JTextField(10);
tf6 = new JTextField(10);
panel = new MyPanel();
getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(tf1);
this.getContentPane().add(tf2);
this.getContentPane().add(tf3);
this.getContentPane().add(panel);
this.getContentPane().add(tf4);
this.getContentPane().add(tf5);
this.getContentPane().add(tf6);
focusTraversalPolicy = new MyFocusTraversalPolicy();
setFocusTraversalPolicy(focusTraversalPolicy);
pack();
setVisible(true);
}
public class MyFocusTraversalPolicy extends FocusTraversalPolicy {
public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
if(aComponent.equals(tf1)) return tf2;
else if(aComponent.equals(tf2)) return tf3;
else if(aComponent.equals(tf3)) return panel.getFocusTraversalPolicy().getDefaultComponent(panel);
else if(panel.isAncestorOf(aComponent)){
if(aComponent.equals(panel.getFocusTraversalPolicy().getLastComponent(panel))) return tf4;
else return panel.getFocusTraversalPolicy().getComponentAfter(panel, aComponent);
}
else if(aComponent.equals(tf4)) return tf5;
else if(aComponent.equals(tf5)) return tf6;
else return tf1;
}
public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
if(aComponent.equals(tf6)) return tf5;
else if(aComponent.equals(tf5)) return tf4;
else if(aComponent.equals(tf4)) return panel.getFocusTraversalPolicy().getLastComponent(panel);
else if(panel.isAncestorOf(aComponent)){
if(aComponent.equals(panel.getFocusTraversalPolicy().getFirstComponent(panel))) return tf3;
else return panel.getFocusTraversalPolicy().getComponentBefore(panel, aComponent);
}
else if(aComponent.equals(tf3)) return tf2;
else if(aComponent.equals(tf2)) return tf1;
else return tf6;
}
public Component getDefaultComponent(Container focusCycleRoot) {
return tf1;
}
public Component getFirstComponent(Container focusCycleRoot) {
return tf1;
}
public Component getLastComponent(Container focusCycleRoot) {
return tf6;
}
}
public class MyPanel extends JPanel {
protected JTextField tf1, tf2, tf3;
protected FocusTraversalPolicy focusTraversalPolicy;
public MyPanel() {
tf1 = new JTextField(10);
tf2 = new JTextField(10);
tf3 = new JTextField(10);
this.add(tf3);
this.add(tf2);
this.add(tf1);
focusTraversalPolicy = new FocusTraversalPolicy() {
public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
if(aComponent.equals(tf1)) return tf2;
else if(aComponent.equals(tf2)) return tf3;
else return tf1;
}
public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
if(aComponent.equals(tf3)) return tf2;
else if(aComponent.equals(tf2)) return tf1;
else return tf3;
}
public Component getDefaultComponent(Container focusCycleRoot) {
return tf1;
}
public Component getFirstComponent(Container focusCycleRoot) {
return tf1;
}
public Component getLastComponent(Container focusCycleRoot) {
return tf3;
}
};
}
public FocusTraversalPolicy getFocusTraversalPolicy() {
return focusTraversalPolicy;
}
}
public static void main(String args[]) {
new focusExample();
}
}
This also works if MyPanel is defined in another file. By default, Container's getFocusTraversalPolicy() will return null if a call to isFocusCycleRoot() on the container returns false. In MyPanel, getFocusTraversalPolicy() is overridden to return the focus traversal policy even if the panel is not a focus cycle root. This allows the frame the panel is on access to the panel's focus traversal policy. You should over-ride getFocusTraversalPolicy() in any subclasses of container that you add to your frame, or you'll get a null-pointer exception when calling panel.getFocusTraversalPolicy(). I'm unsure about any side effects from over-ridding getFocusTraversalPolicy(); if anyone knows of any problems this may cause, please lte me know.
Rendering cells in Swing's JTable component
Excerpt from Chapter 6 of Professional Java Programming |
Level: Intermediate Brett Spell (JavaBrewer@aol.com)Wrox Press Ltd 01 Nov 2000 The book Professional Java Programming covers a variety of advanced Java topics, such as the Java 2 security model, internationalization, performance tuning and memory management, printing, help, drag-and-drop operations, and cut-and-paste operations. It also contains chapters on JTree and JTable, two of the more complex components provided with Swing. This excerpt from Chapter 6 explains how JTable handles the drawing (or "rendering") of its cells and supports the editing of their values. In addition to describing the behavior of the renderers and editors provided with Swing, the text also discusses how to go about creating your own implementations. The complete chapter in the book includes information on how to enhance JTable's functionality to add features that are often needed, such as the ability to sort rows, to create multi-line column headers, and so on. In the screen shot below, the data in several of the columns isn't displayed in an ideal fashion: Specifically, three things can be improved:
In addition to returning a reference to the rendering component, As we'll see shortly,
The following class provides an example of a custom renderer, and it will be used to display the values in the Gender field in our sample application's table. Those values currently appear as a text string of "true" or "false" depending upon the cell's value, but this renderer will cause them to be drawn by a
When an instance of this class is created, it adds two items to its list: a "Male" selection, and a "Female" selection. The
The data for the table comes from the
When you compile and execute the modified version of the application, it produces a display like the one shown below. Notice that the "true" and "false" strings that previously appeared in the It's important to realize that renderers are not really added to In many cases, the easiest way to define a custom cell renderer is to extend Swing's
In effect, In many cases, calling
This simple class does just two things: it changes the label's horizontal alignment during construction, and it overrides the Now that we've created a custom renderer for the Account Balance column, we need to have the table use the renderer when drawing the cells in that column, which could be done by explicitly assigning it to the When a
Since
Now that our
This new addition to At this point, you may be wondering what happens when no renderer has been explicitly assigned to a column and there is no entry in the table's class-to-renderer map that matches the column's data type. You're correct if you guessed that the rendering is handled by When no renderer has been explicitly assigned to a column and no entry for the column's To summarize
This approach provides a great deal of flexibility in assigning renderers to table cells, since it allows you to create a renderer and have it handle rendering for columns with a specific data type, along with any subclasses of that type.
We've now seen how to create custom renderers and how to associate a renderer with a given type of data. However, it's often not necessary to do either one, since JTable includes a number of predefined renderers for commonly used data types, and entries for those renderers are automatically included in its class-to-renderer map. For example, it was already mentioned that an entry exists in the map that associates
As we saw earlier, the date values displayed by In addition to java.lang.Number javax.swing.ImageIcon java.lang.Boolean
Although each cell in the Gender column now appears to be a
This indicates that the cells in the Gender column are now editable. However, if you click on a cell in that column intending to select a gender from a You may be surprised that a text field appears when you edit the cell, because the cell seems to contain a Regardless of which type of component is used, it may seem that the cells are finally editable, which is partly true, but if you enter a value into one of these cells, the value you type is discarded once you complete the editing. To understand why this occurs and what to do about it, you should be familiar with cell editors and how Cell editors
You can assign an editor to one or more When a Although The edit operation is allowed to proceed only if both the
If these parameters look familiar, it's because they're almost identical to those passed to the Before returning a reference to the component that's responsible for handling editing, Once the editing component has been prepared and returned from the With the editing component positioned over the cell being edited, the event that originally triggered the edit processing is posted to the editing component. For example, in the case of a Each A request to end editing can come either from the Regardless of where the request originates to end editing, the The following class defines a component that can be used to provide editing of the rows in the Gender column defined in When editing is initiated for one of the cells in the Gender column, the
Now that the editor component has been defined, it needs to be associated with the Gender column, as shown in the following code:
When this code is compiled and run, a However, selecting a different value from the one already stored in the cell does not result in the cell's value being modified. That's because the value is never changed in the
It's not necessary in every case to build a completely new cell editor. In fact, the
|