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

Thursday, 21 November 2013

Set Notepad Icon for JFrame in Swing

Here is how to set notepad icon for JFrame in Swing. Yes, you heard it right. But is it simple. Dead simple. Just see it below.

import javax.swing.*;

import java.awt.*;

import java.io.*;

import javax.swing.filechooser.*;

class WindowsIconForJFrame extends JFrame

{

public WindowsIconForJFrame()

{

createAndShowGUI();

}



private void createAndShowGUI()

{

setTitle("Windows Icon");

setDefaultCloseOperation(EXIT_ON_CLOSE);



ImageIcon i=(ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(new File(System.getenv("windir")+"\\notepad.exe"));

setIconImage(i.getImage());



setSize(400,400);

setVisible(true);

setLocationRelativeTo(null);

}



public static void main(String args[])

{

new WindowsIconForJFrame();

}

}

FileSystemView.getFileSystemView(): This method gets the FileSystemView object which contains the getSystemIcon() method which takes java.io.File as parameter. The file object is corresponded to the notepad.exe. To work with this program, make sure that you have notepad in your system.

setIconImage(i.getImage()): This method takes java.awt.Image which can be obtained using getImage() in javax.swing.ImageIcon class.

Notepad icon for JFrame

Related: How to set default system icons for JFileChooser?

Friday, 15 November 2013

Create an Advanced Chat Box in Java

The following example illustrates creating an advanced chat box in Java in Swing that detects whether the user is thinking or typing and displays the message accordingly. This chat box is just for demo purpose and it doesn't use any of the networking concepts to interact with the second person.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
class Chatbox extends JFrame
{
JPanel jp;
JTextField jt;
JTextArea ta;
JLabel l;
boolean typing;
Timer t;

    public Chatbox()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
   
        // Set frame properties
        setTitle("Chatbox");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Create a JPanel and set layout
        jp=new JPanel();
        jp.setLayout(new GridLayout(2,1));
        l=new JLabel();
        jp.add(l);
       
        // Create a timer that executes every 1 millisecond
        t=new Timer(1,new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // If the user isn't typing, he is thinking
                if(!typing)
                l.setText("Thinking..");
            }
        });
       
        // Set initial delay of 2000 ms
        // That means, actionPerformed() is executed 2500ms
        // after the start() is called
        t.setInitialDelay(2000);
       
        // Create JTextField, add it.
        jt=new JTextField();
        jp.add(jt);
       
       
        // Add panel to the south,
        add(jp,BorderLayout.SOUTH);
       
       
        // Add a KeyListener
        jt.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke)
            {
           
                // Key pressed means, the user is typing
                l.setText("You are typing..");
               
                // When key is pressed, stop the timer
                // so that the user is not thinking, he is typing
                t.stop();
               
                // He is typing, the key is pressed
                typing=true;
               
                // If he presses enter, add text to chat textarea
                if(ke.getKeyCode()==KeyEvent.VK_ENTER) showLabel(jt.getText());
            }
           
            public void keyReleased(KeyEvent ke)
            {
           
                // When the user isn't typing..
                typing=false;
               
                // If the timer is not running, i.e.
                // when the user is not thinking..
                if(!t.isRunning())
               
                // He released a key, start the timer,
                // the timer is started after 2500ms, it sees
                // whether the user is still in the keyReleased state
                // which means, he is thinking
                t.start();
            }
        });
       
        // Create a textarea
        ta=new JTextArea();
               
        // Make it non-editable
        ta.setEditable(false);
       
        // Set some margin, for the text
        ta.setMargin(new Insets(7,7,7,7));
       
        // Set a scrollpane
        JScrollPane js=new JScrollPane(ta);
        add(js);
       
        addWindowListener(new WindowAdapter(){
            public void windowOpened(WindowEvent we)
            {
                // Get the focus when window is opened
                jt.requestFocus();
            }
        });
       
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
    }
   
    private void showLabel(String text)
    {
        // If text is empty return
        if(text.trim().isEmpty()) return;
       
        // Otherwise, append text with a new line
        ta.append(text+"\n");
       
        // Set textfield and label text to empty string
        jt.setText("");
        l.setText("");
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new Chatbox();
            }
        });
    }
}

Chat box screenshot

Wednesday, 13 November 2013

How to move an undecorated JFrame?

The following example illustrates how to move an undecorated JFrame. As they don't move by default, we need to keep a component that acts like a titlebar, add a MouseListener and MouseMotionListener for it to listen to mousePressed and mouseDragged respectively and change the location accordingly. The logic  is going to be dead simple. And in this program, I'll be using a JMenuBar with the three buttons that act as minimize, maximize, close buttons. In this example, you'll learn:
  1. How to remove titlebar in JFrame?
  2. How to set JMenuBar as custom title bar and add buttons to it?
  3. How to minimize a JFrame and full screen it?
  4. How to set a custom look and feel?
  5. How to set fonts?
  6. How to set JFrame location and make it appear at center?
  7. How to set a rounded rectangle shape for JFrame?
Undecorated JFrame with custom JMenuBar

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CustomTitlebar extends JFrame
{
JPanel p;
JMenuBar mb;
JButton close,min,max;
Font f=new Font("Arial",Font.BOLD,24);
int pX,pY;

    public CustomTitlebar()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        // Custom look and feel
        try
        {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        }catch(Exception e){}
       
        setTitle("Custom Titlebar");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setUndecorated(true);       
       
        // Create JMenuBar
        mb=new JMenuBar();
        mb.setLayout(new BorderLayout());
       
        // Create panel
        p=new JPanel();
        p.setOpaque(false);
        p.setLayout(new GridLayout(1,3));
       
        // Create buttons
        min=new JButton("-");
        max=new JButton("+");
        close=new JButton("x");
       
        min.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // minimize
                setState(ICONIFIED);
            }
        });
       
        max.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                maximize();
            }
        });
       
        close.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // terminate program
                System.exit(0);
            }
        });
       
        // set focus painted false
        // i don't like it, so i removed it
        // if you like, you can remove these steps
        min.setFocusPainted(false);
        max.setFocusPainted(false);
        close.setFocusPainted(false);
       
        // font, again if you don't like you can
        // remove these steps, also remove the Font object
        min.setFont(f);
        max.setFont(f);
        close.setFont(f);
       
        // Add buttons
        p.add(close);
        p.add(max);
        p.add(min);
       
        // To west, mac style!
        mb.add(p,BorderLayout.WEST);
       
        // Add mouse listener for JMenuBar mb
        mb.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent me)
            {
                // Get x,y and store them
                pX=me.getX();
                pY=me.getY();
            }
        });
       
        // Add MouseMotionListener for detecting drag
        mb.addMouseMotionListener(new MouseAdapter(){
            public void mouseDragged(MouseEvent me)
            {
                // Set the location
                // get the current location x-co-ordinate and then get
                // the current drag x co-ordinate, add them and subtract most recent
                // mouse pressed x co-ordinate
                // do same for y co-ordinate
                setLocation(getLocation().x+me.getX()-pX,getLocation().y+me.getY()-pY);
            }
        });
       
        // Set the menu bar
        setJMenuBar(mb);
       
        // Set size, visibility,shape and center it
        setSize(400,400);
        setVisible(true);
        setShape(new java.awt.geom.RoundRectangle2D.Double(0,0,getWidth(),getHeight(),5,5));
        setLocationRelativeTo(null);
    }
   
    private void maximize()
    {
    // Get GraphicsEnvironment object for getting GraphicsDevice object
    GraphicsEnvironment env=GraphicsEnvironment.getLocalGraphicsEnvironment();
   
    // Get the screen devices
    GraphicsDevice[] g=env.getScreenDevices();
   
    // I only have one, the first one
    // If current window is full screen, set fullscreen window to null
    // else set the current screen
    g[0].setFullScreenWindow(g[0].getFullScreenWindow()==this?null:this);
    }
   
    public static void main(String args[])
    {
        new CustomTitlebar();
    }
}

In this way we can set a custom JMenuBar and make it act like the title bar by adding buttons to it. Next, using the MouseListener we can move the JFrame though it is undecorated.

Double Titlebar for JFrame in Swing

Yeah! I am excited to share this, a silly thing, but weird. Here is how to set a double titlebar for JFrame in swing, one comes with a default look and feel and the other is a normal title bar (based on OS). Now, just see the image before the program.

A JFrame with Double titlebar


import javax.swing.*;
import java.awt.*;
class DoubleTitleBar extends JFrame
{
JButton b;

    public DoubleTitleBar()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Double Title bar");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        b=new JButton("Button");
        add(b);
       
        setSize(400,400);
        setVisible(true);
   
        // This does the thing!!
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
    }
   
    public static void main(String args[])
    {
        new DoubleTitleBar();
    }
}

getRootPane().setWindowDecorationStyle(): This method takes an int which can be a FRAME, PLAIN_DIALOG etc and sets the window decoration style, i.e. styles the title bar. Also see using setDefaultLookAndFeelDecorated()

The greatest compliment you can give me is when you share this, I would sincerely appreciate it. :)

“The most beautiful things in the world cannot be seen or even touched, they must be felt with the heart” - Helen Keller

Sunday, 10 November 2013

How to add JCheckBox to JButton in Swing?

Screenshot of JCheckBox on JButton
Yeah! Adding JCheckBox to JButton is really gonna be simple, nothing more than 4 lines of code. Yes, it is. I said it right!! You need to check out the program, to know what is written over there. Three methods in JCheckBox you shouldn't forget are setOpaque(), setIcon() and setSelectedIcon(). Of course, there are other methods too which you must not forget, but these three are what we will be using here. And the beauty JButton stores the tiny JCheckBox in stomach.


import javax.swing.*;
import java.awt.*;
class JCheckBoxOnJButton extends JFrame
{
JCheckBox jc;
JButton jb;

    public JCheckBoxOnJButton()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JCheckBox on JButton");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
       
        jc=new JCheckBox("Check me");
       
        // Set non-opaque, so that background
        // isn't visible
        jc.setOpaque(false);
       
        // Set icon, selected icon (optional)
        jc.setIcon(new ImageIcon("unchecked.gif"));
        jc.setSelectedIcon(new ImageIcon("checked.gif"));
       
        // Just to remove text outline for JCheckBox
        jc.setFocusPainted(false);
       
        // Create JButton, with no text
        jb=new JButton();
       
        // Set a layout
        jb.setLayout(new GridBagLayout());
       
        // Add JCheckBox to JButton
        jb.add(jc);
       
       
        // Add the JButton
        add(jb);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JCheckBoxOnJButton();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“In every CHOICES that we choose, There's always a RISK; But always remember that there's also a chance” - Kent Solatorio Lopez

How to give JCheckBox a feel of Button?

Screenshot of JCheckBox having JButton feel
JCheckBox doesn't look like a JButton. Yes, of course, I do agree. But did you remember that JCheckBox is after all a sub-class of the AbstractButton and that this beautiful class has the setBorderPainted() with which we can play and do the thing like a mad kid?


import javax.swing.*;
import java.awt.*;
class JCheckBoxButton extends JFrame
{
JCheckBox jc;

    public JCheckBoxButton()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JCheckBox Content Area Filled");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        jc=new JCheckBox("Check/Uncheck me");
       
        // Quite big
        jc.setFont(new Font("Arial",Font.PLAIN,15));
       
        // Make it quite broad
        jc.setMargin(new Insets(5,5,5,5));
       
        // Set border painted!!
        jc.setBorderPainted(true);
       
        // Focus shouldn't be painted
        jc.setFocusPainted(false);
       
        // Set foreground, background
        jc.setForeground(Color.WHITE);
        jc.setBackground(Color.GRAY);
       
        // Add JCheckBox
        add(jc);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JCheckBoxButton();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Let there be no purpose in friendship save the deepening of the spirit.” - Kahlil Gibran

Add Image Preview Pane to JFileChooser

Screenshot of Image Preview JFileChooser
Let me show you how to add image preview pane to JFileChooser. This is very simple, you might be familiar with the code of showing an image in swing and adding custom component to JFileChooser. Let us combine these two now to add an Image Preview pane of the selected file in JFileChooser.

import javax.swing.*;
import java.awt.*;
import java.beans.*;
import javax.swing.filechooser.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.concurrent.*;
import java.awt.event.*;
class ImagePreviewJFileChooser extends JFrame
{
JLabel img;
JButton open;
JFileChooser jf=new JFileChooser();

    public ImagePreviewJFileChooser()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Image Preview for JFileChooser");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        // Create label
        img=new JLabel();
       
        // Let label come fatty!!
        img.setPreferredSize(new Dimension(175,175));
       
        // Set label as accessory
        jf.setAccessory(img);
       
        // Accept only image files
        jf.setAcceptAllFileFilterUsed(false);
       
        // Create filter for image files
        FileNameExtensionFilter filter=new FileNameExtensionFilter("Image Files","jpg","jpeg","png","gif");
       
        // Set it as current filter
        jf.setFileFilter(filter);

        // Add property change listener
        jf.addPropertyChangeListener(new PropertyChangeListener(){
       
            // When any JFileChooser property changes, this handler
            // is executed
            public void propertyChange(final PropertyChangeEvent pe)
            {
                // Create SwingWorker for smooth experience
                SwingWorker<Image,Void> worker=new SwingWorker<Image,Void>(){
               
                    // The image processing method
                    protected Image doInBackground()
                    {
                        // If selected file changes..
                        if(pe.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY))
                        {
                        // Get selected file
                        File f=jf.getSelectedFile();
                       
                            try
                            {
                            // Create FileInputStream for file
                            FileInputStream fin=new FileInputStream(f);
                           
                            // Read image from fin
                            BufferedImage bim=ImageIO.read(fin);
                           
                            // Return the scaled version of image
                            return bim.getScaledInstance(178,170,BufferedImage.SCALE_FAST);
                           
                            }catch(Exception e){
                                // If there is a problem reading image,
                                // it might not be a valid image or unable
                                // to read
                                img.setText(" Not valid image/Unable to read");
                            }
                        }
                   
                    return null;
                    }
                   
                    protected void done()
                    {
                        try
                        {
                        // Get the image
                        Image i=get(1L,TimeUnit.NANOSECONDS);
                       
                        // If i is null, go back!
                        if(i==null) return;
                       
                        // Set icon otherwise
                        img.setIcon(new ImageIcon(i));
                        }catch(Exception e){
                            // Print error occured
                            img.setText(" Error occured.");
                        }
                    }
                };
               
                // Start worker thread
                worker.execute();
            }
        });
       
        // Create JButton
        open=new JButton("Open File Chooser");
        add(open);
        open.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // Show open dialog
                jf.showOpenDialog(null);
            }
        });
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new ImagePreviewJFileChooser();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Friday, 8 November 2013

How to place JMenu at center of JMenuBar?

Till now, we have seen how to add JMenu to JMenuBar. Now, we'll be applying a simple hack that lets you place JMenu at the center of JMenuBar.

import javax.swing.*;
import java.awt.*;
class CenteredJMenu extends JFrame
{
JMenuBar mb;
JMenu m;
JMenuItem m1,m2;

    public CenteredJMenu()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Centered JMenu");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        mb=new JMenuBar();
        m=new JMenu("Menu");
        m1=new JMenuItem("Item 1");
        m2=new JMenuItem("Item 2");
        m.add(m1);
        m.add(m2);
        mb.add(m);
       
        // This does the thing!
        mb.setLayout(new GridBagLayout());
       
        setJMenuBar(mb);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new CenteredJMenu();
    }
}

Screenshot of JMenu placed at center