Labels:
javax.swing.JLabel
A display area for a short text string or an image, or both. A label does not react to input events. As a result, it cannot get the keyboard focus.
|
Constructors |
|
|
JLabel() |
Creates a JLabel instance with no image and with an empty string for the title. |
|
Creates a JLabel instance with the specified image. |
|
|
Creates a JLabel instance with the specified image and horizontal alignment. |
|
|
Creates a JLabel instance with the specified text. |
|
|
Creates a JLabel instance with the specified text, image, and horizontal alignment. |
|
|
Creates a JLabel instance with the specified text and horizontal alignment. |
|
|
Methods |
|
|
String getText() |
Returns the text string that the label displays. |
|
Defines the single line of text this component will display. |
|
|
Icon getIcon() |
Returns the graphic image (glyph, icon) that the label displays. |
|
Defines the icon this component will display. |
|
|
int getVerticalTextPosition() |
Returns the vertical position of the label’s text, relative to its image. |
|
(int textPosition) |
Sets the vertical position of the label’s text, relative to its image. |
ImageIcon
javax.swing.ImageIcon
The ImageIcon class defines objects representing small fixed-size pictures that are used typically to decorate components. This class implements the Icon interface.
|
Constructors |
|
|
Creates an uninitialized image icon. |
|
|
ImageIcon(byte[] imageData) |
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF or JPEG. |
|
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF or JPEG. |
|
|
Creates an ImageIcon from an image object. |
|
|
Creates an ImageIcon from the image. |
|
|
Creates an ImageIcon from the specified file. |
|
|
Creates an ImageIcon from the specified file. |
|
|
Creates an ImageIcon from the specified URL. |
|
|
Creates an ImageIcon from the specified URL. |
|
|
Methods |
|
|
Image getImage() |
Returns this icon’s Image. |
|
Sets the image displayed by this icon. |
|
|
int getIconHeight() |
Gets the height of the icon. |
|
int getIconWidth() |
Gets the width of the icon. |
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame
{
public JFrameDemo()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
ImageIcon ii = new ImageIcon(“bulg.jpg”);
JLabel jl1 = new JLabel(“Image”, ii, JLabel.CENTER);
jl1.setVerticalTextPosition(JLabel.BOTTOM);
jl1.setHorizontalTextPosition(JLabel.CENTER);
cp.add(jl1); setTitle(“Demo”);
//setSize(300,500);
//setLocation(150,250);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new JFrameDemo();
}
}
Text Entry Components:
Swing provides several such components from the most basic single-line text field to the sophisticated multi-line components that understand and support HTML and RTF. Swing also provides a convenient class of entry fields specifically suited for entering passwords.
JTextField JPasswordField
JTextComponent JTextArea
JEditorPane JTextPane
JTextComponent
javax.swing.JTextComponent
JTextComponent is the base class for swing text components.
|
Constructor |
|
|
Creates a new JTextComponent. |
|
|
Methods |
|
|
String getText() |
Returns the text contained in this TextComponent. |
|
String getText(int offs, int len) |
Fetches a portion of the text represented by the component. |
|
Sets the text of this TextComponent to the specified text. |
|
|
void setEditable(boolean b) |
Sets the specified boolean to indicate whether or not this TextComponent should be editable. |
|
void selectAll() |
Selects all the text in the TextComponent. |
|
void select(int selectionStart, int selectionEnd) |
Selects the text between the specified start and end positions. |
JTextField
javax.swing.JTextField
JTextField is a lightweight component that allows the editing of a single line of text.
|
Constructors |
|
|
Constructs a new TextField. |
|
|
JTextField(Document doc, String text, int columns) |
Constructs a new JTextField that uses the given text storage model and the given number of columns. |
|
JTextField(int columns) |
Constructs a new empty TextField with the specified number of columns. |
|
JTextField(String text) |
Constructs a new TextField initialized with the specified text. |
|
JTextField(String text, int columns) |
Constructs a new TextField initialized with the specified text and columns. |
|
Methods |
|
|
void addActionListener(ActionListener l) |
Adds the specified action listener to receive action events from this textfield. |
|
Sets the current font. |
|
|
void setColumns(int columns) |
Sets the number of columns in this TextField. |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FullName extends JFrame implements ActionListener
{
JLabel l1,l2;
JTextField txtfn,txtln,txtfull;
JButton b1,b2;
public FullName()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel(“Enter First name:”);
l2=new JLabel(“Enter Last name:”);
txtfn=new JTextField(20);
txtln=new JTextField(20);
txtfull=new JTextField(50);
txtfull.setEditable(false);
b1=new JButton(“Submit”);
b2=new JButton(“Reset”);
b1.addActionListener(this);
b2.addActionListener(this);
add(l1);
add(txtfn);
add(l2);
add(txtln);
add(b1);
add(b2);
add(txtfull);
setTitle(“Name Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
String s1=txtfn.getText();
String s2=txtln.getText();
txtfull.setText(“Your Name is”+(s1+s2));
}
else
{
txtfn.setText(“”);
txtln.setText(“”);
txtfull.setText(“”);
}
}
public static void main(String[] args)
{
new FullName();
}
}
JTextArea
javax.swing.JTextArea
A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component.
|
Constructors |
|||
|
Constructs a new TextArea. |
|||
|
JTextArea(int rows, int cols) |
Constructs a new empty TextArea with the specified number of rows and columns. |
||
|
Constructs a new TextArea with the specified text displayed. |
|||
|
Constructs a new TextArea with the specified text and number of rows and columns. |
|||
|
JTextField(String text, int cols) |
Constructs a new TextField initialized with the specified text and columns. |
||
|
Methods |
|||
|
Appends the given text to the end of the document. |
|||
|
int getColumns() |
Returns the number of columns in the TextArea. |
||
|
void setColumns(int columns) |
Sets the number of columns for this TextArea. |
||
|
Inserts the specified text at the specified position. |
|||
|
Sets the current font. |
|||
|
int getRows() |
Returns the number of rows in the TextArea. |
||
|
void setRows(int rows) |
Sets the number of rows for this TextArea. |
||
JEditorPane
javax.swing.JEditorPane
A JEditorPane is a region that is designed to parse and edit specific types of structured text content. If a scrollbar region is required, this component should be placed inside a JScrollPane object.
|
Constructors |
|
|
Creates a new JEditorPane. |
|
|
JEditorPane(String url) |
Creates a JEditorPane based on a string containing a URL specification. |
|
JEditorPane(String type, String text) |
Creates a JEditorPane that has been initialized to the given text. |
|
JEditorPane(URL initialPage) |
Creates a JEditorPane based on a specified URL for input. |
JPasswordField
javax.swing.JPasswordField
JPasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.
|
Constructors |
|||
|
Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width. |
|||
|
JPasswordField(int columns) |
Constructs a new empty JPasswordField with the specified number of columns. |
||
|
JPasswordField(String text) |
Constructs a new JPasswordField initialized with the specified text.displayed. |
||
|
JPasswordField(String text, int columns) |
Constructs a new JPasswordField initialized with the specified text and columns. |
||
|
Methods |
|||
|
char getEchoChar() |
Returns the character to be used for echoing. |
||
|
void setEchoChar(char c) |
Sets the echo character for this JPasswordField. |
||
|
char[]getPassword() |
Returns the text contained in this TextComponent. |
||
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextDemo extends JFrame implements ActionListener
{
JTextField tnm;
JPasswordField tpwd;
JLabel lnm,lpwd,lmsg;
JButton btnok;
String msg=””;
public JTextDemo ()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
tnm=new JTextField(10);
tnm.setToolTipText(“Enter your name”);
tpwd=new JPasswordField(6);
tpwd.setEchoChar(‘*’);
lnm=new JLabel(“Name:”);
lpwd=new JLabel(“Password:”);
lmsg=new JLabel(“”);
btnok=new JButton(” Ok “);
cp.add(lnm);
cp.add(tnm);
cp.add(lpwd);
cp.add(tpwd);
cp.add (btnok);
cp.add (lmsg);
btnok.addActionListener(this);
setTitle(“Password Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==btnok)
{
if (tnm.getText().equals(“”)||tpwd.getText().equals(“”))
{
lmsg.setText(“plz Enter username/password”); }
else
{
lmsg.setText(“Welcome, “+tnm.getText());
}
}
}
public static void main(String[] args)
{
new JTextDemo ();
}
}
JTextPane
javax.swing.JTextPane
A text component that can be marked up with attributes that are represented graphically.
|
Constructors |
|
|
Creates a new JTextPane. |
|
|
JTextPane(StyledDocument doc) |
Creates a new JTextPane, with a specified document model. |
Buttons:
javax.swing.JButton
JButton is push button with a text object. JButton
JComponent AbstractButton
JCheckBox
JToggleButton
JRadioButton
|
Constructors |
|
|
JButton() |
Creates a button with no set text or icon. |
|
Creates a button with an icon. |
|
|
Creates a button with text. |
|
|
Creates a button with initial text and an icon. |
|
AbstractButton Declares following methods:
|
Methods |
|
|
Icon getRolloverIcon() |
Returns the rollover icon for the button. |
|
void setRolloverIcon(Icon rolloverIcon) |
Sets the rollover icon for the button. |
|
Icon getRolloverSelectedIcon() |
Returns the rollover selection icon for the button. |
|
void setRolloverIcon(Icon rolloverIcon) |
Sets the rollover selected icon for the button. |
|
Icon getPressedIcon() |
Returns the pressed icon for the button. |
|
void setPressedIcon(Icon pressedIcon) |
Sets the pressed icon for the button. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ButtonDemo extends JFrame
{
JButton button = new JButton(“Click Me”);
JTextField text = new JTextField(20);
public ButtonDemo ()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(button);
cp.add(text);
setTitle(“Button Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
text.setText(“Buttons in Swing!”);
}
});
}
public static void main(String[] args)
{
new ButtonDemo ();
}
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
import java.awt.*;
import javax.swing.*;
public class ButtonIconsDemo extends JApplet
{
public ButtonIconsDemo ()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
Icon normal = new ImageIcon(“rollover 1.jpg”);
Icon rollover = new ImageIcon(“rollover 2.jpg”);
Icon pressed = new ImageIcon(“rollover 3.jpg”);
JButton jbutton = new JButton();
jbutton.setRolloverEnabled(true);
jbutton.setIcon(normal);
jbutton.setRolloverIcon(rollover);
jbutton.setPressedIcon(pressed);
cp.add(jbutton);
setTitle(“Button Icons Demo “);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ButtonIconsDemo ();
}
}
JToggleButton:
javax.swing.JToggleButton
A JToggleButton object is a push button with a text label. Clicking on the button causes the button to alternate between pressed and released states.
JRadioButton & JCheckBox classes are subclasses of this class.
|
Constructors |
|
|
Creates an initially unselected toggle button without setting the text or image. |
|
|
JToggleButton(Icon icon) |
Creates an initially unselected toggle button with the specified image but no text. |
|
JToggleButton(Icon icon, boolean selected) |
Creates a toggle button with the specified image and selection state, but no text. |
|
JToggleButton(String text) |
Creates an unselected toggle button with the specified text. |
|
JToggleButton(String text, boolean selected) |
Creates a toggle button with the specified text and selection state. |
|
JToggleButton(String text, Icon icon) |
Creates a toggle button that has the specified text and image, and that is initially unselected. |
|
JToggleButton(String text, Icon icon, boolean selected) |
Creates a toggle button with the specified text, image, and selection state. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ToggleButtonDemo extends JFrame
{
public ToggleButtonDemo ()
{
Container cp = getContentPane();
Icon icon = new ImageIcon(“toggle.jpg”);
JToggleButton toggle1 = new JToggleButton(icon);
JToggleButton toggle2 = new JToggleButton(icon, true);
JToggleButton toggle3 = new JToggleButton(“Toggle Me!”);
JToggleButton toggle4 = new JToggleButton(“Toggle Me!”, icon);
JToggleButton toggle5 = new JToggleButton(“Toggle Me!”, icon,true);
cp.setLayout(new FlowLayout());
cp.add(toggle1);
cp.add(toggle2);
cp.add(toggle3);
cp.add(toggle4);
cp.add(toggle5);
setTitle(“ToggleButton Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ToggleButtonDemo ();
}
}
JCheckBox:
javax.swing.JCheckBox
An item that can be selected or deselected, and which displays its state to the user.
|
Constructors |
|
|
Creates an initially unselected check box button with no text, no icon. |
|
|
Creates an initially unselected check box with an icon. |
|
|
Creates a check box with an icon and specifies whether or not it is initially selected. |
|
|
Creates an initially unselected check box with text. |
|
|
Creates a check box with text and specifies whether or not it is initially selected. |
|
|
Creates an initially unselected check box with the specified text and icon. |
|
|
Creates a check box with text and icon, and specifies whether or not it is initially selected. |
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxDemo extends JFrame implements ItemListener
{
JCheckBox c1,c2,c3;
JLabel jl;
public JCheckBoxDemo()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
c1=new JCheckBox(“Dancing”);
c2=new JCheckBox(“Cricket”);
c3=new JCheckBox(“Travelling”);
add(c1);
add(c2);
add(c3);
jl = new JLabel(“”);
cp.add(jl);
setTitle(“JCheckBox Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jl.setText(cb.getText());
}
public static void main(String[] args)
{
new JCheckBoxDemo();
}
}
JRadioButton:
javax.swing.JRadioButton
An item that can be selected or deselected, and which displays its state to the user. Used with a ButtonGroup object to create a group of buttons in which only one button at a time can be selected.
|
Constructors |
|
|
Creates an initially unselected radio button with no set text. |
|
|
JRadioButton(Icon icon) |
Creates an initially unselected radio button with the specified image but no text. |
|
JRadioButton(Icon icon, boolean selected) |
Creates a radio button with the specified image and selection state, but no text. |
|
JRadioButton(String text) |
Creates an unselected radio button with the specified text. |
|
JRadioButton(String text, boolean selected) |
Creates a radio button with the specified text and selection state. |
|
JRadioButton(String text, Icon icon) |
Creates a radio button that has the specified text and image, and that is initially unselected. |
|
JRadioButton(String text, Icon icon, boolean selected) |
Creates a radio button that has the specified text, image, and selection state. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonDemo extends JFrame implements ActionListener
{
JTextField tf;
JLabel l1,l2,l3;
JRadioButton b1,b2,b3,b4,b5;
public JRadioButtonDemo()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel(“Select your highest degree:”);
cp.add(l1);
b1 = new JRadioButton(“SSC”);
b1.addActionListener(this);
cp.add(b1);
b2 = new JRadioButton(“HSC”);
b2.addActionListener(this);
cp.add(b2);
b3 = new JRadioButton(“Graduate”);
b3.addActionListener(this);
cp.add(b3);
l2=new JLabel(“Seelct gender”);
cp.add(l2);
b4 = new JRadioButton(“Male”);
b4.addActionListener(this);
cp.add(b4);
b5 = new JRadioButton(“Female”);
b5.addActionListener(this);
cp.add(b5);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
ButtonGroup bgs = new ButtonGroup();
bgs.add(b4);
bgs.add(b5);
tf = new JTextField(30);
tf.setEditable(false);
l3=new JLabel();
cp.add(tf);
cp.add(l3);
setTitle(” JListDemo”);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(ae.getSource()==b1)
tf.setText(“U Clicked “+s);
else if(ae.getSource()==b2)
tf.setText(“U Clicked “+s);
else if(ae.getSource()==b3)
tf.setText(“U Clicked “+s);
}
public static void main(String[] args)
{
new JRadioButtonDemo();
}
}
ComboBox:
javax.swing.JComboBox
A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user’s request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.
|
Constructors |
|
|
Creates a JComboBox with a default data model. |
|
|
Creates a JComboBox that contains the elements in the specified array. |
|
|
Creates a JComboBox that contains the elements in the specified Vector. |
|
|
Methods |
|
|
Adds an item to the item list. |
|
|
Object getItemAt(int index) |
Returns the list item at the specified index. |
|
void insertItemAt(Object anObject, int index) |
Inserts an item into the item list at a given index. |
|
void removeItemAt(int anIndex) |
Removes the item at anIndex This method works only if the JComboBox uses a mutable data model. |
|
void removeAllItems() |
Removes all items from the item list. |
|
void removeItem(Object anObject) |
Removes an item from the item list. |
|
int getItemCount() |
Returns the number of items in the list. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxDemo extends JFrame implements ItemListener
{
JLabel jl,jl1;
JComboBox jc;
public JComboBoxDemo()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
jc = new JComboBox();
jc.addItem(“select name”);
jc.addItem(“c++”);
jc.addItem(“java”);
jc.addItem(“net”);
jc.addItemListener(this);
cp.add(jc);
jl = new JLabel(new ImageIcon(“java.jpg”));
jl1 = new JLabel();
cp.add(jl);
cp.add(jl1);
jc.setSelectedIndex(0);
jc.setEditable(true);
setTitle(” JCombo Demo”);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
String s = (String)ie.getItem();
jl1.setText(“U selected “+jc.getSelectedItem());
jl.setIcon(new ImageIcon(s + “.jpg”));
}
public static void main(String[] args)
{
new JComboBoxDemo();
}
}
List:
javax.swing.JList
A component that allows the user to select one or more objects from a list.
|
Constructors |
|
|
JList() |
Constructs a JList with an empty model. |
|
Constructs a JList that displays the elements in the specified array. |
|
|
Constructs a JList that displays the elements in the specified Vector. |
|
|
Methods |
|
|
int getSelectedIndex() |
Returns the first selected index; returns -1 if there is no selected item. |
|
Object getSelectedValue() |
Returns the first selected value or null if the selection is empty. |
|
boolean isSelectedIndex(int index) |
Returns true if the specified index is selected. |
|
void setSelectedIndex(int index) |
Selects a single cell. |
|
void setVisibleRowCount(int visibleRowCount) |
Sets the preferred number of rows in the list that can be displayed without a scrollbar. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JListEx extends JFrame implements ListSelectionListener
{
JList l;
JTextArea ta;
JLabel l1,l2;
String name[]={“pink”,”blue”,”red”,”yellow”};
Color col[]={Color.PINK,Color.BLUE,Color.RED,Color.YELLOW};
Container cp;
public JListEx()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
l = new JList(name);
l.setVisibleRowCount(2);
l.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane sPane = new JScrollPane(l);
ta=new JTextArea(10,10);
JScrollPane sP = new JScrollPane(ta);
l2=new JLabel(new ImageIcon(“republic.png”));
JScrollPane sP1 = new JScrollPane(l2,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
l.addListSelectionListener(this);
cp.add(sPane);
cp.add(sP);
cp.add(sP1);
l1=new JLabel();
cp.add(l1);
setTitle(” JListDemo”);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void valueChanged(ListSelectionEvent e)
{
cp.setBackground(col[l.getSelectedIndex()]);
Object o[]=l.getSelectedValues();
String msg=””;
for(int i=0;i<o.length;i++)
msg+=” “+o[i];
l1.setText(“U selected “+msg);
}
public static void main(String[] args)
{
new JListEx();
}
}
Menus:
JRadioButtonMenuItem
JPopupMenu
JComponent AbstractButton JMenuItem JMenu
JMenuBar JCheckBoxMenuItem
MenuBar
javax.swing.JMenuBar
|
Constructor |
|
|
JMenuBar() |
Creates a new menu bar. |
|
Methods |
|
|
Appends the specified menu to the end of the menu bar. |
|
|
int getMenuCount() |
Returns the number of items in the menu bar. |
|
JMenu getMenu(int index) |
Returns the menu at the specified position in the menu bar. |
|
boolean isSelected() |
Returns true if the menu bar currently has a component selected. |
Menu
javax.swing.JMenu
A popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar.
|
Constructors |
|
|
JMenu() |
Constructs a new JMenu with no text. |
|
Constructs a new JMenu with the supplied string as its text. |
|
|
Methods |
|
|
Appends a menu item to the end of this menu. |
|
|
Creates a new menu item with the specified text and appends it to the end of this menu. |
|
|
void addSeparator() |
Appends a new separator to the end of the menu. |
|
JMenuItem insert(JMenuItem mi, int pos) |
Inserts the specified JMenuitem at a given position. |
|
Inserts a new menu item with the specified text at a given position. |
|
|
void remove(int pos) |
Removes the menu item at the specified index from this menu. |
|
void removeAll() |
Removes all menu items from this menu. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo extends JFrame implements ActionListener
{
JMenuBar m = new JMenuBar();
JMenu m2= new JMenu(“Edit”);
JMenu m1= new JMenu(“File”);
JMenuItem cu = new JMenuItem(“Cut”);
JCheckBoxMenuItem p1 = new JCheckBoxMenuItem(“Paste”);
JMenuItem cpy = new JMenuItem(“Copy”);
JMenuItem Save = new JMenuItem(“Save”);
JRadioButtonMenuItem New =new JRadioButtonMenuItem(“New”);
JMenuItem Exit = new JMenuItem(“Close”);
TextArea t1 = new TextArea(10,30);
public MenuDemo()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
//ImageIcon ii=new ImageIcon(“a.jpg”);
//Save.setIcon(ii );
m.add(m1);
m.add(m2);
m2.add(cu);
m2.add(cpy);
m2.add(p1);
m1.add(New);
m1.add(Save);
m1.addSeparator();
m1.add(Exit);
cp.add(t1);
New.addActionListener(this);
Exit.addActionListener(this);
cpy.addActionListener(this);
cu.addActionListener(this);
p1.addActionListener(this);
setJMenuBar(m);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(“Menu!”);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== New)
t1.setText(” “);
else if(e.getSource()== Exit)
System.exit(0);
}
public static void main(String p[])
{
new MenuDemo();
}
}
PopupMenu
javax.swing.JPopupMenu
A small window that pops up and displays a series of choices. A JPopupMenu is used for the menu that appears when the user selects an item on the menu bar. It is also used for “pull-right” menu that appears when the selects a menu item that activates it. Finally, a JPopupMenu can also be used anywhere else you want a menu to appear. For example, when the user right-clicks in a specified area
|
Constructors |
|
|
Constructs a JPopupMenu without an “invoker”. |
|
|
JPopupMenu(String label) |
Constructs a JPopupMenu with the specified title. |
|
Methods |
|
|
Appends a menu item to the end of this menu. |
|
|
Creates a new menu item with the specified text and appends it to the end of this menu. |
|
|
void addSeparator() |
Appends a new separator to the end of the menu. |
|
Component getInvoker() |
Returns the component which is the ‘invoker’ of this popup menu. |
|
void setInvoker(Component invoker) |
Sets the invoker of this popup menu — the component in which the popup menu menu is to be displayed. |
|
String getLabel() |
Returns the popup menu’s label |
|
Sets the popup menu’s label. |
|
|
void setVisible(boolean b) |
Sets the visibility of the popup menu. |
|
boolean isVisible() |
Returns true if the popup menu is visible (currently being displayed). |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PopupMenuDemo extends JFrame implements MouseListener
{
JLabel jlabel = new JLabel(“Right click me!”, JLabel.CENTER);
JPopupMenu jpopupmenu = new JPopupMenu();
public PopupMenuDemo ()
{
Container contentPane = getContentPane();
jpopupmenu.add(new JMenuItem(“Cut”, new ImageIcon(“bulg2.jpg”)));
jpopupmenu.add(new JMenuItem(“Copy”, new ImageIcon(“bulg2.jpg”)));
jpopupmenu.add(new JMenuItem(“Paste”, new ImageIcon(“bulg2.jpg”)));
jlabel.addMouseListener(this);
contentPane.add(jlabel);
setTitle(“PopupMenu Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void mousePressed (MouseEvent e)
{
if((e.getModifiers() & InputEvent.BUTTON3_MASK) ==InputEvent.BUTTON3_MASK)
jpopupmenu.show(jlabel, e.getX(), e.getY());
}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args)
{
new PopupMenuDemo ();
}
}
CheckBoxMenuItem
javax.swing.JCheckBoxMenuItem
A menu item that can be selected or deselected. If selected, the menu item typically appears with a checkmark next to it. If unselected or deselected, the menu item appears without a checkmark. Like a regular menu item, a check box menu item can have either text or a graphic icon associated with it, or both.
|
Constructors |
|
|
Creates an initially unselected check box menu item with no set text or icon. |
|
|
JCheckBoxMenuItem(Icon icon) |
Creates an initially unselected check box menu item with an icon. |
|
JCheckBoxMenuItem(String text) |
Creates an initially unselected check box menu item with text. |
|
JCheckBoxMenuItem(String text, boolean b) |
Creates a check box menu item with the specified text and selection state. |
|
JCheckBoxMenuItem(String text, Icon icon) |
Creates an initially unselected check box menu item with the specified text and icon. |
|
JCheckBoxMenuItem(String text, Icon icon, boolean b) |
Creates a check box menu item with the specified text, icon, and selection state. |
|
Methods |
|
|
boolean getState() |
Returns the selected-state of the item. |
|
void setState(boolean b) |
Sets the selected-state of the item |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBoxMenuItemDemo extends JFrame implements ActionListener
{
JCheckBoxMenuItem caseMenuItem ;
JMenuItem newMenuItem,bold,italic;
JLabel lbl;
public JCheckBoxMenuItemDemo()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
lbl=new JLabel(“TYCS”);
cp.add(lbl);
JMenuBar mb = new JMenuBar();
// File Menu, F – Mnemonic
JMenu file = new JMenu(“File”);
file.setMnemonic(KeyEvent.VK_F);
mb.add(file);
// File->New, N – Mnemonic
newMenuItem = new JMenuItem(“New”, KeyEvent.VK_N);
file.add(newMenuItem);
caseMenuItem = new JCheckBoxMenuItem(“Case Sensitive”);
caseMenuItem.setMnemonic(KeyEvent.VK_C);
file.add(caseMenuItem);
bold=new JMenuItem(“Bold”, KeyEvent.VK_B);
italic=new JMenuItem(“Italic”, KeyEvent.VK_I);
newMenuItem.addActionListener(this);
file.addSeparator();
file.add(bold);
file.add(italic);
bold.addActionListener(this);
italic.addActionListener(this);
caseMenuItem.addActionListener(this);
setJMenuBar(mb);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(“Menu!”);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==caseMenuItem)
{ if(caseMenuItem.isSelected()==true)
lbl.setText(lbl.getText().toLowerCase());
else if(caseMenuItem.isSelected()==false)
lbl.setText(lbl.getText().toUpperCase());
}
else if (ae.getSource()==bold)
lbl.setFont(new Font(“Arial”,Font.BOLD,18));
else if(ae.getSource()==italic)
lbl.setFont(new Font(“Verdana”,Font.ITALIC|Font.BOLD,28));
else if (ae.getSource()==newMenuItem)
lbl.setText(“”);
}
public static void main(String args[])
{
new JCheckBoxMenuItemDemo();
}
}
RadioButtonMenuItem
javax.swing.JRadioButtonMenuItem
A JRadioButtonMenuItem is a menu item that is part of a group of menu items in which only one item in the group can be selected. The selected item displays its selected state. Selecting it causes any other selected item to switch to the unselected state.
|
Constructors |
|
|
Creates a JRadioButtonMenuItem with no set text or icon. |
|
|
JRadioButtonMenuItem() (Icon icon) |
Creates a JRadioButtonMenuItem with an icon. |
|
JRadioButtonMenuItem(Icon icon, boolean selected) |
Creates a radio button menu item with the specified image and selection state, but no text. |
|
JRadioButtonMenuItem() (String text) |
Creates a JRadioButtonMenuItem with text. |
|
JRadioButtonMenuItem() (String text, boolean b) |
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 b) |
Creates a radio button menu item that has the specified text, image, and selection state. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioMenuItemDemo extends JFrame implements ItemListener
{
JRadioButtonMenuItem forwardMenuItem,backwardMenuItem;
JMenuItem newMenuItem;
JLabel lbl;
public JRadioMenuItemDemo()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
lbl=new JLabel(“TYCS”);
cp.add(lbl);
JMenuBar mb = new JMenuBar();
// File Menu, F – Mnemonic
JMenu file = new JMenu(“File”);
file.setMnemonic(KeyEvent.VK_F);
mb.add(file);
// File->New, N – Mnemonic
newMenuItem = new JMenuItem(“New”, KeyEvent.VK_N);
file.add(newMenuItem);
JMenu findOptionsMenu = new JMenu(“Options”);
findOptionsMenu.setMnemonic(KeyEvent.VK_O);
file.add(findOptionsMenu);
ButtonGroup directionGroup = new ButtonGroup();
// Edit->Options->Forward, F – Mnemonic, in group
forwardMenuItem = new JRadioButtonMenuItem(“Forward”, true);
forwardMenuItem.setMnemonic(KeyEvent.VK_F);
file.add(forwardMenuItem);
directionGroup.add(forwardMenuItem);
// Edit->Options->Backward, B – Mnemonic, in group
backwardMenuItem = new JRadioButtonMenuItem(“Backward”);
backwardMenuItem.setMnemonic(KeyEvent.VK_B);
findOptionsMenu.add(backwardMenuItem);
directionGroup.add(backwardMenuItem);
forwardMenuItem.addItemListener(this);
backwardMenuItem.addItemListener(this);
setJMenuBar(mb);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(“Menu!”);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
System.out.println(“Checked? ” + forwardMenuItem.isSelected());
}
public static void main(String args[])
{
new JRadioMenuItemDemo();
}
}
ToolBar
javax.swing.JToolBar
JToolBar provides a component that is useful for displaying commonly used Actions or controls.
|
Constructors |
|
|
JToolBar() |
Creates a new tool bar; orientation defaults to HORIZONTAL. |
|
JToolBar(int orientation) |
Creates a new tool bar with the specified orientation. |
|
Creates a new tool bar with the specified name. |
|
|
Creates a new tool bar with a specified name and orientation. |
|
|
Methods |
|
|
Adds a new JButton which dispatches the action. |
|
|
void addSeparator() |
Appends a separator of default size to the end of the tool bar. |
|
boolean isFloatable() |
Gets the floatable property. |
|
void setFloatable(boolean b) |
Sets the floatable property, which must be true for the user to move the tool bar. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JToolbarDemo extends JFrame implements ActionListener,
ItemListener
{
JButton b1 = new JButton(“Button 1”);
JButton b2 = new JButton(“Button 2”);
JComboBox jcombobox = new JComboBox();
public JToolbarDemo()
{
Container contentPane = getContentPane();
JToolBar jtoolbar = new JToolBar();
b1.addActionListener(this);
b2.addActionListener(this);
jcombobox.addItem(“Item 1”);
jcombobox.addItem(“Item 2”);
jcombobox.addItem(“Item 3”);
jcombobox.addItem(“Item 4”);
jcombobox.addItemListener(this);
jtoolbar.add(b1);
jtoolbar.add(b2);
jtoolbar.addSeparator();
jtoolbar.add(jcombobox);
contentPane.add(jtoolbar, BorderLayout.EAST);
setTitle(“Demo”);
//setSize(300,500);
//setLocation(150,250);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b1) {
JOptionPane.showMessageDialog(this,”You clicked button 1″);
}
else if (e.getSource() == b2)
{
JOptionPane.showMessageDialog(this,”You clicked button 2″);
}
}
public void itemStateChanged(ItemEvent e)
{
String outString = “”;
if(e.getStateChange() == ItemEvent.SELECTED)
outString += “Selected: ” + (String)e.getItem();
else
outString += “Deselected: ” + (String)e.getItem();
JOptionPane.showMessageDialog(this,outString);
}
public static void main(String[] args)
{
new JToolbarDemo();
}
}
ScrollPane
javax.swing.JScrollPane
Provides a scrollable view of a lightweight component
|
Constructors |
|
|
Creates an empty JScrollPane where both horizontal and vertical scrollbars appear when needed. |
|
|
JScrollPane(Component view, int vsbPolicy, int hsbPolicy) |
Creates a JScrollPane that displays the view component in a viewport whose view position can be controlled with a pair of scrollbars. |
|
JScrollPane(int vsbPolicy, int hsbPolicy) |
Creates an empty (no viewport view) JScrollPane with specified scrollbar policies. |
|
Methods |
|
|
Returns the horizontal scroll bar policy value. |
|
|
void setHorizontalScrollBarPolicy(int policy) |
Determines when the horizontal scrollbar appears in the scrollpane. Options are JScrollPane.HORIZONTAL_SCROLLBAR JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED JScrollPane.HORIZONTAL_SCROLLBAR_NEVER same is for vertical scrollbar |
|
void setVerticalScrollBar(JScrollBar verticalScrollBar) |
Adds the scrollbar that controls the viewports vertical view position to the scrollpane. |
|
void setHorizontalScrollBar(JScrollBar horizontalScrollBar) |
Adds the scrollbar that controls the viewport’s horizontal view position to the scrollpane. |
import java.awt.*;
import javax.swing.*;
public class ScrollpaneImage extends JFrame
{
public scrollpaneimage()
{
Container contentPane = getContentPane();
JLabel jlabel = new JLabel(new ImageIcon(“bulg.jpg”));
JScrollPane jscrollpane = new JScrollPane(jlabel);
contentPane.add(jscrollpane);
setTitle(“ScrollpaneImage Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ScrollpaneImage ();
}
}
import java.awt.*;
import javax.swing.*;
public class JScrollPaneDemo extends JFrame
{
public void JScrollPaneDemo ()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
jp.add(new JButton(“Button ” + b));
++b;
}
}
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
setTitle(” JScrollPane Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JScrollPaneDemo ();
}
}
ProgressBar
javax.swing.JProgressBar
A component that, by default, displays an integer value within a bounded interval. A progress bar typically communicates the progress of some work by displaying its percentage of completion and possibly a textual display of this percentage.
|
Constructors |
|
|
Creates a horizontal progress bar that displays a border but no progress string. |
|
|
JProgressBar(int orient) |
Creates a progress bar with the specified orientation, which can be either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. |
|
JProgressBar(int min, int max) |
Creates a horizontal progress bar with the specified minimum and maximum. |
|
JProgressBar(int orient, int min, int max) |
Creates a progress bar using the specified orientation, minimum, and maximum. |
|
Methods |
|
|
int getMaximum() |
Returns the progress bar’s maximum value. |
|
int getMinimum() |
Returns the progress bar’s minimum value. |
|
void setMaximum(int n) |
Sets the progress bar’s maximum value to n. |
|
void setMinimum(int n) |
Sets the progress bar’s minimum value to n. |
|
void setValue(int n) |
Sets the progress bar’s current value to n. |
|
void setOrientation(int orientaion) |
Sets the progress bar’s orientation to newOrientation, which must be JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. |
|
double getPercentComplete() |
Returns the percent complete for the progress bar. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Progressbarevents extends JFrame
{
JProgressBar jprogressbar = new JProgressBar();
JButton jbutton = new JButton(“Increment the progress bar”);
public Progressbarevents ()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jbutton);
jprogressbar.setForeground(Color.blue);
cp.add(jprogressbar);
jbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jprogressbar.setValue(jprogressbar.getValue() + 10);
}
});
jprogressbar.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
showStatus(“Progress bar minimum: ” +jprogressbar.getMinimum()+ ” maximum: ” + jprogressbar.getMaximum() +” value: ” + jprogressbar.getValue());
}
});
setTitle(“Progressbarevents Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Progressbarevents ();
}
}
Slider
javax.swing.JSlider
A component that lets the user graphically selects a value by sliding a knob within a bounded interval. The slider can show both major tick marks and minor tick marks between them.
|
Constructors |
|
|
JSlider() |
Creates a horizontal slider with the range 0 to 100 and an initial value of 50. |
|
JSlider(int orient) |
Creates a slider using the specified orientation with the range 0 to 100 and an initial value of 50. |
|
JSlider(int min, int max) |
Creates a horizontal slider using the specified min and max with an initial value equal to the average of the min plus max. |
|
JSlider(int min, int max, int value) |
Creates a horizontal slider using the specified min, max and value. |
|
JSlider(int orientation, int min, int max, int value) |
Creates a slider with the specified orientation and the specified minimum, maximum, and initial values. |
|
Methods |
|
|
int getMajorTickSpacing() |
This method returns the major tick spacing. |
|
void setMajorTickSpacing(int n) |
This method sets the major tick spacing. |
|
int getMinorTickSpacing() |
This method returns the minor tick spacing. |
|
vod setMinorTickSpacing(int n) |
This method sets the minor tick spacing. |
|
int getMaximum() |
Returns the maximum value supported by the slider. |
|
void setMaximum(int maximum) |
Sets the models maximum property. |
|
int getMinimum() |
Returns the minimum value supported by the slider. |
|
void setMinimum(int minimum) |
Sets the models minimum property. |
|
int getValue() |
Returns the sliders value. |
|
void setValue(int n) |
Sets the sliders current value. |
|
boolean getPaintLabels() |
Tells if labels are to be painted. |
|
void setPaintLabels(boolean b) |
Determines whether labels are painted on the slider. |
|
boolean getPaintTicks() |
Tells if tick marks are to be painted. |
|
void setPaintTrack(boolean b) |
Determines whether the track is painted on the slider. |
|
int getOrientation() |
Return this slider’s vertical or horizontal orientation. |
|
void setOrientation(int orientation) |
Set the scrollbars orientation to either VERTICAL or HORIZONTAL. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class slider_label extends JFrame implements ChangeListener
{
JSlider jslider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 0);
public slider_label ()
{
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
jslider.addChangeListener(this);
jslider.setPaintTicks(true);
jslider.setPaintLabels(true);
jslider.setMajorTickSpacing(20);
jslider.setMinorTickSpacing(10);
cp.add(jslider);
setTitle(” slider_label Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new slider_label ();
}
public void stateChanged(ChangeEvent e)
{
JSlider jslider1 = (JSlider) e.getSource();
showStatus(“Slider minimum: ” + jslider1.getMinimum() +”, maximum: ” + jslider1.getMaximum() +”, value: ” + jslider1.getValue());
}
}
ScrollBar
javax.swing.JScrollBar
The user positions the knob in the scrollbar to determine the contents of the viewing area. The program typically adjusts the display so that the end of the scrollbar represents the end of the displayable contents, or 100% of the contents. The start of the scrollbar is the beginning of the displayable contents, or 0%.
|
Constructors |
|
|
Creates a vertical scrollbar with the following initial values: |
|
|
JScrollBar(int orientation) |
Creates a scrollbar with the specified orientation and the following initial values. |
|
JScrollBar(int orientation, int value, int extent, int min, int max) |
Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum. |
|
Methods |
|
|
int getMaximum() |
The maximum value of the scrollbar is maximum – extent. |
|
int getMinimum() |
Returns the minimum value supported by the scrollbar (usually zero). |
|
void setMaximum(int n) |
Sets the scroll bar’s maximum value to n. |
|
void setMinimum(int n) |
Sets the scroll bar’s minimum value to n. |
|
int getValue() |
Returns the scrollbar’s value. |
|
void setValue(int n) |
Sets the scrollbar’s value. |
|
int getOrientation() |
Returns the component’s orientation (horizontal or vertical). |
|
void setOrientation(int orientaion) |
Set the scrollbar’s orientation to either VERTICAL or HORIZONTAL. |
|
int getUnitIncrement(int direction) |
Returns the amount to change the scrollbar’s value by, given a unit up/down request. |
|
void setUnitIncrement(int unitInc) |
Sets the unitInc property |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class scrolldemo extends JFrame implements AdjustmentListener
{
JTextField t1;
JScrollBar s1,s2;
Container cp=getContentPane();
public void init()
{
s1=new JScrollBar(Scrollbar.HORIZONTAL,1,2,1,800);
s1.addAdjustmentListener(this);
cp.add(s1);
s2=new JScrollBar(Scrollbar.VERTICAL,1,2,1,200);
s2.addAdjustmentListener(this);
cp.add(s2);
t1=new JTextField(20);
cp.add(t1);
setTitle(“scroll Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new scrolldemo ();
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if(e.getAdjustable()==s1 || e.getAdjustable()==s2)
{
t1.setText(“Horizontal”+s1.getValue()+” Vertical”+s2.getValue());
}
}
}
Tree:
javax.swing.JTree
A control that displays a set of hierarchical data as an outline.
|
Constructors |
|
|
JTree() |
Returns a JTree with a sample model. |
|
Returns a JTree created from a Hashtable which does not display with root. |
|
|
Returns a JTree with each element of the specified array as the child of a new root node which is not displayed. |
|
|
Returns a JTree with each element of the specified Vector as the child of a new root node which is not displayed. |
|
|
Returns a JTree with the specified TreeNode as its root, which displays the root node. |
|
|
Methods |
|
|
int getRowCount() |
Returns the number of rows that are currently being displayed. |
|
void setEditable(boolean flag) |
Determines whether the tree is editable. |
|
void setSelectionRow(int row) |
Selects the node at the specified row in the display. |
|
TreePath getPathForLocation(int x, int y) |
Returns the path for the node at the specified location. |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*<applet code=”JTreeEvents” width=400 height=200></applet>*/
public class JTreeEvents extends JFrame
{
JTree tree;
JTextField jtf;
public JTreeEvents ()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode(“Options”);
DefaultMutableTreeNode a = new DefaultMutableTreeNode(“A”);
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(“A1”);
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(“A2”);
a.add(a2);
// Create subtree of “B”
DefaultMutableTreeNode b = new DefaultMutableTreeNode(“B”);
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(“B1”);
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(“B2”);
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(“B3”);
b.add(b3);
// Create tree
tree = new JTree(top);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
jtf = new JTextField(“”, 20);
contentPane.add(jtf, BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
setTitle(” JTreeEvents Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JTreeEvents ();
}
void doMouseClicked(MouseEvent me)
{
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if(tp != null)
jtf.setText(tp.toString());
else
jtf.setText(“”);
}
}
Table
javax.swing.JTable
The JTable is used to display and edit regular two-dimensional tables of cells
|
Constructors |
|
|
JTable() |
Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model. |
|
JTable(int numRows, int numColumns) |
Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel. |
|
Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames. |
|
|
Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames. |
|
|
Methods |
|
|
void setValueAt(Object aValue, int row, int column) |
Sets the value for the cell in the table model at row and column. |
|
void setShowGrid(boolean showGrid) |
Sets whether the table draws grid lines around cells. |
|
void setGridColor(Color gridColor) |
Sets the color used to draw grid lines to gridColor and redisplays. |
|
Object getValueAt(int row, int column) |
Returns the cell value at row and column. |
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JFrame
{
public JTableDemo ()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
// Initialize column headings
final String[] colHeads = { “Name”, “Phone”, “Fax” };
// Initialize data
final Object[][] data = {
{ “Gail”, “4567”, “8675” },
{ “Ken”, “7566”, “5555” },
{ “Viviane”, “5634”, “5887” },
{ “Melanie”, “7345”, “9222” },
{ “Anne”, “1237”, “3333” },
{ “John”, “5656”, “3144” },
{ “Matt”, “5672”, “2176” },
{ “Claire”, “6741”, “4244” },
{ “Erwin”, “9023”, “5159” },
{ “Ellen”, “1134”, “5332” },
{ “Jennifer”, “5689”, “1212” },
{ “Ed”, “9030”, “1313” },
{ “Helen”, “6751”, “1415” }
};
// Create the table
JTable table = new JTable(data, colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
setTitle(” JTreeEvents Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JTableDemo ();
}
}
ColorChooser:
javax.swing.JColorChooser
JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
|
Constructors |
|
|
Creates a color chooser pane with an initial color of white. |
|
|
JColorChooser(Color initialColor) |
Creates a color chooser pane with the specified initial color. |
|
Methods |
|
|
static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) |
Creates and returns a new dialog containing the specified ColorChooser pane along with “OK”, “Cancel”, and “Reset” buttons. |
|
static Color showDialog(Component component, String title, Color initialColor) |
Shows a modal color-chooser dialog and blocks until the dialog is hidden. |
|
Color getColor() |
Gets the current color value from the color chooser. |
|
void setColor(int c) |
Sets the current color of the color chooser to the specified color. |
|
Sets the current color of the color chooser to the specified color. |
|
|
void setColor(int r, int g, int b) |
Sets the current color of the color chooser to the specified RGB color. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class colorchooser extends JFrame implements ActionListener
{
JPanel jpanel = new JPanel();
JButton jbutton;
public colorchooser()
{
jbutton = new JButton(“Click here to change colors.”);
jbutton.addActionListener(this);
jpanel.add(jbutton);
getContentPane().add(jpanel);
setTitle(“Demo”);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Color c= JColorChooser.showDialog(colorchooser.this,
“Select a new color…”, Color.black);
jpanel.setBackground(c);
}
public static void main(String[] args)
{
new colorchooser();
}
}
FileChooser:
javax.swing.JFileChooser
JFileChooser provides a simple mechanism for the user to choose a file.
|
Constructors |
|
|
Constructs a JFileChooser pointing to the user’s default directory. |
|
|
JFileChooser(File currentDirectory) |
Constructs a JFileChooser using the given File as the path. |
|
JFileChooser(String currentDirectoryPath) |
Constructs a JFileChooser using the given path. |
|
Methods |
|
|
int showOpenDialog(Component parent) |
Pops up an “Open File” file chooser dialog. |
|
int showSaveDialog(Component parent) |
Pops up a “Save File” file chooser dialog. |
|
int showDialog(Component parent, String approveButtonText) |
Pops a custom file chooser dialog with a custom approve button. |
|
void setDialogTitle(String dialogTitle) |
Sets the string that goes in the JFileChooser window’s title bar. |
|
File getSelectedFile() |
Returns the selected file. |
|
Returns the filename. |
|
import java.awt.*;
import java.io.File;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class filechooser extends JFrame implements ActionListener
{
JFileChooser chooser = new JFileChooser();
JButton jbutton = new JButton(“Display file chooser”);
JTextField jtextfield = new JTextField(30);
public filechooser()
{
Container cp= getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jbutton);
cp.add(jtextfield);
jbutton.addActionListener(this);
setVisible(true);
setSize(300,400);
setTitle(“File Chooser Demo..”);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
int result = chooser.showOpenDialog(null);
File fileobj = chooser.getSelectedFile();
if(result == JFileChooser.APPROVE_OPTION)
{
jtextfield.setText(“You chose ” + fileobj.getPath());
}
else if(result == JFileChooser.CANCEL_OPTION)
{
jtextfield.setText(“You clicked Cancel”);
}
}
public static void main(String args[])
{
new filechooser();
}
}
TabbedPane
javax.swing.JTabbedPane
A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.
|
Constructors |
|
|
Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP. |
|
|
JTabbedPane(int tabPlacement) |
Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT. |
|
JTabbedPane(int tabPlacement, int tabLayoutPolicy) |
Creates an empty TabbedPane with the specified tab placement and tab layout policy. |
|
Methods |
|
|
Adds a component represented by a title and no icon. |
|
|
Adds a component represented by a title and/or icon, either of which can be null. |
|
|
void addTab(String title, Icon icon, Component component, String tip) |
Adds a component and tip represented by a title and/or icon, either of which can be null. |
|
void remove(int index) |
Removes the tab and component which corresponds to the specified index. |
|
void removeAll() |
Removes all the tabs and their corresponding components from the tabbedpane. |
|
void setToolTipTextAt(int index, String toolTipText) |
Sets the tooltip text at index to toolTipText which can be null. |
|
void setTitleAt(int index, String title) |
Sets the title at index to title which can be null. |
import javax.swing.*;
import java.awt.*;
public class JTabbedPaneDemo extends JFrame
{
public JTabbedPaneDemo()
{
JTabbedPane jtp = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.WRAP_TAB_LAYOUT);
/*JPanel jp=new JPanel();
jp.add(new JLabel(“Enter something”));
jp.add(new JTextField(20));*/
jtp.addTab(“Cities”,new CitiesPanel());
/*JPanel jp1=new JPanel();
JCheckBox cb1 = new JCheckBox(“Red”);
JCheckBox cb2 = new JCheckBox(“Green”);
jp1.add(cb1);
jp1.add(cb2);*/
jtp.addTab(“Colors”,new ColorsPanel());
jtp.addTab(“Flavor”,new FlavorsPanel());
Container cp=getContentPane();
cp.add(jtp);
setTitle(“Demo”);
//setSize(300,500);
//setLocation(150,250);
setBounds(100,200,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new JTabbedPaneDemo();
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton(“New York”);
add(b1);
JButton b2 = new JButton(“London”);
add(b2);
JButton b3 = new JButton(“Hong Kong”);
add(b3);
JButton b4 = new JButton(“Tokyo”);
add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox(“Red”);
add(cb1);
JCheckBox cb2 = new JCheckBox(“Green”);
add(cb2);
JCheckBox cb3 = new JCheckBox(“Blue”);
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem(“Vanilla”);
jcb.addItem(“Chocolate”);
jcb.addItem(“Strawberry”);
add(jcb);
}
}
SplitPane
javax.swing.JSplitPane
JSplitPane is used to divide two (and only two) Components. The two Components are graphically divided based on the look and feel implementation, and the two Components can then be interactively resized by the user.
|
Constructors |
|
|
Creates a new JSplitPane configured to arrange the child components side-by-side horizontally with no continuous layout, using two buttons for the components. |
|
|
JSplitPane(int newOrientation) |
Creates a new JSplitPane configured with the specified orientation and no continuous layout. |
|
JSplitPane(int newOrientation, boolean newContinuousLayout) |
Creates a new JSplitPane with the specified orientation and redrawing style. |
|
Methods |
|
|
int getOrientation() |
Returns the orientation. |
|
void setOrientation(int orientation) |
Sets the orientation, or how the splitter is divided. |
|
void setOneTouchExpandable(boolean newValue) |
Sets the value of the oneTouchExpandable property, which must be true for the JSplitPane to provide a UI widget on the divider to quickly expand/collapse the divider. |
|
void setDividerSize(int newSize) |
Sets the size of the divider. |
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Splitpane extends JFrame implements ActionListener
{
JButton jbutton1, jbutton2;
JTextField text1 = new JTextField(“Text 1”);
JTextField text2 = new JTextField(“Text 2”);
JSplitPane jsplitpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,text1, text2);
public Splitpane ()
{
Container cp = getContentPane();
JPanel jpanel = new JPanel();
jbutton1 = new JButton(“Make one-touch expandable”);
jbutton1.addActionListener(this);
jpanel.add(jbutton1);
jbutton2 = new JButton(“Make split horizontal”);
jbutton2.addActionListener(this);
jpanel.add(jbutton2);
cp.add(jsplitpane, BorderLayout.CENTER);
cpadd(jpanel, BorderLayout.SOUTH);
setTitle(” Splitpane Demo”);
setBounds(200,300,400,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Splitpane();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbutton1)
{
jsplitpane.setOneTouchExpandable(true);
}
if(e.getSource() == jbutton2)
{
jsplitpane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
}
}
}