Friday, August 30, 2013

JTable

JTable component can be used to display and edit a two-dimensional table of cells. You can construct the JTable object for your data by using one of its constructors shown below.

Constructors of the JTable class:
-JTable()
creates an empty table with default data, column, and selection models.
-JTable(int rows, int columns)
creates an empty table with the specified number of rows and columsn using DefaultTableModel.
-JTable(Object[][] rowData, Object[] columnNames)
creates table with data in rows taken from the two-dimensional array, rowData and column names taken from the array, columnNames.
-JTable(TableModel dm)
creates table to display data of the TableModel, dm with default column and selection models.
-JTable(TableModel dm, TableColumnModel cm)
creates table to display data of the TableModel, dm with column names taken from TableColumnModel, cm and default selection model.
-JTable(TableModel dm, TableColumnModel cm, ListSelectionModel)
creates table to display data of the TableModel, dm with column names taken from TableColumnModel, cm, and selection model, sm.
-JTable(Vector rowData, Vector columnNames)
creates table to display data of the vector of vectors, rowData, and the column names,columnNames.

In the example below, data are retrieved from the SQLite database called sales.db. In the database, the tblcustomers table is created and sample data are inserted when the program initially runs. The DefaultTableModel, dm is created and some column names are added. Then The sample data are retrieved immediately to populate the DefaultTableModel, dm before it is added to the JTable, table object.

import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

class MainForm extends JFrame{
TableColumnModel colmodel;
DefaultTableModel model;
DataManager dm;
MainForm(){
//setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("JTable");
setSize(500,300);
setLayout(new FlowLayout());
dm=new DataManager();
//add sample data to the sqlite database
addSampleDataToDatabase();
//create data model for a table component
model=new DefaultTableModel();
//add column names to the model
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Sex");
model.addColumn("Address");
model.addColumn("Email");
model.addColumn("Phone");
//read sample data from the database and place them in the model
dm.getData(model);
//create a table object
JTable table = new JTable(model);
JScrollPane scrollpane = new JScrollPane(table);
    add(scrollpane);
 
   addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try {
dm.closeConnection();
} catch (SQLException se) {
se.printStackTrace();
}
System.exit(0);
}
});
   setVisible(true);

}

public void addSampleDataToDatabase(){
dm.insertSampleData(1, "Sok Chan","F","#444,st.933,Phnom Penh","sk.chan@gmail.com","855334543");
dm.insertSampleData(2, "Thida Vin","F","#23,st.103,Kampot","vin_thida@gmail.com","855135547");
dm.insertSampleData(3, "Chea Som","M","#476,st.883,Phnom Penh","chea_som@yahoo.com","855988454");

}


}

class DataManager {
Connection c = null;
Statement stm=null;
DataManager(){
try {

Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sales.db");
stm=c.createStatement();
String sql="CREATE TABLE tblcustomers(Id INT PRIMARY KEY, Name TEXT NOT NULL, Sex TEXT NOT NULL,"+
" Address TEXT NOT NULL, Email TEXT NOT NULL, Phone TEXT NOT NULL)";
stm.executeUpdate(sql);

} catch ( Exception e ) {
e.printStackTrace();
System.exit(0);
}
}
public void insertSampleData(int id,String name, String sex, String address,String email, String phone){
String sqlinsertion="INSERT INTO tblcustomers(Id,Name,Sex,Address,Email,Phone) VALUES("+id+",'"
+sex+"','"+name+"','"+address+"','"+email+"','"+phone+"')";
try{
stm.executeUpdate(sqlinsertion);
}catch(SQLException se){se.printStackTrace();}
}

public void getData(DefaultTableModel datamodel){
String sqlselection="SELECT * FROM tblcustomers";
try{
ResultSet result=stm.executeQuery(sqlselection);
if(result!=null){
while(result.next()){
datamodel.addRow(new Object[]{result.getInt("Id"),result.getString("Name"),result.getString("Sex"),result.getString("Address"),result.getString("Email"),result.getString("Phone")});
}
}

}catch(SQLException se){se.printStackTrace();}

}

public void closeConnection() throws SQLException{
stm.close();
c.close();
}
}

public class CusList{
public static void main(String[] args){
new MainForm();
}
}


DefaultTableCellRenderer class is used to paint the cells and format the values of the cells. The code fragment below applies red background color and bold font to all cells in even columns and light gray background color and normal font to all cells in odd columns of the table. You can apply a cell renderer object to a column of the table by using the setCellRenderer( TableCellRenderer cellRenderer) method of the table column object.

   TableColumn column = null;
   for (int i = 0; i < model.getColumnCount(); i++) {
       column = table.getColumnModel().getColumn(i);
       if(i%2==0){
        column.setPreferredWidth(100);
            MyCellRenderer cellRenderer=new MyCellRenderer(Color.RED, new Font("Arial",Font.BOLD,12));
            column.setCellRenderer(cellRenderer);
       }
       else
       {
        column.setPreferredWidth(100);
            MyCellRenderer cellRenderer=new MyCellRenderer(Color.LIGHT_GRAY,new Font("Arial",Font.PLAIN,12));
          column.setCellRenderer(cellRenderer);
       }
}

MyCellRenderer is a class that extends the DefaultTableCellRenderer class.

class MyCellRenderer extends DefaultTableCellRenderer {
  Color bgColor=null;
  Font font=null;
  public MyCellRenderer(Color c,Font f) {
  super();
  bgColor=c;
  font=f;
  }

    public void setValue(Object value) {
    setText(value.toString());
    setBackground(bgColor);
    setFont(font);
   
   }
}


Cell Render of JTable

By using the DefaultTableCellRender class, you can apply styles to the cells of a column or many columns. You can also use this class to style the column headers. However, you need to use the setHeaderRenderer
(TableCellRenderer render method) of a column object to specify the renderer for the columns. The below code fragment does this task.

     TableColumn column = null;
   MyHeaderRenderer headerRenderer=new MyHeaderRenderer

(Color.RED, new Font("Arial",Font.BOLD,15));
   
   for (int i = 0; i < model.getColumnCount(); i++) {    
       column = table.getColumnModel().getColumn(i);
       column.setHeaderRenderer(headerRenderer);
   }


MyHeaderRenderer is a class that extends the DefaultTableCellRenderer class.

class MyHeaderRenderer extends DefaultTableCellRenderer {
  Color bgColor=null;
  Font font=null;
  public MyHeaderRenderer(Color c,Font f) {
  super();
  bgColor=c;
  font=f;
  }

   public void setValue(Object value) {
    setText(value.toString());
    setBackground(bgColor);
    setFont(font);
   
   }
}

JTable style header


If don't want to allow cells editing in a column or you want to create your own editor for those cells, you can use the DefaultCellEditor to do these tasks. In the code fragment below, all cells in the first columns (index 0) are not allowed to edit. All cells in the third column (index 2) use a drop down list as its editor.

     TableColumn column = null;
   for (int i = 0; i < model.getColumnCount(); i++) {
       column = table.getColumnModel().getColumn(i);
       if(i==0){
        column.setPreferredWidth(100);
          JTextField txt=new JTextField();
            txt.setEditable(false);
          DefaultCellEditor editor=new DefaultCellEditor(txt);
            column.setCellEditor(editor);
       }
     
       else if(i==2)
       {
        column.setPreferredWidth(100);
        JComboBox box=new JComboBox();
        box.addItem("M");
            box.addItem("F");
            DefaultCellEditor editor=new DefaultCellEditor(box);
            column.setCellEditor(editor);
       }
   }

Cell Editor of JTable



Thursday, August 29, 2013

JFileChooser

JFileChooser is a component that you can use to display an open file dialog to select a file or many files for opening or to display a save file dialog to select a directory in which you can save text to a file.
To display a open file dialog, you need to use the showOpenDialog(Component parent) method of the JFileChooser object. By using its showSaveDialog(Component parent) method, you will have a save file dialog. Below are constructors and commonly used methods of the JFileChooser class.

Constructors of the JFileChooser class:
-JFileChooser()
creates a file chooser pointing to the user's current directory.
-JFile(File directory)
creates a file chooser pointing to the specified File path.
-JFile(String directory)
creates a file chooser pointing to the specified string path.

Useful methods of the JFileChooser class:
-getSelectedFile():File
return a selected file object.
-getSelectedFiles():File[]
returns all selected file objects. The user is able to select many files from the file chooser when set the multiselection property to true by using the setMultiSelectionEnabled(boolean b) method.
-setFileFilter(FileFilter filter):void
sets the file filter to the file chooser.
-setMultiSelectionEnabled(boolean b):void
allows single or mutiple files selection.
-showOpenDialog(Component parent):int
displays an open file dialog.
-showSaveDialog(Component parent):int
displays a save file dialog.


Example:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;

class JFileChooserShow extends JFrame{
JTextArea txta;
JFileChooserShow(String title){
setTitle(title);
setSize(550,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
JMenuItem itemnew=new JMenuItem(new AAction("New",new ImageIcon("d:/newicon.png")));
JMenuItem itemopen=new JMenuItem(new AAction("Open...",new ImageIcon("d:/openicon.png")));
JMenuItem itemsave=new JMenuItem(new AAction("Save as...",new ImageIcon("d:/saveicon.png")));
JMenuItem itemclose=new JMenuItem(new AAction("Exit",new ImageIcon("d:/closeicon.png")));
mfile.add(itemnew);
mfile.add(itemopen);
mfile.add(itemsave);
mfile.add(itemclose);
mbar.add(mfile);
setJMenuBar(mbar);
txta=new JTextArea(10,30);
txta.setLineWrap(true);
JScrollPane scroll=new JScrollPane(txta);
contpane.add(scroll,BorderLayout.CENTER);
setVisible(true);

}
class AAction extends AbstractAction{

AAction(String text){
super(text);

}

AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("New"))
txta.setText("");
else if(e.getActionCommand().equals("Open..."))
showFileDiag(false);
else if(e.getActionCommand().equals("Save as..."))
showFileDiag(true);
else if(e.getActionCommand().equals("Exit"))
System.exit(0);

}
}

public void showFileDiag(boolean save){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text (.*)","txt");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
int returnVal;

if(!save){
returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
readFile(file.toString());

}
}
else
{
returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
writeFile(file.toString());
}
}


}

public void readFile(String path){
txta.setText("");
try{
FileInputStream fs=new FileInputStream(path);
int data=0;
while((data=fs.read())!=-1){
char ch=(char)data;
txta.append(ch+"");
}
fs.close();
}catch(IOException ie){ie.printStackTrace();}
}
public void writeFile(String path){
try{
FileOutputStream fw=new FileOutputStream(path);
DataOutputStream ds=new DataOutputStream(fw);
String text=txta.getText();
ds.writeBytes(text);
ds.flush();
ds.close();
}catch(IOException ie){ie.printStackTrace();}
}

}

public class JFrameSwing {
public static void main(String[] args){
new JFileChooserShow("JFileChooser");
}
}

JFileChooser Open File dialog

JFileChooser Save File dialog

Wednesday, August 28, 2013

JColorChooser

JColorChooser represents a a dialog that you can manipulate and select a color value. JColorChooser object has its own model that handles color selection. This model can generate the change event. This event occurs when a color is selected. So you need to implement the ChangeListener interface to receive the event. Its useful constructors and methods are shown below.

Constructors:
-JColorChooser()
creates a color chooser without initial color.
-JColorChooser(Color c)
creates a color chooser with the initial color.
Methods:
-getColor():Color
gets the color from the color chooser.
-getSelectionModel():ColorSelectionModel
returns the model that handle the color selection.
-setColor(Color c):void
sets the color to the color chooser.
-showDialog(Component parent,String title, Color initColor): static Color displays the color-chooser dialog.

Example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.colorchooser.DefaultColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JColorChooserShow extends JFrame implements ChangeListener{
JLabel lbl;
JColorChooserShow(String title){
setTitle(title);
setSize(550,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JColorChooser chooser=new JColorChooser(Color.BLACK);
chooser.getSelectionModel().addChangeListener(this);
contpane.add(chooser,BorderLayout.NORTH);
lbl=new JLabel("Select a color to see the change",JLabel.CENTER);
lbl.setFont(new Font("Arial",Font.PLAIN, 30));
contpane.add(lbl,BorderLayout.CENTER);
setVisible(true);
}

public void stateChanged(ChangeEvent e){
DefaultColorSelectionModel model=(DefaultColorSelectionModel)e.getSource();
lbl.setForeground(model.getSelectedColor());

}

}
public class JFrameSwing {
public static void main(String[] args){
new JColorChooserShow("JColorChooser");
}
}

JColorChooser Swing


If you want to display a color chooser in a separate widow, you need to use the showDialog(Component parent, String title,Color initColor) method. It is a static method. So, you no need to create an instance of the JColorChooser. This method returns the color that is selected.

Example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

class JColorChooserShow extends JFrame{
JTextArea txta;
JColorChooserShow(String title){
setTitle(title);
setSize(550,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JButton btcolor=new JButton(new AAction("",new ImageIcon("d:/coloricon.png")));
btcolor.setBackground(Color.WHITE);
JPanel p=new JPanel(new FlowLayout(FlowLayout.LEFT));
p.add(btcolor);
contpane.add(p,BorderLayout.NORTH);
txta=new JTextArea(10,30);
txta.setLineWrap(true);
JScrollPane scroll=new JScrollPane(txta);
contpane.add(scroll,BorderLayout.CENTER);
setVisible(true);

}
class AAction extends AbstractAction{

AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(null, "Select a color", Color.BLACK);
txta.setForeground(c);
}
}

}

public class JFrameSwing {
public static void main(String[] args){
new JColorChooserShow("JColorChooser");
}
}

Tuesday, August 27, 2013

JToolBar

JToolBar is a container that can be used to display commonly used controls in a program. You can drag and drop the JToolBar in a location of the window or drag it out into a separate window.  The summary of the JToolBar constructors and useful methods are shown below.

Constructors of the JToolBar class:
-JToolBar()
creates a horizontal tool bar without name;
-JToolBar(String name)
creates a horizontal tool bar with the specified name.
-JToolBar(int orient)
creates a tool bar with the specified orientation.
-JToolBar(String name, int orient)
creates a tool bar with the specified name, and orientation.

Useful methods of the JToolBar class:
-add(Action action):JButton
adds a new JButton to the tool bar.
-add(Component c):Component
adds a new component to the tool bar.
-addSeparator():void
adds the separator to the tool bar to separate its components.
-setFloatable(boolean float):boolean
allows or does not allow the tool bar to be moved or dragged.

Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

class JToolBarShow extends JFrame implements ItemListener{
JTextArea txta;
JComboBox cbfontnames;
JComboBox cbfontsizes;
JComboBox cbfontcolors;
JToolBarShow(String title){
setTitle(title);
setSize(550,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
JMenuItem itemnew=new JMenuItem(new AAction("New",new ImageIcon("d:/newicon.png")));
mfile.add(itemnew);
JMenuItem itemclose=new JMenuItem(new AAction("Close",new ImageIcon("d:/closeicon.png")));
mfile.add(itemclose);
mbar.add(mfile);
setJMenuBar(mbar);
txta=new JTextArea(10,30);
JScrollPane scroll=new JScrollPane(txta);
JToolBar toolbar=new JToolBar();
toolbar.add(new JButton(new AAction("Copy",new ImageIcon("d:/copyicon.png"))));
toolbar.add(new JButton(new AAction("Paste",new ImageIcon("d:/pasteicon.png"))));
toolbar.add(new JButton(new AAction("Wrap",new ImageIcon("d:/wrapicon.png"))));
cbfontnames=new JComboBox(fnames());
cbfontsizes=new JComboBox(sizes());
cbfontcolors=new JComboBox(colors());
cbfontnames.addItemListener(this);
cbfontsizes.addItemListener(this);
cbfontcolors.addItemListener(this);
toolbar.add(cbfontnames);
toolbar.add(cbfontsizes);
toolbar.add(cbfontcolors);
toolbar.setFloatable(true);
contpane.add(scroll,BorderLayout.CENTER);
contpane.add(toolbar,BorderLayout.SOUTH);
cbfontnames.setSelectedItem("Arial");
cbfontsizes.setSelectedItem(12);
cbfontcolors.setSelectedItem(0);
validate();

}
class AAction extends AbstractAction{

AAction(String text){
super(text);

}

AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("New"))
txta.setText("");

else if(e.getActionCommand().equals("Close"))
System.exit(0);
else if(e.getActionCommand().equals("Wrap"))
{
if(txta.getLineWrap()==false)
txta.setLineWrap(true);
else
txta.setLineWrap(false);
}
else if(e.getActionCommand().equals("Copy"))
txta.copy();
else if(e.getActionCommand().equals("Paste"))
txta.paste();
}
}

public void itemStateChanged(ItemEvent e){
setFontToTextArea(cbfontnames.getSelectedItem(),cbfontcolors.getSelectedItem(),cbfontsizes.getSelectedItem());
}

public String[] fnames(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
return ge.getAvailableFontFamilyNames();

}
public Object[] sizes(){
Object[] fsizes={8,9,10,11,12,13,14,15,16,17,18,19,20,30,31,32,33,36,40,45};
return(fsizes);
}

public Object[] colors(){
Object[] tcolor={0x000000,0xfffff,0xffff00,0xff0000,0xff00ff};
return(tcolor);
}

public void setFontToTextArea(Object fname,Object fcolor,Object fsize){
String fontname=fname.toString();
Color forecolor=new Color(Integer.parseInt(fcolor.toString()));
int fontsize=Integer.parseInt(fsize.toString());
txta.setFont(new Font(fontname,Font.PLAIN,fontsize));
txta.setForeground(forecolor);
}

}

public class JFrameSwing {
public static void main(String[] args){
new JToolBarShow("JToolBar");
}
}

JToolBar Swing

Monday, August 26, 2013

JCheckBoxMenuItem

JCheckBoxMenuItem component can used to implement check boxes as the menu items. You can select many checkbox menu items. When you select a check box, menu item displays a check mark. Deselecting the item clears the check mark. Like a menu item, checkbox menu item can display text, icon, and both. Below are constructors that can be used to create a checkbox menu item.

-JCheckBoxMenuItem()
creates a checkbox menu item without text or icon.
-JCheckBoxMenuItem(Action action)
creates a checkbox menu item that its properties are taken from the Action object.
-JCheckBoxMenuItem(Icon icon)
creates a checkbox menu item with the specified icon.
-JCheckBoxMenuItem(String text)
creates a checkbox menu item with the specified text.
-JCheckBoxMenuItem(String text,boolean selected)
creates a checkbox menu item with the specified text and selection state.
-JCheckBoxMenuItem(String text,Icon icon)
creates a checkbox menu item with the specified text and icon.
-JCheckBoxMenuItem(String text,Icon icon,boolean selected)
creates check menu item with the specified text, icon, and selection state.

In the example program below, a menu bar is created using the JMenuBar class. On this menu bar, we place a menu called Format. In the menu Format, there is one checkbox menu item. When the user select this checkbox menu item, the text in the JTextArea will be wrapped.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JCheckBoxMenuItemShow extends JFrame implements ChangeListener{
JTextArea txta;
JCheckBoxMenuItemShow(String title){
setTitle(title);
setSize(400,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JMenuBar mbar=new JMenuBar();
JMenu format=new JMenu("Format");
JCheckBoxMenuItem itemlinewrap=new JCheckBoxMenuItem("Line wrap");
itemlinewrap.setSelected(true);
format.add(itemlinewrap);
mbar.add(format);
setJMenuBar(mbar);
txta=new JTextArea(10,30);
JScrollPane scroll=new JScrollPane(txta);
contpane.add(scroll,BorderLayout.CENTER);
setVisible(true);

}

public void stateChanged(ChangeEvent e){
JCheckBoxMenuItem chm=(JCheckBoxMenuItem)e.getSource();
if(chm.getState()==true)
txta.setLineWrap(true);
else
txta.setLineWrap(false);
}

}

public class JFrameSwing {
public static void main(String[] args){
new JCheckBoxMenuItemShow("JCheckBoxMenuItem");
}
}

JCheckBoxMenuItem Swing

Sunday, August 25, 2013

JRadioButtonMenuItem

JRadioButtonMenuItem represents a radio button menu item. You can place radio button menu items in a group by using the ButtonGroup class. In the group only one menu item can be selected. You can add radio button menu items in the same way as you add the normal menu items to the menu object.

Constructors of the JRadioButtonMenuItem class:
-JRadioButtonMenuItem()
creates a radio button menu item without text or icon.
-JRadioButtonMenuItem(Action action)
creates a radio button menu item that its properties are taken from the Action object. The action of the menu item also can be specified with this Action object.
-JRadioButtonMenuItem(Icon icon)
creates a radio button menu item with the specified icon.
-JRadioButtonMenuItem(String text)
creates a radio button menu item with the specified text.
-JRadioButtonMenuItem(String text, boolean selected)
creates a radio button menu item with the specified text and selection state.
-JRadioButtonMenuItem(String text,Icon icon)
creates a radio button menu item with the specified text and icon.
-JRadioButtonMenuItem(String text,Icon icon,boolean selected)
creates a radio button menu item with the specified text, icon, and selection state.

In the example program below, we have two menus-File and Window. The File menu has two items-New and Close. These menu items are normal. The Window menu has two menu items too-Minimize and Maximize. These menu items are RadioButton menu items. They are grouped in a RadioButton so that only one item can be selected at a time. The AbstractAction class is extended to define the text property and action of each RadioButton menu item. The window can be minimized or maximized by selecting the Minimize or Maximize menu item.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
class JRadioButtonMenuItemShow extends JFrame{
JMenu mfile;
JMenu mwin;
JMenuItem itemnew;
JMenuItem itemclose;
JRadioButtonMenuItem itemmax;
JRadioButtonMenuItem itemmin;

JRadioButtonMenuItemShow(String title){
setTitle(title);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
addWindowListener(new WinList());
setVisible(true);
JMenuBar mbar=new JMenuBar();
mfile=new JMenu("File");
mfile.setMnemonic(KeyEvent.VK_F);
itemnew=new JMenuItem(new AAction("New"));
itemclose=new JMenuItem(new AAction("Close"));
mfile.add(itemnew);
mfile.add(itemclose);
mwin=new JMenu(new AAction("Window"));
mwin.setMnemonic(KeyEvent.VK_W);
ButtonGroup bg=new ButtonGroup();
itemmax=new JRadioButtonMenuItem(new AAction("Maximize"));
itemmax.setSelected(true);
itemmin=new JRadioButtonMenuItem(new AAction("Minimize"));
bg.add(itemmax);
bg.add(itemmin);
mwin.add(itemmax);
mwin.add(itemmin);
mbar.add(mfile);
mbar.add(mwin);
   setJMenuBar(mbar);
   validate();
}


class AAction extends AbstractAction{

AAction(String text){
super(text);

}

AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Close"))
System.exit(0);
else if(e.getActionCommand().equals("Maximize"))
setExtendedState(JFrame.MAXIMIZED_BOTH);
else if(e.getActionCommand().equals("Minimize"))
setExtendedState(JFrame.ICONIFIED);
}
}
class WinList extends WindowAdapter{
public void windowIconified(WindowEvent e){
itemmin.setSelected(true);
}
public void windowDeiconified(WindowEvent e){
itemmax.setSelected(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}

}

public class JFrameSwing {
public static void main(String[] args){
new JRadioButtonMenuItemShow("JRadioButtonMenuItem");
}
}
JRadioButtonMenuItem Swing

Saturday, August 24, 2013

JMenu

JMenu represents a menu that contains menuitems. Menus (created by JMenu class) are added to a menu bar object (created by JMenuBar class) by using the add(JMenu menu) method of the menu bar object. MenuItems (created by JMenuItem class) are added to a menu object by using the add(JMenuItem item) method of the menu object. When a menu of the menu bar is selected, menuitems of the menu are displayed.

A menu or menuitem can associate with an action through its constructor or by using its setAction(Action action) method. A direct class that implements the Action interface is AbstractAction. You can extends the AbstractAction class to determine the properties (text and icons) and actions of the menus or menuitems.

Constructors of the JMenu class:
-JMenu()
creates a menu without text.
-JMenu(String text)
creates a menu with text.
-JMenu(Action action)
creates a menu with its properties and action defined by Action object.

Useful methods of the JMenu class:
-add(Action item):JMenuItem
adds an menu item that its properties and action are specified by the Action object to the menu.
-add(JMenuItem item):JMenuItem
adds a menu item to the menu.
-addSeparator():void
separates the menu items of the menu.
-insert(JMenuItem,int post):void
inserts a menu item to the menu at the specified position.

Example:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
class JMenuShow extends JFrame{
JMenuShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
setVisible(true);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic(KeyEvent.VK_F);
JMenuItem item0=new JMenuItem("New");
mfile.add(item0);
JMenu item1=new JMenu(new AAction("Window"));
JMenuItem subitem0=new JMenuItem(new AAction("Close",new ImageIcon("d:/closeicon.png")));
JMenuItem subitem1=new JMenuItem(new AAction("Minimize",new ImageIcon("d:/minicon.png")));
item1.add(subitem0);
item1.add(subitem1);
mfile.add(item1);
mbar.add(mfile);
   setJMenuBar(mbar);
   validate();
}


class AAction extends AbstractAction{

AAction(String text){
super(text);

}
AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Close"))
System.exit(0);
else if(e.getActionCommand().equals("Minimize"))
setExtendedState(JFrame.ICONIFIED);
}
}


}

public class JFrameSwing {
public static void main(String[] args){
new JMenuShow("JMenu");
}
}

JMenu JMenuBar

JPopupMenu

JPopupMenu represents a popup menu. A popup menu is a small window that displays a list of choices. A popup menu can appear at any locaiton that you specified on a component. For example, a popup menu of choices is shown on the window where the user right-clicked the window.

Constructors of the JPopupMenu class:
-JPopupMenu()
creates a popup menu.
-JPopupMenu(String label)
creates a popup menu with the title.

Useful methods of the JPopupMenu class:
-add(Action a):JMenuItem
adds an menu item that its properties and action are specified by the Action object to the popup menu.
-add(String item):JMenuItem
adds a menu item to the popup menu.
-setVisible(boolean visible):void
sets the visibility of popup menu.
-show(Component c,int x,int y):void
displays the popup menu at the specified coordiate (x,y) of the component c.

In the example code below, the MouseListener is registered withe the JFrame window to listen to the mouse pressed event. The JPopupMenu is created with two items-Close and Minimize. The Close menu item is clicked to close the window and the Minimize item will minimize the window.  We determine the text properties and actions of the Close and Minimize menu items by using the AbstactAction classs. This class is extended by the AAction class. The instances of the AAction class are attached to the menu items.
When the user right-clicks the window, the popup menu displays at the clicked point on the window. To detect whether the right button of the mouse is pressed, you need to use the getButton method of the MouseEvent class. This method returns a value that is equivalent to the button of the mouse that is pressed. The left button will be MouseEvent.BUTTON1, the middle button MouseEvent.BUTTON2, and the MouseEvent.BUTTON3 for the right button.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;

import javax.swing.JPopupMenu;

class JPopupMenuShow extends JFrame{
JPopupMenu pmenu;
JPopupMenuShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
contpane.addMouseListener(new MouseA());
setVisible(true);
pmenu=new JPopupMenu();
pmenu.add(new AAction("Close"));
pmenu.addSeparator();
pmenu.add(new AAction("Minimize"));

}

class MouseA extends MouseAdapter{
public void mousePressed(MouseEvent e){
if(e.getButton()==MouseEvent.BUTTON3)
pmenu.show(getContentPane(),e.getX(),e.getY());
}
}
class AAction extends AbstractAction{

AAction(String text){
super(text);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Close"))
dispose();
else if(e.getActionCommand().equals("Minimize"))
setExtendedState(JFrame.ICONIFIED);
}
}


}

public class JFrameSwing {
public static void main(String[] args){
new JPopupMenuShow("JPopupMenu");
}
}
JPopupMenu Swing

JProgressBar

JProgressBar is a component to visually display the progress of a task. The progress bar displays the percentage of the task completed. It starts with an empty rectangle. Then the rectangle is filled in gradually toward the complete state of the task.

Constructors of the JProgressBar class:
-JProgressBar()
creates a progress bar.
-JProgressBar(BoundedRangeModel model)
creates a progress bar with its data are taken from the model.
-JProgressBar(int min, max)
creates a progress bar with the specified minimum and maximum values.
-JProgressBar(int orent,int min,int max)
creates a progress bar with the specified orientatin, minimum and maximum values.

Useful methods of the JProgressBar class:
-getValue():int
returns the current value of the progress bar.
-isIndeterminate():boolean
returns true if the progress bar is indeterminate state.
-setIndeterminate(boolean value):void
allows the progress bar in determinate or indeterminate state.
-setStringPainted(boolean painted):void
Shows or deos not show the string representing the percentage of the work progress.
-setValue(int value):void
sets the current value of the progress bar.

In the example program below, the progress bar is created to show the progress of retrieving available font names from the system. The DefaultRoundedRangleModel class is used to define the current value, extent value, an min and max values of the progress bar. The Thread.sleep(50) delays each progress step 50 milliseconds to ensure the progress is visible.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JProgressBarShow extends JFrame{
JLabel lbl;
JProgressBarShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
setVisible(true);
JPanel p=new JPanel();
p.setLayout(new GridLayout(2,1));
BoundedRangeModel model=new DefaultBoundedRangeModel(0,1,0,100);
String[] fn=fnames();
model.setMinimum(0);
model.setMaximum(fn.length);
model.setExtent(1);
JProgressBar pbar=new JProgressBar(model);
pbar.setForeground(Color.BLUE);
pbar.setStringPainted(true);
p.add(pbar);
lbl=new JLabel("Please wait...");
lbl.setForeground(Color.RED);
p.add(lbl);
contpane.add(p, BorderLayout.NORTH);
validate();
DefaultListModel lmodel=new DefaultListModel();
for(String n:fn){
lmodel.addElement(n);
pbar.setValue(pbar.getValue()+1);
try{
Thread.sleep(50);
}catch(InterruptedException ie){}
}
lbl.setText("Complete");
JList fontlist=new JList(lmodel);
contpane.add(fontlist,BorderLayout.CENTER);
validate();

}

public String[] fnames(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
return ge.getAvailableFontFamilyNames();

}



}

public class JFrameSwing {
public static void main(String[] args){
new JProgressBarShow("JProgressBar");
}
}

JProgressBar task in progressing

JProgressBar complete task