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

How to create a transparent frame in Java ?

In a GUI programming at some point the transparent windows are very much in need. The transparent frames are mostly used to show some less important content to users. It is basically a JFrame with faded color. It can also used in creating some widget in a very large application. Here is a code snippet.

import javax.swing.JFrame;
import java.awt.Color;

public class TransparentDemo extends JFrame{
public TransparentDemo(){
setSize(200, 200);

/***
* To make a JFrame transparent this method needs to be set to true
* if this method is not set to true this will throw an exception
* java.awt.IllegalComponentStateException
*/

setUndecorated(true);

/***
* The Transparency of the frame is mainly done with the help of
  * class Color of the package java.awt
* there are 3 arguments of the construction first 3 args are of
  * color red, green, and blue and the
* the last 4th argument is called opacity which is an integeral
  * number raging from 0 to 100 which
* will improve the opacity from 100 to 0 means 0 will be no
  * background and 100 will be pure 
* background with color.
*/
setBackground(new Color(10,200,255,90));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new TransparentDemo().setVisible(true);
}
}

Type the above code in notepad or any editor and run it.

Gujarati Typing in Java Application

This Example shows how to use the 3rd party font (.ttf) in our java application. This sometime need when we want to use strictly to some of the other languages like Gujarati, etc. We just need to have a .ttf(True Type Font) file which is need to be loaded by programming in our application.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.awt.Font;
import java.awt.FontFormatException;

class GujaratiType extends JFrame
{
public Font font,fontUsed;
public GujaratiType()
{
try
{
InputStream myStream = new BufferedInputStream(new FileInputStream("LMG_LAX1.ttf"));
font = Font.createFont(Font.TRUETYPE_FONT, myStream);
fontUsed = font.deriveFont(Font.PLAIN,20);
}
catch(FontFormatException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,ex,"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,"System can not find the file : LMG_LAX1.TTF","Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
JTextArea txt = new JTextArea();
txt.setFont(fontUsed);
JScrollPane jsp = new JScrollPane(txt);
add(jsp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0,0,300,300);
//setSize(300,300);
setVisible(true);
}
public static void main(String[] a)
{
new GujaratiType();
}
}

Example of JTabbedPane

Sometime we need to have something like multiple tabs like in chrome we have. So here i am posting a simple example of JTabbedPane which may help you in any way.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class TabDemo extends JFrame
{
JTabbedPane tb;
JTextArea txt;
private int tabCounter = 1;
public TabDemo()
{
tb = new JTabbedPane();
addTab();
setJMenuBar(createMenuBar());
getContentPane().add(tb,BorderLayout.CENTER);
//addTab();
setVisible(true);
setBounds(20,20,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JMenuBar createMenuBar()
{
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newFile = new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke('N',KeyEvent.CTRL_DOWN_MASK));
newFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addTab();
}
});
JMenuItem saveFile = new JMenuItem("Save");
saveFile.setAccelerator(KeyStroke.getKeyStroke('S',KeyEvent.CTRL_DOWN_MASK));
saveFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int x = tb.getSelectedIndex();
JScrollPane jsp = (JScrollPane)tb.getComponentAt(x);
JTextArea tx = (JTextArea) jsp.getViewport().getView();
//JOptionPane.showMessageDialog(TabDemo.this,tx.getText());
fileSaver(tx.getText());
}
});
file.add(newFile);
file.add(saveFile);
mb.add(file);
return mb;

}
void addTab()
{
txt = new JTextArea();
JScrollPane txtPnl = new JScrollPane(txt);
JPanel tbPnl = new JPanel();
tbPnl.setOpaque(false);
tbPnl.setLayout(new FlowLayout());
JLabel lbl = new JLabel("Tab - "+tabCounter);
JButton btnClose = new JButton("X");
tbPnl.add(lbl);
tbPnl.add(btnClose);
tb.addTab(null,txtPnl);
btnClose.setActionCommand(""+tabCounter);
btnClose.setFont(new Font("Serif",1,9));
lbl.setFont(new Font("Serif",1,9));
btnClose.setOpaque(false);
btnClose.setBorder(null);
btnClose.setBackground(Color.RED);
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton btn =(JButton) e.getSource();
String str = btn.getActionCommand();
for(int i =0 ;i <tb.getTabCount();i++)
{
JPanel pnl = (JPanel)tb.getTabComponentAt(i);
btn = (JButton)pnl.getComponent(1);
String str2 = btn.getActionCommand();
if(str.equals(str2))
{
tb.removeTabAt(i);
tabCounter--;
break;
}
}
}
};
btnClose.addActionListener(al);

//tb.setTabComponentAt(tb.getTabCount()-1 ,lbl);
tb.setTabComponentAt(tb.getTabCount()-1 , tbPnl);
tb.setSelectedIndex(tb.getTabCount() - 1);
tabCounter++;
}
public static void main(String []args)
{
new TabDemo();
}
private void fileSaver(String text)
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showSaveDialog(TabDemo.this);

/*if(result != JFileChooser.APPROVE_OPTION)
{ return false; }*/
File file = chooser.getSelectedFile();
setTitle(file.getName());

try
{
FileOutputStream out = new FileOutputStream(file);
//String str = txt.getText();
byte b[] = text.getBytes();
out.write(b);
out.close();
//return true;
}
catch(Exception ex){}//return false;}
}
}

Now Type the above code in text editor save it as TabDemo.java.
Then compile it by command javac TabDemo.java
and execute it by command java TabDemo

Default and Escape Button in Java

We may sometimes need to have that when we press the enter key it automatically performs some tasks.
And when we press the escape key it automatically exits the application or like else.
So here is a simple example to do so.

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;

public class DefaultEscapeButton extends JFrame
{
JButton btn1,btn2;
        //Preparing ActionListener for escape key pressed
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
DefaultEscapeButton()
{
setLayout(null);
btn1 = new JButton("Default");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println(btn1.getText());
}
});
btn1.setBounds(10,10,150,30);
btn2 = new JButton("Cancel");
btn2.setBounds(10,50,150,30);
                //This is the code for when Escape key is pressed
getRootPane().registerKeyboardAction(al,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);


add(btn1);
add(btn2);
getRootPane().setDefaultButton(btn1);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new DefaultEscapeButton();
}
}

Add Button in Tab of JTabbedPane

There are lots of things we can do in the desktop application using java's swing technology. One of  which here is adding a button to the Tab for some help user to closing the tab, etc. This kind of example can help to build some application having facility for multiple infinite tab like Browser application, or a kind of text editor, etc.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class AddButtonToTabBar extends JFrame {
private JTabbedPane tp;
private int tabCounter = 0;

public AddButtonToTabBar() {
super("Editor");
setDefaultCloseOperation(EXIT_ON_CLOSE);

JToolBar jtb = new JToolBar();
JButton btnAdd = new JButton("Add Tab");
ActionListener addTabl = new ActionListener() {
 public void actionPerformed(ActionEvent e) {
addTab();
 }
};
btnAdd.addActionListener(addTabl);
jtb.add(btnAdd);

JPanel pnlURL = new JPanel();
tp = new JTabbedPane();
addTab();
getContentPane().add(jtb, BorderLayout.NORTH);
getContentPane().add(tp, BorderLayout.CENTER);

setSize(700, 700);
setVisible(true);
}

void addTab() {
// A Simple Text editor
JEditorPane ep = new JEditorPane();
ep.setEditable(true);
tp.addTab("Tab - " + tabCounter, new JScrollPane(ep));

//Preparing a button to add 
JButton tabCloseButton = new JButton("X");
tabCloseButton.setActionCommand("" + tabCounter);

//ActionListener for what to do when the button is clicked, here is to close the particular tab
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JButton btn = (JButton) ae.getSource(); // It will get the button object which is clicked
String s1 = btn.getActionCommand();
for (int i = 1; i < tp.getTabCount(); i++) {
JPanel pnl = (JPanel) tp.getTabComponentAt(i); // It will return the whole component which we had set in the Tab

// It will get the button component. The parameter for the getComponent 
// is index of the total number of component. Here 1 means the button and 0 means the lable.
btn = (JButton) pnl.getComponent(1);
String s2 = btn.getActionCommand();
if (s1.equals(s2)) {
tp.removeTabAt(i);
break;
}
}
}
};
tabCloseButton.addActionListener(al);

// This condition is to make at least one tab to be in the application.
if (tabCounter != 0) {
JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.add(new JLabel("Tab - "+tabCounter));
pnl.add(tabCloseButton);
tp.setTabComponentAt(tp.getTabCount() - 1, pnl);
tp.setSelectedIndex(tp.getTabCount() - 1);
}
tabCounter++;
}

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

}
}

Write the above program, save it as AddButtonToTabBar.java , compile it and run it.