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

Thursday, October 15, 2009

Unique Example of synchronized threads with MouseListener

Ide@: Arindam Mitra



Below source code is an example of you can manage synchronization of a continuous thread of MouseEntered event with a user defined thread of MouseExited event.



MouseListener interface has abstract methods out of which mouseEntered and mouseExited are the two methods. Suppose, in a JWindow, you have a JProgressBar. When you enter your mouse in the JWindow, it will continuously progress the status of the progress bar. However, if you remove the mouse from the window, progress bar will stop progressing and halts the current status.



Below is the source code. Hope you like it.



import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class WindowProgressBarThread extends JFrame implements MouseListener, ActionListener, Runnable {
JLabel label;
JButton buttonClick;
JButton buttonClose;
JWindow window;
JProgressBar jProgressBar = new JProgressBar();
private static int statusInt = 0;
private Thread runner;
// A thread that runs as long as the timer
// is running. It sets the text in the label
// to show the elapsed time. This variable is
// non-null when the timer is running and is
// null when it is not running. (This is
// tested in mousePressed().)

// Constants for use with status variable.
private static final int GO = 0, TERMINATE = 1;

private int status;
// This variable is set by mouseEntered() and mouseExited()
// to control the thread. When it's time
// for the thread to end, the value is
// set to TERMINATE.

public WindowProgressBarThread() {

buttonClick = new JButton(" Click On It ");
buttonClose = new JButton("Close");
jProgressBar.setMaximum(100);
jProgressBar.setMinimum(0);
window = new JWindow();

JPanel panel = new JPanel(new GridLayout(1, 0));
JFrame.setDefaultLookAndFeelDecorated(true);
this.setLayout(new BorderLayout());
this.setDefaultLookAndFeelDecorated(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel.add(buttonClick);

this.add(panel, BorderLayout.LINE_START);



this.setSize(200,75);
this.pack();
this.setVisible(true);
this.setResizable(false);
this.setLocationRelativeTo(null);

window.addMouseListener(this);
buttonClick.addActionListener(this);
buttonClose.addActionListener(this);

}


// Run method executes while the timer is going.
// Several times a second, it computes the number of
// seconds the thread has been running and displays the
// whole number of seconds on the label. It ends
// when status is set to TERMINATE.
public void run() {
while (true) {
synchronized(this) {
if (status == TERMINATE) {
break;
}
if(statusInt <= 99) { statusInt = statusInt + 1; jProgressBar.setValue(statusInt); jProgressBar.setString(statusInt + "%"); jProgressBar.setStringPainted(true); } } waitDelay(100); } } synchronized void waitDelay(int milliseconds) { // Pause for the specified number of milliseconds OR // until the notify() method is called by some other thread. // (From Section 7.5 of the text.) try { wait(milliseconds); } catch (InterruptedException e) { } } public void mousePressed(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } synchronized public void mouseEntered(MouseEvent evt) { status = GO; runner = new Thread(this); runner.start(); // start the runner thread (can call it child thread) } synchronized public void mouseExited(MouseEvent evt) { status = TERMINATE; notify(); // Wake up the main thread so that child thread can terminate quickly. jProgressBar.setValue(statusInt); jProgressBar.setString(statusInt + "%"); jProgressBar.setStringPainted(true); runner = null; // stop the runner thread (can call it child thread) } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==buttonClick) { buttonClick.setEnabled(false); statusInt = 0; jProgressBar.setValue(statusInt); jProgressBar.setString(statusInt+"%"); jProgressBar.setStringPainted(true); window.add(new JLabel("Progress Bar Demo",SwingConstants.CENTER), BorderLayout.NORTH); window.add(jProgressBar, BorderLayout.CENTER); window.add(buttonClose, BorderLayout.SOUTH); window.pack(); window.setBounds(800, 500, 200, 75); window.setVisible(true); } if(ae.getSource()==buttonClose){ buttonClick.setEnabled(true); window.setVisible(false); } } public static void main(String[] args) { WindowProgressBarThread windoeProgressThread = new WindowProgressBarThread(); } }


Wednesday, October 14, 2009

Add Swing Components Dynamically using Array List

Below code is to add swing components (button and textfield) dynamically using ArrayList.


import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ButtonAddDynamic implements ActionListener{

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonAddDynamic().createAndShowGUI();
}
});
}

private JFrame frame;
private JPanel panel = new JPanel(new GridBagLayout());
private GridBagConstraints constraints = new GridBagConstraints();

private List fields = new ArrayList();
private List fieldButton = new ArrayList();
private List fieldFile = new ArrayList();

private JButton button1 = new JButton("Add Another TextField and Button");
private static int countReport = 0;
String files = null;
int y=2;

protected void createAndShowGUI() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

String[] labels = { "Locations of the given input" };
for (String label : labels)
addColumn(label);
addRowBelow();
constraints.gridx=1;
constraints.gridy=0;
panel.add(button1,constraints);

frame = new JFrame("Add Button Dynamically");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(panel));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
button1.addActionListener(this);

//Set the default button to button1, so that when return is hit, it will hit the button1

JRootPane root = frame.getRootPane();
root.setDefaultButton(button1);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}


private void addColumn(String labelText) {
constraints.gridx = fields.size();
constraints.gridy = 1;
panel.add(new JLabel(labelText), constraints);
constraints.gridy=2;
final JTextField field=new JTextField(40);
field.setEditable(false);
panel.add(field,constraints);
fields.add(field);

//constraints.gridy=3;
constraints.gridx = fields.size() + fieldButton.size();
JButton button = new JButton("OK");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null,"Program to add swing components dynamically","HI",1);
}
}
);
panel.add(button,constraints);
fieldButton.add(button);
panel.revalidate(); // redo layout for extra column
}


private void addRowBelow() {
y++;
constraints.gridy=y;
//System.out.println(fields.size());
for (int x=0;x < fields.size();x++) {
constraints.gridx=x;
final JTextField field = new JTextField(40);
field.setEditable(false);
panel.add(field, constraints);
constraints.gridx=x+1;
JButton button = new JButton("OK");
button.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null,"Program to add swing components dynamically","HI",1);
}
}
);
panel.add(button,constraints);
}
}

public void actionPerformed(ActionEvent ae){
if("Add Another TextField and Button".equals(ae.getActionCommand())) {
addRowBelow();
frame.pack();
frame.setLocationRelativeTo(null);
}
}
}

Java Source Code – Slowly Closing the Window of a JFrame – Tricks

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;


public class SlowClose {
public SlowClose() {

final JFrame jFrame = new JFrame();
jFrame.setSize(500,350);
jFrame.setVisible(true);
jFrame.setResizable(false);
jFrame.setLocationRelativeTo(null);
jFrame.setTitle("SlowClose");


jFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
int x = 500;
int y = 350;
int d = 10;
while(x > 100 && y > 50){
x = x-d;
y = y-d;
jFrame.setSize(x,y);
System.out.println("X = " + x + "Y = " + y);
try{
Thread.sleep(10000);
}catch(InterruptedException ie){
ie.printStackTrace();
}

if(x <= 100 y <= 50){
System.exit(0);
}
}
}
});
}

public static void main(String args[]) {
SlowClose slowClose = new SlowClose();
}

}

Sunday, August 16, 2009

JcheckBox – Select Any of the checkbox

Below is the java source code which selects any of the JcheckBox – which is basically acting as Radio Button.

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingCheckBoxDemo implements ActionListener {

JCheckBox FZYamaha;
JCheckBox XCD135Bajaj;
JCheckBox StunnerHero;
JCheckBox Avenger;

public SwingCheckBoxDemo() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingCheckBoxDemo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FZYamaha = new JCheckBox("FZ Yamaha");
FZYamaha.setMnemonic(KeyEvent.VK_C);
FZYamaha.setSelected(true);

XCD135Bajaj = new JCheckBox("XCD 135 Bajaj");
XCD135Bajaj.setMnemonic(KeyEvent.VK_G);
XCD135Bajaj.setSelected(false);

StunnerHero = new JCheckBox("Stunner");
StunnerHero.setMnemonic(KeyEvent.VK_H);
StunnerHero.setSelected(false);

Avenger = new JCheckBox("Avenger");
Avenger.setMnemonic(KeyEvent.VK_T);
Avenger.setSelected(false);

/*Put the check boxes in a column in a panel*/

JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.add(FZYamaha);
checkPanel.add(XCD135Bajaj);
checkPanel.add(StunnerHero);
checkPanel.add(Avenger);

frame.add(checkPanel, BorderLayout.LINE_START);

frame.pack();
frame.setSize(300,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

FZYamaha.addActionListener(this);
XCD135Bajaj.addActionListener(this);
StunnerHero.addActionListener(this);
Avenger.addActionListener(this);
}


public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == FZYamaha) {
System.out.println("Yamaha");
FZYamaha.setSelected(true);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(false);
Avenger.setSelected(false);
}

if(ae.getSource() == XCD135Bajaj) {
System.out.println("XCD135Bajaj");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(true);
StunnerHero.setSelected(false);
Avenger.setSelected(false);
}

if(ae.getSource() == StunnerHero) {
System.out.println("StunnerHero");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(true);
Avenger.setSelected(false);
}

if(ae.getSource() == Avenger) {
System.out.println("Avenger");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(false);
Avenger.setSelected(true);
}
}

public static void main(String[] args) {
SwingCheckBoxDemo swingCheckBoxDemo = new SwingCheckBoxDemo();
}
}



Thursday, August 13, 2009

JCheckBox - Java Source Code

Below source code is simple example of JCheckBox in Swings.


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JCheckBoxDemo {

JCheckBox FZYamaha;
JCheckBox XCD135Bajaj;
JCheckBox StunnerHero;
JCheckBox Avenger;

JCheckBoxDemo() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingCheckBoxDemo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FZYamaha = new JCheckBox("FZ Yamaha");
FZYamaha.setMnemonic(KeyEvent.VK_C);
FZYamaha.setSelected(true);

XCD135Bajaj = new JCheckBox("XCD 135 Bajaj");
XCD135Bajaj.setMnemonic(KeyEvent.VK_G);
XCD135Bajaj.setSelected(true);

StunnerHero = new JCheckBox("Stunner");
StunnerHero.setMnemonic(KeyEvent.VK_H);
StunnerHero.setSelected(true);

Avenger = new JCheckBox("Avenger");
Avenger.setMnemonic(KeyEvent.VK_T);
Avenger.setSelected(true);

/*Put the check boxes in a column in a panel*/

JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.add(FZYamaha);
checkPanel.add(XCD135Bajaj);
checkPanel.add(StunnerHero);
checkPanel.add(Avenger);

frame.add(checkPanel, BorderLayout.LINE_START);

frame.pack();
frame.setSize(300,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}


public static void main(String[] args) {
JCheckBoxDemo checkBoxDemo = new JCheckBoxDemo();
}
}









Tuesday, August 11, 2009

JMenu – Java Source Code

Below is the simple source code to implement JMenu, JMenuItem and JMenuBar.


Source Code



import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

public class ExploreMenu implements ActionListener {

ExploreMenu() {
JFrame frame = new JFrame("Explore Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setResizable(false);
frame.setLocationRelativeTo(null);

// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("File");
menuBar.add(menu);
// Create a menu item
JMenuItem item = new JMenuItem("Windows");
menu.add(item);
// Install the menu bar in the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
item.addActionListener(this);
}


public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Windows")) {
try {
Runtime.getRuntime().exec("explorer C:\\WINDOWS");
}catch(IOException ie){
ie.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}


public static void main(String[] args) {
ExploreMenu exploreMenu = new ExploreMenu();
}

}



Monday, August 3, 2009

TabbedPane – Java Source Code

The below code is the simple source code to create TabbedPane in Swings.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class TabbedPaneDemo {

TabbedPaneDemo() {
JFrame frame = new JFrame("TabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setResizable(false);
frame.setLocationRelativeTo(null);

JPanel p = new JPanel();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JTabbedPane tb = new JTabbedPane();

tb.addTab("Index",null,p,"This is enabled");
tb.addTab("Index",null,p1,"This is disabled");
tb.addTab("Index",null,p2,"This is enabled");
tb.addTab("Index",null,p3,"This is disabled");
tb.addTab("Index",null,p4,"This is enabled");

tb.setEnabledAt(1,false);
tb.setEnabledAt(3,false);

frame.add(tb);

frame.setVisible(true);
}



public static void main(String[] args) {
TabbedPaneDemo tabbedPaneDemo = new TabbedPaneDemo();
}

}


Friday, April 17, 2009

Implementing Action Class in Swing Components






The article enlightens us all with how you can implement Action Class in the Swing Components.

If you are aware of the swing components, you must have known that swing components do not allow us to edit the text underlying with in it without keyboard.

If you see the figure above, after right click on the textarea components or the textfield component, the option to copy, cut, paste, select all and delete all options are appearing.
This functionality does not come with default swing components.

You need to apply the Action class and DefaultEditorKit class to get it done.

DefaultEditorKit class is the class which is having a set of things needed by a text component to be functioning for some type of text component.

Without any further description of how we achieve this, I would like to bring the code for this:

import java.awt.Color;
import javax.swing.JFrame;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JPopupMenu;
import javax.swing.Action;
import java.util.Hashtable;
import javax.swing.border.LineBorder;
import javax.swing.text.DefaultEditorKit;

public class ActionDemo extends JFrame implements MouseListener {
JPopupMenu jPopupMenu = new JPopupMenu();
ActionDemo(){
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

JTextField jTextField1 = new JTextField(20);
JTextField jTextField2 = new JTextField(20);
JTextArea jTextArea = new JTextArea(5,20);
JScrollPane jScrollPane = new JScrollPane();

jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
jScrollPane.getViewport().add(jTextArea,null);
this.setTitle("ActionDemo");
this.setSize(300,75);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.add(jTextField1,BorderLayout.NORTH);
this.add(jTextField2,BorderLayout.CENTER);
this.add(jScrollPane,BorderLayout.SOUTH);
this.pack();
Action actions[] = jTextField1.getActions();
Action cutActiontf1 = TextUtilities.findAction(actions,
DefaultEditorKit.cutAction);
Action copyActiontf1 = TextUtilities.findAction(actions,
DefaultEditorKit.copyAction);
Action pasteActiontf1 = TextUtilities.findAction(actions,
DefaultEditorKit.pasteAction);
Action selectAllActiontf1 = TextUtilities.findAction(actions,
DefaultEditorKit.selectAllAction);
Action deleteActiontf1 = TextUtilities.findAction(actions,
DefaultEditorKit.deleteNextCharAction);

jPopupMenu.add(copyActiontf1);
jPopupMenu.add(cutActiontf1);
jPopupMenu.add(pasteActiontf1);
jPopupMenu.add(selectAllActiontf1);
jPopupMenu.add(deleteActiontf1);

jTextField1.addMouseListener(this);
jTextField2.addMouseListener(this);
jTextArea.addMouseListener(this);

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}

public void mouseClicked(MouseEvent me){

}

public void mouseReleased(MouseEvent me){
if(me.getButton() == MouseEvent.BUTTON3){
jPopupMenu.show(me.getComponent(),me.getX(),me.getY());
}
}

public void mousePressed(MouseEvent me){

}

public void mouseEntered(MouseEvent me){

}

public void mouseExited(MouseEvent me){

}

public static void main(String args[]){
ActionDemo actionDemo = new ActionDemo();
}
}

class TextUtilities {
private TextUtilities() {
}

public static Action findAction(Action actions[], String key) {
Hashtable commands = new Hashtable();
for (int i = 0; i < actions.length; i++) {
Action action = actions[i];
commands.put(action.getValue(Action.NAME),action);
}
return (Action) commands.get(key);
}
}


Hope you all will find it useful.

Tuesday, March 3, 2009

Print Swing Components in JAVA

Few days back, I have been asked for an assignment from my workgroup that will print a swing component. This was really new task for me, as I have never experienced it.

After digging through the internet, I could easily find out that JDK 6 itself has the provision of printing the Swing components. The package that it deals with is the java.awt.print package. The documentation link for the above package is: http://java.sun.com/javase/6/docs/api/index.html?java/awt/print/package-summary.html

The source code I found is very straight forward to explain as it first creates simple java frame. The class you will be using should extend JFrame to make it a Swing Component and it should implement Printable class to make it a pointer (Not technical terms) to printable object.

The following line of code is the backbone for printing the Swing Components:

public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}

The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.

The setPrintable() calls painter to render the pages. The pages in the document to be printed by this PrinterJob are rendered by the Printable object, painter.

Following is the whole set of code that first creates a Swing Component and then prints it.

package printswing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
import javax.swing.UIManager;

public class Main extends JFrame implements ActionListener,Printable{

/** Creates a new instance of PrintEntire */
public Main() {
super("An example of printing swing components");
setNativeLookAndFeel();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.setActionCommand("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}


public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Print")){
this.print();
}
}


public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}

public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}

public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}

/** A simplified way to see a JPanel or other Container.
* Pops up a JFrame with specified Container as the content pane.
*/

public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setVisible(true);
return(frame);
}

/** Uses Color.white as the background color. */

public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height, title, Color.white));
}

/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/

public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}


public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}

public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}

public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}

public static void main(String args[]){
new Main();
}

class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;

public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
}

Friday, August 8, 2008

Java class to capture frame in JPG format

Here is the thing that enables java developers to capture the frame into a picture. To capture a frame, you need to use BufferedImage class of the java.awt.image package.

The BufferedImage subclass describes an Image with an accessible buffer of image data. A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0). Any Raster used to construct a BufferedImage must therefore have minX=0 and minY=0.

You can go to the following link to see the API of BufferedImage class.
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html

A demo code for capturing the frame into picture is given below.

Source code:

import java.awt.AWTException;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class Fig extends javax.swing.JFrame implements ActionListener{

private JButton jButton1 = null;
private JLabel jLabel1 = null;
public Fig(){
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setLayout(new FlowLayout());
jLabel1 = new JLabel("Demo");
jButton1 = new JButton("Demo");

this.add(jLabel1);
this.add(jButton1);
jButton1.setActionCommand("Demo");
jButton1.addActionListener(this);
this.setTitle("Figure");
this.setSize(200,100);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}

public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Demo")){
try {
this.createImage(this,"C:\\Demo.jpg");
} catch (AWTException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// Methods to create Image correspoding to the frame.
public static BufferedImage createImage(Component component, String fileName)
throws AWTException, IOException {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, component);
Rectangle region = component.getBounds();
region.x = p.x;
region.y = p.y;
return Fig.createImage(region, fileName);
}

public static BufferedImage createImage(Rectangle region, String fileName)
throws AWTException, IOException {
BufferedImage image = new Robot().createScreenCapture( region );
Fig.writeImage(image, fileName);
return image;
}

public static void writeImage(BufferedImage image, String fileName)
throws IOException {
if (fileName == null) return;
int offset = fileName.lastIndexOf( "." );
String type = offset == -1 ? "jpg" : fileName.substring(offset + 1);

ImageIO.write(image, type, new File( fileName ));
}
// Methods to create Images
//End
public static void main(String args[]){
Fig fig = new Fig();
}
}


The highlighted portion of the code is responsible for capturing the frame into picture. There are two createImage methods in the code.

The first one converts a point from the component’s coordinate system to screen coordinates. Then it gets the bound of the component in the form of rectangle object. The bound specify the width, height and location relative to its parents.

It passes the location/region and size details to the second createImage method. The second one creates the image containing the pixels read from the screen corresponding to the region.

The writeImage method writes it to the specific file in jpg format with the help of write method of ImageIO class.




Practical Use:

It is quite useful in standalone applications.

The application is also useful, whenever you want some frame to be shown to a particular group of people. If you want some chart frame or any status frame which indicates some record over the past few months, you can easily capture it in jpg format and send it to concerned persons.



Hope you all will find it useful.

Saturday, June 28, 2008

AutoComplete in Java

While using Internet Explorer, we use autocomplete facility in browsers, google search for e.g. if you type 'g' in the browser, all the urls starting with 'g' will appear below.

If you are using java and you want the same thing in a textfield, for e.g. you want that whenever you write anything in the textfield, it should show every value those are starting with the letter you type, meaning, you want autocomplete in textfield, here is the trick.

In java, there are APIs available to do that effectively.

Suppose jTextField1 is the textfield in which you want to have that autocomplete facility. Here is the code to do it.

Demo Code

AutoComplete au = new AutoComplete(jTextField1);

au.add("One");

au.add("Two");

au.add("Three");

au.add("Four");


au.add("Five");

au.add("Six");

au.add("Seven");

au.add("Eight");

au.add("Nine");

au.add("Ten");

You can find the API in below mentioned links:

http://femur.biostr.washington.edu/~mindseer/doc/edu/washington/biostr/sig/brainj3d/shwing/swing/AutoComplete.html



It needs a specific jar file. You can find it in below link:

http://sig.biostr.washington.edu/projects/MindSeer/download.html

Practical Use

Suppose, you are using database. And you need the details based on a particular field or column which may be your primary key. You can add these primary keys to the autocomplete and use it.





Total Pageviews