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

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

Monday, 11 November 2013

Using GlassPane to block input in JFrame

Using GlassPane to block input in JFrame
Since time, I have been stumped of how to use glass pane even when seeing the tutorial. Now, here is an example on how to use GlassPane to block input in JFrame by creating a transparent black background for that GlassPane with a busy symbol as if some data is being processed. When the user clicks any where on the JFrame when processing the data then a beep sound is played.



import javax.swing.*;


import java.awt.*;


import java.awt.event.*;


class BlockInput extends JFrame


{


JButton b;





public BlockInput()


{


createAndShowGUI();


}




private void createAndShowGUI()


{


setTitle("Block input");


setLayout(new FlowLayout());


setDefaultCloseOperation(EXIT_ON_CLOSE);




// Create JButton


b=new JButton("Block input");


add(b);




b.addActionListener(new ActionListener(){


public void actionPerformed(ActionEvent ae)


{


// Create a JPanel with semi-transparent


// black background


// This will be glass pane


JPanel p=new JPanel(){


public void paintComponent(Graphics g)


{


g.setColor(new Color(0,0,0,140));


g.fillRect(0,0,getWidth(),getHeight());


}


};




// Set it non-opaque


p.setOpaque(false);




// Set layout to JPanel


p.setLayout(new GridBagLayout());




// Add the jlabel with the image icon


p.add(new JLabel(new ImageIcon("loading.gif")));




// Take glass pane


setGlassPane(p);




// Add MouseListener


p.addMouseListener(new MouseAdapter(){


public void mousePressed(MouseEvent me)


{


// Consume the event, now the input is blocked


me.consume();




// Create beep sound, when mouse is pressed


Toolkit.getDefaultToolkit().beep();


}


});




// Make it visible, it isn't by default because


// it is set as glass pane


p.setVisible(true);


}


});




setSize(400,400);


setVisible(true);


setLocationRelativeTo(null);


}




public static void main(String args[])


{


new BlockInput();


}


}

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


“Genius is 1% inspiration 99% perspiration” - Thomas Alva Edison