Showing posts with label Swing. Show all posts
Showing posts with label Swing. Show all posts

Sunday, July 01, 2012

Do You Remember When?... Closing Windows in Swing

I was just looking at some old Swing code. I mean some really old Swing code, and I found this interesting morsel of code which made me think back to when this was considered the standard mechanism for window management.

Today when we want to control the closing of a JFrame, we would use something like setDefaultCloseOperation(int operation). If we wanted the frame to close when someone clicked the "X", we would set it using setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). The code I found was the old style of doing it, and it made me think about it. Here is the code snippet I found which would still work today.



Here are the rules for the implementation.

There are three elements that the event handling mechanism must employ:
  1. It must implement a listener interface, or extend a class that implements a listener interface.
  2. You must register an event handler class as a listener on one or more components.
  3. The event handler class has code that implements methods in the listener interface.
Does it meet the requirements? It sure does, and the code works today. It is part of my code cleanup for code I have kept since 1995, and I am deciding what is useful.
 
Update: I found this comment in the code too. It is still true and relevant, but I must have thought it important to document since there are so many little event handlers. Since it was not in source control, I have no idea when I wrote this. Perhaps when Swing came on the scene (1997)? Interesting historical note.
The event handler code should be minimized to allow the program to remain responsive to user input. The event handling code is handled on a single thread - event-dispatching thread. This thread also handles the paint and repainting of components. This may also result in "gray screens" while the system is waiting to repaint a component.

Wednesday, November 24, 2010

Creating Charts on Headless Systems: JFreechart and Rogue Wave

JFreechart Example
This week we had an interesting conundrum at work. We had a headless server which is not uncommon, that would not generate charts in our web based application. Apparently some of the charts are not used very often, or it would have been reported sooner. The charts in question were originally created using Rogue Wave Software charting software from 1999-2000. This software was used to create charts in AWT based applications. Yes, I said AWT not Swing, and I know that it is very old.

The particular charts do not have replacements available in free charting software like JFreechart currently, and are available only as commercial software. We had purchased the original software and licenses from Rogue Wave, and did not want to purchase new commercial software.

Now to the conundrum. Since Java 1.4, heavyweight AWT and Swing components throw a HeadlessException, if you attempt to run them on a headless system.

As you can see from the list, it does not leave much room for the developer to work with in a headless environment. Fair enough, AWT/Swing are GUI environments.

The graphical libraries used to create charts in the case of Rogue Wave and JFreechart generally expect a GUI framework. Rogue Wave is expecting to generate the chart images in a Window, or one of its subclasses like Frame. This can cause an issue as you can see. So I am left with a couple of components that I can use like Component, Canvas, and Panel.

You can create a headless environment and check it with the code below.

System.setProperty("java.awt.headless", "true");
boolean headless = GraphicsEnvironment.isHeadless();
System.out.println("Headless: " + headless);

So how do you generate the charts, or create images in general on a headless system. It turns out to be quite simple. Since all components have a paint(Graphics g) method, and JFreechart has a createBufferedImage() method. These turn out to be the keys.

Solution

We need to create a BufferedImage which we can pass to the Component to paint. Once we create the image to paint to, we simply ask the component to paint it, and use ImageIO to output our chart.

Note: You will need to have the Rogue Wave graphing and gif libraries, or you may comment out those code sections.

NetBeans 6.9 project files: HeadlessAWT.zip

Headless.java

/*
 *  Copyright 2010 Blue Lotus Software.
 *  Copyright 2010 John Yeary.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.bluelotussoftware.graph.headless.example;

import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Locale;
import com.roguewave.chart.awt.datamodels.v2_2.SampleData;
import com.roguewave.chart.awt.standard.v2_2.beans.PieChart;
import com.roguewave.chart.awt.standard.v2_2.beans.LineChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.encoders.ImageFormat;
import org.jfree.data.general.DefaultKeyedValuesDataset;
import org.jfree.data.general.DefaultPieDataset;

/**
 *
 * @author John Yeary
 * @version 1.0
 */
public class Headless {

    private static BufferedImage generateRectangle(Component component, int width, int height) {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.ORANGE);
        graphics.fill3DRect(50, 50, 300, 300, true);
        component.paint(graphics);
        return bufferedImage;
    }

    private static BufferedImage generateRectangle(Component component) {
        return generateRectangle(component, 400, 400);
    }

    private static BufferedImage generateCylinder(int width, int height) {
        Panel panel = new Panel();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.ORANGE);
        graphics.drawOval(100, 100, 50, 75);
        graphics.fillOval(200, 100, 50, 75);
        graphics.drawLine(125, 100, 225, 100);
        graphics.drawLine(125, 175, 225, 175);
        panel.paint(graphics);
        return image;
    }

    private static boolean save(BufferedImage image, Component component) {
        boolean success = false;
        try {
            ImageIO.write(image, "gif", new FileOutputStream(component.getClass().getSimpleName() + ".gif"));
            success = true;
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace(System.err);
        } catch (IOException ex) {
            ex.printStackTrace(System.err);
        }
        return success;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        System.setProperty("java.awt.headless", "true");
        boolean headless = GraphicsEnvironment.isHeadless();
        System.out.println("Headless: " + headless);
        Toolkit tk = Toolkit.getDefaultToolkit();
        tk.beep();

        BufferedImage bufferedImage = null;
        boolean success = false;

        // ---------------------------------------------------------------------------------------------- //
        Component component = new Component() {

            private static final long serialVersionUID = 3109256773218160485L;
        };
        Canvas canvas = new Canvas();
        Panel panel = new Panel();
        // ---------------------------------------------------------------------------------------------- //

        // Drawing Examples
        bufferedImage = Headless.generateRectangle(component);
        success = Headless.save(bufferedImage, component);
        System.out.println("Created " + component.getClass().getSimpleName() + " : " + success);
        success = false;

        bufferedImage = Headless.generateRectangle(canvas);
        success = Headless.save(bufferedImage, canvas);
        System.out.println("Created " + canvas.getClass().getSimpleName() + " : " + success);
        success = false;

//        bufferedImage = Headless.generateRectangle(panel);
//        success = Headless.save(bufferedImage, panel);
//        System.out.println("Created " + panel.getClass().getSimpleName() + " : " + success);
//        success = false;

        bufferedImage = Headless.generateCylinder(400, 400);
        success = Headless.save(bufferedImage, panel);
        System.out.println("Created " + panel.getClass().getSimpleName() + " : " + success);
        success = false;
        // ---------------------------------------------------------------------------------------------- //

        // Rogue Wave Examples
        SampleData sd = new SampleData();
        LineChart lineChart = new LineChart();
        lineChart.setData(sd);
        PieChart pieChart = new PieChart();
        pieChart.setData(sd);

        // The chart size is required.
        lineChart.setSize(400, 400);
        pieChart.setSize(400, 400);

        bufferedImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
        lineChart.paint(g);
        ImageIO.write(bufferedImage, ImageFormat.PNG, new FileOutputStream("LineChart.png"));
        pieChart.paint(g);
        ImageIO.write(bufferedImage, ImageFormat.PNG, new FileOutputStream("PieChart.png"));
        // ---------------------------------------------------------------------------------------------- //

        // JFreechart Examples
        DefaultPieDataset dpds = new DefaultKeyedValuesDataset();
        dpds.setValue("Java", 60.0);
        dpds.setValue("C++", 20.0);
        dpds.setValue("MS Technologies", 10.0);
        dpds.setValue("Misc.", 10.0);

        JFreeChart jfc = ChartFactory.createPieChart("Programming Languages", dpds, true, true, Locale.ENGLISH);
        bufferedImage = jfc.createBufferedImage(400, 400);
        ImageIO.write(bufferedImage, "gif", new FileOutputStream("jfc-piechart.gif"));
    }
}

Enhanced by Zemanta

Tuesday, February 09, 2010

NetBeans 6.8 JSR-296 Database Application Example

Here is an example application development video.

Saturday, November 21, 2009

Swing Event Examples - JButton and JRadioButton

I was looking at some code examples I created, and decided to polish them up and post them. One of the most challenging issues for most Swing developers is learning, and using events. I have included to examples below: One using events associated with a JButton, and the other using ActionEvents when a JRadioButton is pressed.

Note: The attached project is a NetBeans 6.5.1 project.

Here is the JButtonsEvent.java example

/*
* Copyright 2009 John Yeary <jyeary@bluelotussoftware.com>.

*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*

* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/

/**
* JButtonEvents.java

*
* Created on Dec 30, 2008, 3:00:00 PM
*

* $Id: JButtonEvents.java 155 2009-11-21 15:06:40Z jyeary $
*/

package com.bluelotussoftware.examples.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
*
* @author John Yeary <jyeary@bluelotussoftware.com>

* @version 1.0
*/
public class JButtonEvents extends javax.swing.JFrame {

JButton button;

public JButtonEvents() {
initialize();
}

private void initialize() {
button = new JButton("Press Me");

//Add Listeners as anonymous inner classes.

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent!");
}
});

button.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {
System.out.println("ItemEvent!");
}
});

button.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) {
System.out.println("ChangeEvent!");
}
});


// Exit the application when the frame is closed

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(button);
this.pack();
}

/**
* @param args the command line arguments

*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new JButtonEvents().setVisible(true);
}
});
}
}

Here is the JRadioButtonActionEvents.java example

/*
* Copyright 2008-2009 John Yeary <jyeary@bluelotussoftware.com>.

*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*

* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/

/*
* JRadioButtonActionEvents.java

*
* Created on Dec 30, 2008, 3:45:09 PM
*
* $Id: JRadioButtonActionEvents.java 155 2009-11-21 15:06:40Z jyeary $
*/
package com.bluelotussoftware.examples.swing;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.ButtonModel;
import javax.swing.JRadioButton;

/**

*
* @author John Yeary <jyeary@bluelotussoftware.com>
* @version 1.0

*/
public class JRadioButtonActionEvents extends javax.swing.JFrame {

/** Creates new form JRadioButtonActionEvents */

public JRadioButtonActionEvents() {
initComponents();

int value = 0;
ButtonModel[] models = new ButtonModel[3];
int ctr = 0;
Enumeration e = buttonGroup1.getElements();

while (e.hasMoreElements()) {
JRadioButton x = (JRadioButton) e.nextElement();
models[ctr++] = x.getModel();

}
jRadioButton1.setActionCommand("A");
jRadioButton2.setActionCommand("B");
jRadioButton3.setActionCommand("C");
ActionListener action = new MyActionListener();
jRadioButton1.addActionListener(action);
jRadioButton2.addActionListener(action);
jRadioButton3.addActionListener(action);
buttonGroup1.setSelected(models[value], true);
}

class MyActionListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();

if ("A".equalsIgnoreCase(s)) {
System.out.println("Radio Button \"A\" ActionEvent!");
} else if ("B".equalsIgnoreCase(s)) {
System.out.println("Radio Button \"B\" ActionEvent!");
} else if ("C".equalsIgnoreCase(s)) {
System.out.println("Radio Button \"C\" ActionEvent!");
}
}
}

/** This method is called from within the constructor to

* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.
*/

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

buttonGroup1 = new javax.swing.ButtonGroup();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("A");

buttonGroup1.add(jRadioButton2);
jRadioButton2.setText("B");

buttonGroup1.add(jRadioButton3);
jRadioButton3.setText("C");

jLabel1.setText("Select a radio button to generate an ActionEvent");

org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1)
.add(layout.createSequentialGroup()
.add(21, 21, 21)
.add(jRadioButton1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jRadioButton2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jRadioButton3)))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jRadioButton1)
.add(jRadioButton2)
.add(jRadioButton3))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments

*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new JRadioButtonActionEvents().setVisible(true);
}
});
}

// Variables declaration - do not modify

private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
// End of variables declaration
}

NetBeans project files SwingEventsExamples-1.0.zip

Friday, September 11, 2009

Using JTabbedPane on Swing Application Framework (JSR-296)

I was trying to figure out how to set the selected tab for a multi-tab JTabbedPane on my Swing Application Framework application. I thought that a quick Google search would have a simple answer. This was not the case. I found a post on a forum where a number of other people were wondering how to do it. So here is a summary of how I did it.

On the Frameview, I added a method as show below:

public void setSelectedTab (Integer tabIndex) {
tabPanel.setSelectedIndex(tabIndex);
}


The tabPanel in my case is the JTabbedPane instance.

In the SingleFrameApplication, I modified the startup() method to display the tab I want.

Note: You must set it after a call to show() the FrameView

@Override
protected void startup() {
FrameViewImpl frameView = new FrameViewImpl(this);
show(frameView);
//This must be done after the GUI is displayed
frameView.setSelectedTab(0);
}

Thursday, September 10, 2009

Beans Binding Part Deux

I have really enjoyed using the Beans Binding Framework (JSR-295) in the past. It was a really good start to making Swing a more usable platform doing client development. The project and JSR have been left abandoned by Sun. In large measure this was the result of development work done by Sun on JavaFX.

The really painful part of JavaFX currently is based on two items:
  1. No table (grid) component.
  2. No data providers to make binding to a database easy.
The result is a nearly useless framework for business developers who don't need shiny new baubles. I need Swing to work.

I am not the only person who feels this way. Fabrizio Giudici has created a project on Kenai.com to address the shortcomings: Better Beans Binding. He took the original JSR-295 code and forked it to create the new project. The package names have remained the same to allow a drop in replacement for the current beans binding framework without breaking anything. I am excited that Fabrizio has decided to do this project. I am hopeful that others wil join the project and make "better beans binding" a reality for the business users and others who need to make Swing just work.

Wednesday, January 14, 2009

Swing Listener Example

I was asked about using a listener to handle Swing GUI events. I created a simple example which uses a PropertyChangeListener that captures events. You can see the KeyEvents output to the System.out

Here is a link to the NetBeans 6.5 project SwingGUIListenerExample

Saturday, December 13, 2008

JavaFX missing the boat

I was looking at all of the effort that went into JavaFX. Sun has really done a good job with it. It does some really cool things: effects, animations, simple declarative style, etc.

It is missing something... Usefulness.

I think that it is really neat. Don't get me wrong. I am wondering based on Sun's history and recent pull-back from projects it has called "the next big thing", that this will fall into the heap of ideas that fail to get momentum (sustainable momentum).

I have waited for two years (JavaOne 2007) for this to come out. In that two years, we have had plenty of hype, but no substance. Sun's chance at getting into the RIA space has been diminishing during this time. The folks that are/were most interested in this type of technology have adopted Adobe Flash, Flex, and Air, or have moved to Microsoft Silverlight.

Who is this technology designed for?

A few years ago, Sun had a product called Sun Studio Creator. It had this vision of making it easier for web developers to develop sophisticated JSF and EJB technology based sites. The idea was to make the tool easy enough for non-programmers to use these powerful technologies. It never gained critical mass. That technology was transferred over to NetBeans as Visual Web Pack in its first editions. Later this became Visual JSF in NetBeans (Project Woodstock). Sun has since abandoned the project.

Now Sun has another framework based on the same idea that we can get visual designers to work with Java developers to do the same thing again, but with a twist. Visual designers won't do ANY development, just provide their creative work to Java developers to implement.

Interesting.

I am an enterprise developer. I create applications for business users to use. These are primarily web based, but I also do a lot of Swing development. When I want to create an application for end users to access SAP, I don't need drop shadows, 3D animations, or transitions. I need a simple elegant interface to enter data. I have never seen a visual designer, nor do I need one. I need a technology that just works.

I shouldn't need a visual designer to create "pretty" pictures for my applications.

The majority of the companies I am familiar with are in the same boat. We don't need fancy JavaFX... we need Swing to work.

I would rather have had some folks at Sun work on JSR-295 Beans Binding and JSR-296 Swing Application Framework. These were Sun's next big things at JavaOne 2005 and JavaOne 2006.

Where do we go from here?

JavaFX is really cool. I suggest you go check out the demos if you have a Windows, or Mac based machine. Linux users will need to wait. It has not been released for Linux.

It is also quite apparent that someone in marketing who does not get it, came up with some of the current name changes: Stage and Scene. Really??? So I need to learn new names for something that should be transparent. That is a permanent mistake!

Tooling needs to be improved. In its initial release, the tools in NetBeans 6.5 are mediocre at best. I have been waiting for the technology and tools for two years. The initial tooling release is disappointing at its best, and better left undiscussed in polite company at its worst.

Swing tooling with Matisse, and Visual JSF are much more mature and better.

I will probably try some experiments with JavaFX, but it is not ready for the prime time of critical business application development and deployment.

In the December issue of eWeek magazine, Spencer Katt has an article on the last page which has a cartoon with the tag line "Adobe Releases 64-bit Version of Flash For Linux". In the cartoon, the Linux penguin asks Spencer what his favorite feature in Flash is. He replies "The skip-intro button". Let's hope that is not the fate of JavaFX.

Friday, November 09, 2007

Building Maps into Your Swing Application with the JXMapViewer



I just read a great tutorial by Joshua Marinacci on using the new Swing Labs JXMapViewer component. His tutorial is on java.net. It took me 15 minutes start to finish to do the tutorial. At the end, I had a wonderful proof of concept for using mapping in a Swing application.

This is a tutorial that should not be missed. It is so well written with plenty of images to demonstrate the steps. BZ to Josh.



I have added a copy of my example application which includes the screenshots above here
You will need to fix the dependencies and point them to the jar files found in the root of the project directory

Popular Posts