This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
คาคงที่และ Method ที่สําคัญของ Class Dimension มีดังนี้ คาคงที่/Method ความหมาย
public int height เก็บความสูงของ Dimension public int width เก็บความกวางของ Dimension public Dimension() สราง Dimension ที่มีคาเทากบั 0 public Dimension(int width, int height) สราง Dimension ที่มีขนาดเทากับ width และ
height ที่กําหนด public double getHeight() คืนคาความสูงของ Dimension เปน Double public double getWidth() คืนคาความกวางของ Dimension เปน Double public void setSize(double width , double height)
กําหนดขนาดของ Dimension เปน double
Public void setSize(int width , int height) กําหนดขนาดของ Dimension เปน int ใน Class Component มี Overload method “setSize()” ซ่ึงรับคาเปน Dimension Object เพื่อใชกําหนดขนาดใหกับ Component ตางๆเหมือนกับ Method “setSize(int,int)” ใน Class “Toolkit” มี Method หนึ่งที่จะใหคา Dimension ของจอภาพขณะนั้นออกมา คือ public Dimension getScreenSize() ตัวอยางที่ 1.1 แสดงการกําหนดขนาด Component ผาน Dimension และกําหนดใหแสดง Frame กลางจอภาพพอดีดวยการใชคุณสมบัติผาน Method getScreenSize() ของ Class Toolkit /*------------------file useDimension.java----------------*/ import java.awt.* ; import javax.swing.* ; public class useDimension extends JPanel { JButton b1,b2; JTextField text ; public useDimension() { setLayout(new FlowLayout()) ; b1 = new JButton("OK"); b2 = new JButton("Cancel"); text = new JTextField(10); add(text);
Constructor/Method ความหมาย Box(int axis) Create a Box container that displays its
components along the specified axis. static Component createGlue() Create an invisible “glue” component that can
be useful in a Box whose visible components have a maximum width (for horizontal box) or height (for a vertical box). The size of a glue component can expand fill the empty space between component
static Box createHorizontalBox() Creates a Box container that arranges its components from left-to-right.Components have a fixed width.
static Component createHorizontalGlue() Create a horizontal glue component. static Component createHorizontalStrut(int width) Creates an invisible component that’s always
เนื่องจาก Component ตางๆไดทําการ Implement และสืบทอดคุณสมบัติตางๆมาจาก Interface และ Class ตางๆมากมาย ดังนัน้เพื่อใหสามารถเรียกใช ตวัแปร และ Methods ของแตละ Component ไดสะดวก จึงไดสรุปเกี่ยวกับตัวแปร และ Method บางสวนที่ใชงานบอยๆ ของ Class หลักๆที่ขยายไปสู Class ที่ใชสราง Component ดังตารางตอไปนี ้
ตารางแสดง Method ของ Class Component ท่ีใชงานบอยๆ Method ความหมาย
public Color getBackground() คืนคาสี Background ของ Component นั้นๆเปน Object ของ Class Color
public Rectangle getBounds() คืนคา Bound ของ Component เปน Object ของ Class Rectangle
public Component getComponentAt(int x,int y) คืน Component ที่วางอยู ณ.ตําแหนง x,y public Component getComponentAt(Point p) คืน Component ที่วางอยู ณ.ตําแหนง point public Cursor getCursor() คืนคา Cursor ที่ใชใน Component ขณะนัน้ public Font getFont() คืนคา Font ที่ Component นั้นใชงานอยู public FontMetrics getFontMetrics(Font font) คืนคาตระกูล Font ตาม font ที่ระบุ public Color getForeground() คืนคาสี Foreground ของ Component public Graphics getGraphics() คืนคา Object ของ class Graphics public Point getLocationOnScreen() คืนคา Point ณ.ตําแหนงที่ Component วางอยู
บน top-level containers public String getName() คืนคาชื่อ Component นั้นๆ public Dimension getPreferredSize() คืนคา preferred size ของ Component เปน
public void setFont(Font f) กําหนด Font ใหกับ Component public void setForeround(Color c) กําหนดสี Foreground ใหกับ Component public void setLocation(int x,int y) เล่ือนตําแหนง Component ไปยังจุดที่ตองการ public void setLocation(Point p) เล่ือนตําแหนง Component ไปยัง Point ที่ตองการ public void setName(String name) กําหนดชื่อใหกับ Component
public void setCursor(Cursor cursor) กําหนดการใชงาน Cursor ใหกับ window public void show() กําหนดใหมองไมเห็น window ทางจอภาพ
สามารถใช setVisible(true) แทนได
ตารางแสดง Method ของ Class Frame ท่ีใชงานบอยๆ Method ความหมาย
public Fame() Constructor ใชสราง Frame วางๆขึ้นมา public Frame(String title) Constructor ใชสราง Frame พรอมระบุขอความ Title
Bar ตาม title ที่กําหนด Public Image getIconImage() คืนคา Icon ของ Frame กลับมาเปน Image Object Public String getTitle() คืนคา Title bar ของ Frame เปน String
ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class JFrame คาคงที่/Method ความหมาย
public static final int DISPOSE_ON_CLOSE ทําลายและปด Window โดยอัตโนมัติ public static final int EXIT_ON_CLOSE ออกจากโปรแกรมและปด Window โดย
อัตโนมัติ public static final int DO_NOTHING_ON_CLOSE
ปองกันการกดปุม Close(เมื่อกดแลวไมปด Window)
public static final int HIDE_ON_CLOSE ปดแลวซอน Window โดยอัตโนมัติ public JFrame() สราง Frame วางๆขึ้นมา public int getDefaultCloseOperation() คืนคาคงที่ที่ใชสําหรับจัดการกับ Frame ที่
กําหนดผาน Metod setDefaultCloseOperatio() public JFrame(String title) สราง Frame วางๆขึ้นมาพรอมกับกําหนด
ขอความ Title Bar ผาน title public JMenuBar getJMenuBar() คืนคา Menu Bar Object ของ Frame public Container getContentPane() คืนคา Content Pane ซ่ึงเปน Container ของ
Frame เพื่อใชสําหรับวาง Component ตัวอ่ืนๆลงไป
public void remove(Component comp) Remove Component ออกจาก Container ของ Frame
AbstractButton() No-argument constructor void doClick() Programmatically simulate the user activating, orclicking,
the button.Typically,this method is not called by application
Icon getDisableIcon() Return the icon that represents the disabled state of the button.
Icon getDisabledSelectedIcon() Return the icon that represents the disabled state and selected state of the button.
int getHorizontalAlignment() Gets the button’s policy for aligning its text an icon whithin its display area. The valid values are AbstractButton.LEFT, AbstractButton.CENTER ,or AbstractButton.RIGHT
int getHorizontalTextPosition() Gets the position in which the button text label is drawn relative to its icon.
int getIcon() Gets the default icon used when one is not specified. Insets getMargin() Gets the insets object that defines the margin between the
int getMnemonic() Gets the mnemonic key that activates this button. Icon getPressedIcon() Returns the icon that represents the state when the button
is pressed. Icon getRolloverIcon() Gets the icon displayed when the button is in the rollover
state, that is,when the mouse is placed overed the button. Icon getRolloverSelectedIcon() Gets the icon used to display the button face when the
button is selected while in the rollover state. Icon getSelectedIcon() Gets the icon displayed on the button face when the
button is selected. Object[] getSelectedObjects() Returns an array of one element that contains the button’s
label if selected. String getText() Returns the text used as the button label. int getVerticalAlignment() Return the button’s vertical alignment, either
SwingConstants.TOP,SwingConstants.CENTER, or SwingConstants.BOTTOM.
int getVerticalTextPosition() Gets the vertical position in which the button labels is drawn,relative to its icon.
boolean isRolloverEnable() Indicates whether the rollover state is currently set for this button.
boolean isSelected() Return the disposition of selected state of the button. void setDisabledIcon(Icon disabled) Sets the icon used to display the disabled state for this
Sets the icon used to represent the selected disabled state.
void setEnabled(boolean b) Sets the enabled disposition of the button to either enable or disable it.
void setHorizontalAlignment(int align)
Sets the horizontal alignment of this button’s text and icon within the its display area. Valid value are SwingConstants.CENTER, SwingConstatnts.LEFT, or SwingConstants.RIGHT,or SwingConstants.RIGHT
void setHorizontalTextPosition(int Relative to the placement of its icon. Valid values are
align) SwingConstants.CENTER,SwingConstants.LEFT, SwingConstants.RIGHT,SwingConstants.LEADING, of SwingConstants.TRAILING.
void setIcon(Icon defaulticon) Sets the default icon used by this button when no other is specified.
void setmarginIInsets insets) Sets the insets object used by the button. void setMnemonic(int mnemonic) Sets the mnemonic key represented by the numeric code
that represents the keyboard key that the activates this button.
void setMnemonic(char mnemonic) Sets the mnemonic key represented by the specified character.
void setPressedicon(Icon pressedIcon)
Sets the icon that is displayed to indicate the button is in the pressed state.
void setRolloverIcon(Icon rolloverIcon)
Sets the icon displayed when the button is in the rollover state,that is, when the mouse is over the button.
void setRolloverEnabled(boolean b) Sets the button to the rollover state. void setRolloverSelectedIcon(Icon rolloverSelectedIcon)
Sets the icon displayed when the button is selected while in th rollover state.
void setSelected(boolean b) Sets the disposition of the selected state to the value specified. A value of True means the button is selected.
void setSelectedIcon(Icon selectedIcon)
Sets the icon displayed when the button is selected.
void setText(String text) Sets the text used for the button’s label. void setVerticalAlignment(int alignment)
Sets the vertical alignment of this button’s text and icon within the button’s display area. Valid vaues are SwingConstants.CENTER , SwingConstants.TOP , and SwingConstants.BOTTOM
Void setVerticalTextPosition(int textPosition)
Sets the vertical position of this button’s text label relative to the placement if this icon. Valid vaues are SwingConstants.CENTER , SwingConstants.TOP , and SwingConstants.BOTTOM
int getDisplayedMnemonic() Returns the keycode that represents the label’s mnemoic key
int getHorizontalAlignment() Returns the label’s horizontal alignment within its display area.
int getHorizontalTextPosition() Returns the horizontal position of the label’s text ,relative to its image.
Icon getIcon() Returns the graphic icon image that the label displays.
int getIconTextGap() Returns the amount of space between the label’s test and its icon
Component getlabelFor() Gets the component labeled by this label String getText() Returns the label’s text string. int getVerticalAligment() Returns the label’s vertical alignment within its
display area. int getVerticaltextPosition() Returns the vertical position of the label’s text,
relative to its image. void setDisabledIcon(Icon disabledIcon) Sets the icon that tepresents the disabled state of
gthe label. void setDisplayedMnemonic(char aChar) Sets the list mnemonic character represented by
the specified char value void setDisplayedMnemonic(int key) Sets the list mnemonic character represented by
the specified integer key code void setHorizontalAlignment(int alignment) Sets the label’s horizontal alignment void setHorizontalTextPosition(int textPosition)
Sets the label text’s horizontal position relative to its image
void setIcon(Icon icon) Sets the icon this component will display. void setIconTextGap(int iconTextGap) St the space between the label’s text and icon void setLabelFor(Component c) Sets the component labeled by this label void setText(String text) Sets the text(a single line only) displayed as part
ตัวอยางที่ 1.13 แสดงการสราง Label พรอมดวย Icon /*--------------------file Label3.java-----------------------*/ import java.awt.*; import javax.swing.*; public class Label3 extends JFrame { public Label3() { super("การสราง Label พรอม Icon"); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel lb1 = new JLabel("label with text"); lb1.setToolTipText("This is label1"); c.add(lb1); Icon fish = new ImageIcon("goldFish.gif"); JLabel lb2= new JLabel("label with text and icon",fish,SwingConstants.LEFT); lb2.setToolTipText("This is label2"); c.add(lb2); JLabel lb3=new JLabel(); lb3.setText("label with icon and text at bottom"); lb3.setIcon(fish); lb3.setHorizontalTextPosition(SwingConstants.CENTER);
CheckBox1 f = new CheckBox1(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,100); f.show(); } }
1.7 JRadioButton ปุม radio มีไวเพื่อใหผูใชเลือกตัวเลือกไดเพียวตวัเลือกเดยีวภายในกลุมเดียวกัน การสรางและใชงานจะคลายกบั checkbox โดยจะใช class JRadioButton เพื่อสราง และใช class ButtonGroup เพื่อจัดกลุมของ radio Class JRadioButton มี constructosr และ Methods ที่สําคัญดังนี้
Constructor/Methods ความหมาย JRadioButton() No-argument constructor, which constructs a
radio button that has an empty label. JRadioButton(Icon icon) Constructs a radio button that displays the
specified icon. JRadioButton(Icon icon,boolean selected) Constructs a radio button that displays the
specified icon ,and that is initially in the indicates selection state.
JRadioButton(String text) Constructs a radio button that display the specified string as its text label.
JRadioButton(String text , boolean selected Constructs a radio button that display the specified string as its text label. and that is initially in the indicates selection state.
JRadioButton(String text ,Icon icon) Constructs a radio button that display the
specified string as its text label ,and icon. JRadioButton(String text , Icon icon ,boolean selected)
Constructs a radio button that display the specified string as its text label and icon and that is initially in the selected state.
Class ButtonGroup มี Constructor และ Method ที่สําคัญดังนี ้
Constructors/Methods ความหมาย ButtonGroup() No-argument constructor, which constructs
anew button group object. void add(AbstractButton b) Adds the specified button to the button group. Enumeration getElements() Returns all buttons that are currently members
of this button group. ButtonModel getSelection() Return the currently selected button boolean isSelected(ButtonModel m) Indicates if the specified button is selected void remove(AbstractButton b) Removes the specified button from the button
group. void setSelected(ButtonModel m , boolean b) Set the specified button to the state represented
by the specified button model object. ตัวอยางที่ 1.15 แสดงการสราง RadioButton /*-------------------------file Radio1.java---------------------------*/ import java.awt.* ; import javax.swing.* ; public class Radio1 extends JFrame { JLabel label1; JRadioButton radio1,radio2,radio3; ButtonGroup buttonGroup; public Radio1(String title) { super(title);
Container c=getContentPane(); c.setLayout(new FlowLayout()); label1 = new JLabel("Please, select that you like"); c.add(label1); buttonGroup = new ButtonGroup(); radio1=new JRadioButton("Favorite language is Java"); radio2=new JRadioButton("Favorite language is VB"); radio3=new JRadioButton("Favorite language is C++"); c.add(radio1); c.add(radio2); c.add(radio3); buttonGroup.add(radio1); buttonGroup.add(radio2); buttonGroup.add(radio3); } public static void main(String[] args) { Radio1 f= new Radio1("Radio Button Demo"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,150); f.show(); } }
1.8 JComboBox ComboBox บางที่จะเรยีกวา drop-down list เนื่องจากสามารถเลื่อน scrollbar ขึ้นลง เพื่อคนหาตัวเลือกที่ตองการได การสราง ComboBox จะสรางจาก class JcomboBox ซ่ึงมี Constructors และ Methods ที่สําคัญดังนี้
Constructors/Methods ความหมาย JcomboBox() No-argument constructor that constructs a new
combo box JcomboBox(ComboBoxModel mode) Constructs a new combo box that uses the specifed
model to stoe its elements JcomboBox(Object[] items) Constructs a new combo box that stores the items in
the specified array JComboBox(Vector items) Constructs a new combo box that stores the items in
the specified vector void addItem(Object anItem) Add the specified item to this combo box Object getItemAt(int idex) gets the item located in the specifid index in this
combo box int getItemCount() Gets the number of items currently stored by combo
box int getMaximumRowCount() Gets the maximm number of items that can be
displayed without using a scroll bar int getSelectedIndex() Return the index of the selection item Object getSelectedItem() Gets the iem that is currently marked as selected Object[] getSelectedObjects() Returns an array whose elements is the single
selected item of this combo box void hidePopup() Closed the pop-up window used by the combo box to
display its elements void insertItemAt(Object item, int index) Inserts the specified item at the specified index boolean isEditable() Indicates whether the combo box items can be edited boolean isPopupVisible() Indicates if the pop-up that displays the conmbo box
items is visible void removeAllItem() Removes all items from this combo box
void removeItem(Object item) Removes the specified item from this combo box void removeItemAt(int index) Removes the item at the index indicated from the
combo box void setEditable(boolean flag) Sets the editing policy for this combo box and
indicates if items can be edited void setEnabled(boolean enabled) Sets the enabled state of this combo box to either
enabled or disabled void setMaximumRowCount(int count) Sets the maximum number of rows that this combo
box can store void setPopupVisible(boolean v) Sets whether or not this combo box makes its pop-up
window visible void setSelectedIndex(int anIndex) Set the item represented by the specified void setSelectedItem(Object anObject) Set the state of the specified object to selected void showPopup() Display the pop-up window of this combo box ตัวอยางที่ 1.16 แสดงการสราง Combo box /*---------------------file JComboBox1.java-------------------*/ import java.awt.*; import javax.swing.*; public class JComboBox1 extends JFrame { public JComboBox1(String title) { super(title); Container c = getContentPane(); c.setLayout(new FlowLayout());
JList() No-argument constructor. It constructs a Jlist with an empty data model.
JList(ListMode dataModel) Creates a JList populated with elements contained in the specified model.
JList(Object[] listData) Creates a JList populated with the elements in the specified array.
JList(Vector listData) Creates a JList populated with the elements in the specified vector.
void addSelectionIntevl(int anchor, int lead) Sets the list’s selection to be the union of the specified interval and the list’s current selection.
void clearSelection() Clear the list’s selection protectd ListSelectionModel createSelectionModel)
Returns an instance of DefaultListSelectionModel.
void ensureIndexIsVisible(int idex) Scrolls the viewport, if any, to make the element represented by the specified index completely visible.
protected void fireSelectionValueChanged(int firstIndex int lastIndex, boolean isAdiJusting)
Notifies registered listeners of a change in the list’s selection model.
int getAnchorSelectionIndex() Returns the value that representes the low index that marks the current selection from the most recent addSelectionInterval or setSelectionInterval call.
Rectangle getCellBounds(int index1, int index2)
Returns the bounds of the items contained in the range specified by the two index arguments.
ListCellRenderer getCellRenderer() Returns the object that renders the list items. int getFirstVisibleIndex() Returns the index of the first visible call,that is
,the cell in the upper-left coner of the JList.It returns -1 if nothing is visible or if the list is
empty int getFixedCellHeight() Returns the value of the fixedCellHeight
variable. int getFixedCellWidth() Returns the value of the fixedCellWidth
property. int getLastVisibleIndex() Returns the index of the last visible cell,that is,
the cell in the lower right corner of the JList.It returns -1 if nothing is visible or if the list is empty.
int getLeadSelectionIndex() Returns the value of the index that marks the “lead” item of the set of selected itms.
int getMaxSelectionIndex() Returs the largest selected cell index. int getMinSelectionIndex() Returns the smallest selected cell index. ListModel getModel() Retrns the data model used by this JList to
store its elements. Dimension getPreferredScrollable ViewportSize()
Computes the sze of the view port needed to display the number of rows represented by the visibleRowCount variable.
Object getPrototypeCellValue() Returns the cell width used to represent the width of the cells for all the list’s elements.
int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the value of the bloack increment,which is used to scroll the list by one block.
boolean getScrollableTracks ViewportHeight() Indicates if the heght of thisJList changes when the height of its Jviewport,if any,changes.
boolean getScrollableTracks ViewportWidth() Indicates if the heght of thisJList changes when the width of its Jviewport,if any,changes.
int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the amount by which the list is scrlled during a units scroll event.
int getSelectedIndex() Returns the index of the first seleted item int[] getSelectedIndices() Returns an array of the indices of all the
selected iems. Object getSelectedValue() Returns the value of the first selected item, or
null if nothing is selected Object[] getSelectedValues() Returns an array of the values of the selected
elements. Color getSelectionBackground() Returns background color used to paint the
selected cells. Color getSelectionForeground() Returns color used to paint the foreground of
the selected cells. int getSelectionMode() Indicates whether the selection policy is single-
item or multi-item. ListSelectionModel getSelectionMode() Returns he selection model object boolean getValueIsAdjusting() Indicates the adjustment state of the data
model, that is, the value of the model’s isAdjusting property.
int getVisibleRowCount() Return the preferred number of visible rows. Point indexToLocation(int index) Returns the point that represents the oriin of the
list item specified by the index argument. boolean isSelectedIndex(int index) Indicates if the element at the specified index is
seleted. boolean isSelectionEmpty() Indicates if there are any list elements
currently selected. int locationoIndex(Point location) Converts a point relative to the JList
component’s upper left corner to the index of the cell at the location.
Sets the color used to paint the foreground of selected cells.
void setSelectionInterval(int anchor, int lead) Sets the list’s selection to be the cells containedin the specified interval
void setSelectionMode(int selectionMode) Sets the selection policy for the list,either single-item or multiple-item selections
void setValueIsAjusting(boolean b) Sets the adjustment state of the data model. If tis is TRUE, only one selectiob events is fired when all the selections have stabilized,for example, when the user stops dragging the mouse
void setVisibleRowCount(int visibleRowCount)
Sets the preferred number of list rows to be displayed without using scrollbar
void cut() Transfers the currently selected text to the system clipboard and deletes the contents from the text component.
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Jcomponent.
Action[] getActions() Retrieves the list of editor commands. Caret getCaret() Retrieves the caret object associated with the
text component. The caret marks the current position in the document affected by editing actions.
Color getCaretColor() Indicates the current color used to display the caret.
int getCaretPosition() Returns the offset within the document from the beginning of the current caret position.
Color getDisabledTextColor() Indicates the color currently used to display disabled text.
Document getDocument() Fetches the document model object associated with this component’s text editor.
char getFocusAccelerator() Returns the key accelerator character that results in the target text component acquiring the keyboard focus.
Highligher getHilighlighter() Retrieves the highlighter object that does highlighting.
InputMethodRequests getInputMethodRequests()
Return an input method handler. This object handles input method requests for the text component.
Keymap getKeymap() Retrieves this text component’s currently active keymap.
static Keymap getKeymap(String nm) Retrieves the keymap with the specified name, which was previously added to the document used by this text component.
Insets getMargin() Returns the insets object that represents the space between the text component’s border and its text.
Dimension getPreferredScrollable ViewportSize()
Returns the preferred size of the text component.
int getScrollableBlockIncrement(Rectangle visibleRect,int orientation,int direction)
Returns the scroll block increment amount that will expose one complete block of rows or columns as a result of a scroll operation.
boolean getScrollableTracks ViewportHeight() Indicates if this text component’s height should match the height of any view port the presents a view of its content.
boolean getScrollableTracks ViewportWidth() Indicates if this text component’s width should match the height of any view port the presents a view of its content.
int getScrollableUnitIncrement(Rectangle visbleRect, int orientation,int direction
Returns the scroll unit increment amount that will expose one complete row or column as result of scroll operation.
String getSelectedText() Returns this component’s currently selected text.
Color getSelectedTextColor() Retrieves the color currently used to display text that is selected.
Color getSelectionColor() Retrieves the color currently used to indicate selected text.
int getSelectionEnd() Returns the end position of the selected text. int getSelectionStart() Returns the start position of the selected text. String getText() Returns the text component’s text content. String getText(int offs,int len) Retrieves the subset of the text component’s
text delineated by two offsets, which represent caret position.
TextUI getUI() Fetches the user-interface factory for this text-oriented editor.
void select(int selectionStart , int selectionEnd) Marks as selected the text delineated by the specified start and end positions.
void selectAll() Selects all the text in the text component. void setCare(Caret c) Set the caret to be used by this text
component. void setCaretColor(Color c) Set the color used to render the caret void setCaretPosition(int position) Sets the position of the caret for text insertion
operations. void setDisabledTextColor(Color c) Sets the color used to display text that is
marked disabled. void setDocument(Document doc) Set the document object used by this text
component. void setEdiable(boolean b) Specifies whether or not this text component
is editable. void setEnabled(boolean b) Sets the enabled state of the component. void setFocusAccelerator(char aKey) Sets the key accelerator whose activation will
cause the receiving text component to get the focus.
void setHighlighter(Highlighter h) Sets the highlighter used by the component. void setKeymap(Keymap map) Sets the keymap used by the component. A
keymap binds keys to actions. void setMargin(Insets m) Sets the text component’s insets object, which
specifies the amount of space between the component border.
void setOpaque(boolean o) Sets whether or not the UI should be opaque. void setSelectedTextColor(Color c) Sets the color used to display text marked
selected. void setSelectionColor(Color c) Sets the color used to highlight selected text. void setSelectionEnd(int selectionEnd) Sets the selection end to the specified offset
AccessibleContext getAccessibleContext() Get accessibleContext associated with this JTextField
Action[] getActions() Returns the list of editor commands. int getColumns() Returns the number of columns in this text
field int getHorizontalAligment() Returns the horizontal alignment of the text BoundRangeModel getHorizontalVisibility() Returns the range of text that is currently
visible Dimension getPreferredSize() Returns the preferred size of this text field. int getScrollOffset() Gets the scroll offset. String getUIClassID() Gets the class ID for a UI boolean isValidateRoot() Indicates whether or not calls to revalidate this
component will be processed by validating this component itself
void posActionEvent() Dispatches action events to registered listeners void removeActionListener(ActionListener l) Removes the specified action listener from the
notification list void scrollRectToVisible(Rectangle r) Scroll the field left or right void setActionCommand(String command) Sets the name of the string that represents the
name of the action command. void setColumns(int columns) Sets the number of columns and invalidates
the layout so the component will be redraw with the new number of columns
void setFont(Font f) Sets the font used to display the content void setHorizontalAligment(int alignment) Sets the horizontal alignment of the text void setScrollOffset(int scrollOffset) Sets the scroll offset
public static void main(String[] args) { JTextFieldTest f = new JTextFieldTest("JTextField and JPasswordField Test"); f.setDefaultCloseOperation(EXIT_ON_CLOSE); f.setSize(320,100); f.setVisible(true); } }
number of rows and columns , but initialized with no content
JTextArea(String text) Constructs a new JTextArea that display the specified text
JTextArea(String text,int rows , int columns) Constructs a new JTextArea with the specified number of rows and columns, initialized to contain the specified text
void append(String str) Appends the specified text to the end of the document
Protected Document createDefaultMode() Creates the document mplementation that is used by default if none is specified in a constructor
AccessibleContext getAcessibleContext() Get the AccessibleContext associated with this JTextArea
int getColumns() Returns the number of columns that this text area display
protected int getColumnWidth() Gets the width in pixels of a display column int getLineCount() Returns the number of lines of content contined
in the text area component int getLineEndOffset(int line) Determins the offset of the character at the end
of the secified lice, relative to the beginning of the document
int getLineOffOffset(int offset) Translates the specifiedncharacter offset, relative to the beginning of the document, into a line number
int getLineStartOffset(int line) Returns the offset of the first character of the specified line, relative to the beginning of the document
boolean getLineWrap() Indicates the line-wrapping policy of the text area
Dimension getPreferredScrollable Returns the preferred size of the viewport that
ViewportSize() contains this component Dimension getPreferredSize() Returns the preferred size of the text area protected int getRowHeight() Indicates the height of a row int getRow() Returns the number of rows in the text area boolean getSrollabeTracks ViewportWidth() Indicates if he text area’s view port forces the
text area to have the view port’s width int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the unit increment that enables one whole row to be scrolled up or down
int getTabSize() Gets the number of character equivalent to a tab
String getUIClassID() Returns the class ID for the UI boolean getWrapStyleWord() Gets the wrap-style used when wrapping is
enabled void insert(String str, int pos) Insertsthe specified textat the specified position boolean inManagingFocus() Disables the traversal effect of tabs protected String paramString() Returns a string representation of the text area
void replaceRange(String str, int start, int end) Replaces the txt delineated by the specified start and end position with the new text specified.
void setColumns(int columns) Sets this text area’s number of columns. void setFont(Font f) Sets the current font used to display the text
area’s content void setLineWrap(boolean wrap) Sets the line-wrapping policy of the text area void setRow(int rows) Sets the number of rows for this text area Void setTabSize(int size) Sets the number of characters to be equivalent
to a tab void setWrapStyleWord(boolean word) Sets the wrap style used when line wrapping is
ตัวอยางที่ 1.20 แสดงการใชงาน JTextBox /*-------------------------file TextAreaDemo.java--------------------------------*/ import java.awt.*; import javax.swing.*; public class TextAreaDemo extends JPanel { public TextAreaDemo() { //สราง Container แบบ Box Box box = Box.createVerticalBox(); //กําหนดขนดของจอภาพ Dimension dim =new Dimension(100,600); StringBuffer str = new StringBuffer(); str.append("Stretch (a bolw) to the very full,\n"); str.append("And yo will wish you had stopped in time.\n"); str.append("Temper a (sword-edge) o its very sharpest \n"); str.append("And the wdge will not last long. \n"); str.append("When gold and jade fill yor hall, \n"); str.append("You will not be able to keep them safe. \n"); str.append("To be proud with wealth and honor \n"); str.append("is to sow th seeds of one's own downfull. \n"); str.append("Retire when your work is done \n"); str.append("Such is Heaven's way, \n"); //สราง TextArea ดานบน JTextArea textArea1 = new JTextArea(str.toString(),6,25); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setFont(new Font("Serif",Font.PLAIN,18)); //สรางขอความที่จะนําไปแสดงไวที่ textareaที่ 1 (ดานลาง) str=new StringBuffer(); str.append("To yield is to be preserved whole \n");
str.append("To be bent is to become straight \n"); str.append("To be hollow is to be filled. \n"); str.append("To be tattered is to be renewed. \n"); str.append("To be in want is to possess. \n"); str.append("To have plenty is to be confused.\n"); //สราง TextArea ที่สอง(ดานลาง) JTextArea textArea2 = new JTextArea(str.toString(),6,25); textArea2.setLineWrap(true); textArea2.setWrapStyleWord(true); textArea2.setFont(new Font("Serif",Font.ITALIC,18)); //สราง ScrollPane ไวใน TextArea JScrollPane sp1 = new JScrollPane(textArea1); JScrollPane sp2 = new JScrollPane(textArea2); box.add(sp1); box.add(Box.createVerticalStrut(20)); box.add(new JScrollPane(textArea2)); add(box); } public static void main(String[] args) { TextAreaDemo app = new TextAreaDemo(); JFrame f=new JFrame("Text Area Demo"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.getContentPane().add(app); f.pack(); f.show(); } }
Creates a slider with the secified orientation, minimum,maximum, and initial value
Hashtable createStandardLabels(int increment)
Creates a hashtable that stores the labels for the slider’s has marks. The hash marks appear at each interval specified by the increment argument, from the minimum to maximum vaues.
Creates a hashtable that stores the labels for the slider’s has marks, which appear at each interal specified by the increment argument, starting at the secified starting value.
protected void fireStateChanged() Notifies listeners of the occurrence of aChangeEvent on this slider
AccessibleContext getAccessibleContext() Gets the AccessibleContext associates wih this JComponent
int getExtent() Returns the values of the slider’s Extent, which is the range of values spanned by the slider’s knob
boolean getInverted() Returns true if the slider’s scale is marked I inverse, that is, descending from left-to-right or top-to-bottom.
Dictionary getLabelTable() Returns the dictionary object tat stores an associatve set of labels and values.
int getMajorTickSpacing() Rturns the valueof theinterval at which major ticks are spaced.
int getMaximum() Returns the maximum value supported by the slider.
int getMinimum() Returns the minimum value supported by the slider.
int getMinorTickSpacig() Returns the value of the interval at which minor ticks are spaced.
BoundedRangeModel getModel() Returns the data model that defines the slider’s minimum, maximum, and current value prperty
int getOrientation() Returns this slider’s orientation, either JSlider.VERTICAL or JSlider.HORIZONTAL
boolean getPaintLabeles() Indcates if labels are painted. boolean getPaintTicks() Indicates if tick marks are painted. boolean getPaintTrack() Indicates if the track, the area in which the slider
slides, should be painted. boolean getSnapToTicks() Indicates if the knob position and the slider’s
data value are always set to th value of the tick mark that is closest to the point where the user
positioned the knob. SliderUI getUI() Gets the UI object that implements the L&F
forthis component. String getUIClassID() Returns the name of the L&F class that renders
this component. int getValue() Returns the slider’s value. boolean getValueISAdjusting() Indicates if theb slider’s knob is currently begin
dragged. protected String paramString() Returns the string representation of this JSlider void removeChangeListener(ChangeListener l) Remove a listener previously registerd for
change event notification void setExtent(int extent) Sets the slide’s extent, which is the size of the
range spanned by the slider’s knob. void setIverted(boolean b) Sets the policy for marking the tick slider’s
marks. A value of true indicates that the marks should be drawn descending from left-to-right for from top-to-bottom.
void setLabelTable(Dictionary labels) Sets the dictionary that stores the association between slider values and their labels.
void setMajorTickSpacing(int n) Sets the major tick spacing interval void setMaximum(int maximum) Sets the maximize value of the model void setMinimum(int minimum) Sets the minimize value of the model void setMinorTickSpacing(int n) Set s the minor tick spacing interval void setMode(BoundedRangeModel newModel)
Sets the slider’s model to the specified object
void setOrientation(int orientation) Sets the scrollbar’s orientation. Valid values are JSlider.VERTICAL or JSlider.HORIZONTAL
void setPaintLabels(boolean b) Sets the policy for a painting labels on the slider. void setPaintTicks(boolean b) Sets the policy for painting tick marks on the
slider void setPaintTrack(boolean b) Sets the plicy for painting the track on the slider
void setSnapToTicks(boolean b) Sets the policy for positioning the knob. If true, the knob is always positioned at the tick mark cleses to the location where it was last placed by the user.
void setUI(SliderUI ui) Sets the UI oject that implements the Look and Feel for this component
void setValue(int n) Sets the slider’s curret value. void setValueIsAdjusting(boolean b) Sets the state to indicate if the model’s value is
currenly adjusting. protected void updateLabelUIs() Update the label UIs with the latest versions
from the UIFactory. This is called internallywhen the UIFactory notifiesthe slider that the Look & Feel has changed.
void updateUI() Notifies the UIFactory that the Lok & Feel has changed.
ตัวอยางที่ 1.22 แสดงการสราง Slider ทั้งแนวตั้งและแนวนอน /*--------------------file SliderDemo.java--------------------------*/ import java.awt.* ; import javax.swing.* ; public class SliderDemo extends JPanel { public SliderDemo() { JLabel msg = new JLabel("Set your ideal temperature(Celsius)"); //create horizontal slider JSlider horSlider = new JSlider(); horSlider.setMinimum(-20); //defined minimume values horSlider.setMaximum(50); //defined maximum values horSlider.setValue(27); //defined initial values horSlider.setPaintTicks(true); //กําหนดใหมีเสนขีดใหญและเสนขีดยอย
Constructors/Methods คําอธิบาย JMenu() No-arguments constructor. I creates a new
JMenu with no text Label. JMenu(String s) Creates a new JMenu with thespecified string
as its text lael. JMenu(String s, boolean b) Creates a new JMenu with the specified string
as its text label. The boolean argument specified whether or not the menu is tear-off menu. A tear-off menu can exist in its own window even after the pop-up window of its parent menu is closed.
Component add(Component c) Appends the specified component to the end of the menu.
JMenuItem and(JMenuItem menuItem) Appends the specified menu item to the end of the menu.
JMenuItem add(String s) Creates a new item with the specified text. The menu item is appended to the end of the menu.
void addMenuListener() Adds the specified listener for menu events on this menu.
void addSeparator() Appends a new separator to the end of the menu. Separator are rendered as raised horizontal line.
void doClick(int pressTime) Programmatically perform a selection of the menu that simulates the user clicking on the menu.
Component getComponent() Returns the component that paints this menu. int getDelay() Returns the value of the time delay that
transpires before the menu’s pop-up is popped up or down.
JMenuItem(getItem(int pos) Returns the JMenuItem located at the specified position.
int getItemCount() Returns the number of items on the menu, including separator.
Component getMenuComponent(int n) Returns the component at the specified position int getMenuComponentCount() Returns the number of componentin the menu Components[] getMenuComponents() Returns an array of the menu’s subcomponents. JPopupMenu getPopupMenu() Returns this menu’s pop-up menu. MenuElement[] getSubElements() Returns an array of the submenu components
for this menu. String getUIClassID() Returns the name of Look and Feel class tha
MenuItem insert(Action a, int pos) Insert a new menu item at the specified position in the menu. The specified Actionobject is registered as an actonlistener on the new menu item.
JMenuItem insert(JMenuItem mi, int pos) Inserts the specifed JMenuItem at the specifed position.
void insert(String s, int pos) Constructs a new menu item with the specified text and insert it at the specified position.
void insertSeparator(int index) Inserts a separator at the specified position. boolean isMenuComponent(Component c) Return true if the specified component is a
submenu of this menu. boolean isPopupMenuVisible() Indicates if the menu’s pop-up window is
visible. boolean isSelected() Indicates if the menu is currently selected
(poped up) boolean isTearOff() Inicates if the menu is a tear-off menu-that is, if
it can be torn from its cotaining menu or menu bar.
boolean isisTopLevelMenu() Idicates if the menu is a top-level menu, that is, if it is the direct child of a menu bar.
void MenuSelectionChanged(boolean isIncluded)
Changes the selection state of this menu.
void remove(Component c) Removes the specified component from this menu.
void remove(int pos) Removes the menu item located at the specified indexfrom this menu.
void remove(JMenuItem item) Removes the specified menu item from this menu
void removeAl() Removes all this menu’s items. void setAccelerator(KeyStroke keystroke) Does nothing for the JMenu class. void setDelay(int d) Sets the delay time that transpires before the
munu’s pop-up menu is poped up or down. void setMenuLocation(int x, int y) Sets the location of the pop-up menu
component void setModel(ButtonModel newModel) Sets the data model for the menu item void setPopupMenuVisible(boolean b) Sets the visibility of the menu’s pop-up
portion. void setSelected(boolean b) Sets the selection status of the menu. Construcstors และ Methods ของ class JMenuBar
Connstructors / Methods คําอธิบาย JMenuBar() No-argument constructor.It creates a new menu bar JMenu add(JMenu c) Appends the specified menu to the end of the
menubar. AccessibleContext getAccessibleContext() Gets the acessibleContext associated with this menu
bar. Component getComponent() Returns the component that is used to paint the
menu bar. The component determines if event occurs inside the menu bar.
Component getComponentAtIndex(int i) Returns the componentat the specified index int getComponentIndex(Component c) Returns the index of the specified component. JMenu getHekpMenu() Gets the help menu for the menu bar. The help
menu is the far right menu. Insets getMargin() Returns the insets object that defined the margin
between the menu bar’s border and its menu. JMenu getMenu(int index) Reurns the menu located at the specified position in
the menu bar int getMenuCount() Returns the number of menu elements in the menu
bar. SingleSelectionMode getSelectionModel() Returns the model object used by the menu bar. MenuElement[] getSubElements() Returns array of all the menus contained in this
boolean isBorderPainted() Indicates if the menu bar’s policy is t paint its border.
boolean isManagingFocus() Indicates if the menubar manages focus events internally.
boolean isSelected() Indicates if one of the menu bar’s menu elements is currently selectd.
void menuSelectionChange(boolean isIncluded)
Currentsly does nothing, but must be implemented to fulfill the requirement to implement the MenuElement interface.
void setBorderPainted(boolean s) Sets the menu bar’s policy for painting its border. void setHelpMenu(JMenu menu) Sets the help menu for this menu bar, which appears
when the user selects the Help menu. The help menu is always placedto the far right of the menu.
void setMargin(Insets margin) Sets the insets object that defines the margin between the menu bar’s border and its menus.
void setSelected(Compont sel) Sets the currenty selected component; results in a change tothe state of themenu bar’s selection model.
specified text and icon. JMenuItem(Stringtext, int mnemonic) Creates a menu item that displays the specified
text and keyboard mnemonic, represented by an underline beneath the mnemonic character in the menu item’ s text.
Ketstroke getAccelerator() Returns the DeyStroke object that is the accelerator for the menu itex.
AccessibleCntext getAccessileContext() Gets the AccessibleContext associated with this menu item.
Component getComponent() Returns the component used to paint the menu item.
MenuElement[] getSubElements() Returns the an array of the submenu components of this menu item. This menu item must be a menu to contain submenus.
String getUIClassID() Retums the name of the L&F class that reners this component.
Protected void init (String text, Icon icon) Initializes the string and icon displayed for the menu item with the specified quantities.
boolean isArmed() Indicates whether the menu item is Armed. An armed button is one that has been pressed but not released.
Void menuSeectionChanged (boolean isIncluded)
Sets the menu item’s state when it is selected or deselected. It is called by the MenuSelectionManager, not applications.
void setAccelerator(KeyStroke keystroke) Set the KeyStroke object that represents the key combination which selects the menu item. This is equivalent to the user selecting the menu item.
void setArmed(boolean b) Sets the state of the menu item to Armed or Not Armed.
void setEnabled(boolean b) Sets the enabled or disabled state of the menu item.
1.15 Popup Menu Popup Menu คือ Menu ที่จะปรากฏขึ้นเมื่อคลิกเมาสปุมขวา โดยสามารถสรางขึ้จาก Class JPopupmenu ซ่ึงมี Constructors และ Methods ที่สําคัญดังนี ้
Constructors/Methods ความหมาย public JPopupMenu() สราง Popup Menu public JPopupMenu(String label) สราง Popup Menu โดยระบุช่ือผาน label เพื่อ
ใชอางถึงในการทํางาน public JPopupMenu add(JMenuItem menuItem) เพิ่ม Menu Item ใหกับ Popup Menu public void addSeparator() แทรกเสนคั่นระหวาง Menu Item ใน Popup
Menu public Component getComponent() คืนคา Component กลับมา public int getComponentIndex(Comonent c) คืนคาตําแหนง Component ที่ระบุ pulic void setBorderPainted(boolean b) กําหนดการแสดง Border ใหกับ Popup Menu
ProgressBarUI getUI() Returns the L&F object that renders this component
String getUIClassID() Returns the name of the L&F class that renders this component
int getValue() Returns the current value of the model boolean inBorderPainted() Indicates if a border is painted around the
progress bar boolean inStringPainted() Indicates if the progress bar will paint a
progress string onto the progress bar protected void paintBorder(Graphics g) Paints the progress bar’s border, if the
BorderPainted property is True protected String paramString() Returns a string representation of the
JProgressBar void setBorderPainted(boolean b) Sets the progress bar’s policy for painting its
border void setMaximum(int n) Sets the model’s maximum value to x void setMinimum(int n) Sets the model’s minimum value to x void setModel(BoundedRangeModel newModel) Sets the data model used by the JProgressBar void setOrientation(int newOrientation) Sets the progress bar’s orientation to the
specified value, which must be either JProgressBar.VERTICAL or JProgressBAr.HORIZONTAL
void setString(String s) Sets the value of the progress string void setStringPainted(boolean b) Sets the progress bar’s policy for painting the
progress string void setUI(ProgressBarUI ui) Sets the L&F object that render this component void setValue() Sets the model’s current value to x void updateUI() Notification from the UIFactory that the L&F
ตัวอยางที่ 1.24 แสดงการสราง Progress bar /*---------------file JProgressBarDemo.java---------------*/ import java.awt.*; import javax.swing.*; public class JProgressBarDemo extends JFrame { JLabel message; JProgressBar pb; public JProgressBarDemo() { super("Progress Bar Demo"); Box box= Box.createVerticalBox(); Dimension dim = new Dimension(0,10); Container c = getContentPane(); message = new JLabel("This lebel is not part of the progress bar"); pb = new JProgressBar(0,100); pb.setMaximum(100); pb.setValue(0); pb.setStringPainted(true); box.add(message); box.add(Box.createRigidArea(dim)); box.add(pb); c.add(Box.createVerticalStrut(30),BorderLayout.NORTH); c.add(Box.createHorizontalStrut(30),BorderLayout.WEST); c.add(box,BorderLayout.CENTER); c.add(Box.createHorizontalStrut(30),BorderLayout.SOUTH); c.add(Box.createHorizontalStrut(30),BorderLayout.EAST); } private void updatebar() { for(int i=0;i<=100;i++) { pb.setValue(i); //แสดงตวัเลขเปนเปอรเซ็นตในแถบ Progress Bar
Constructs a new JPlitPane with the specified orientation and with the specified components. This new constructor does not do continuous redrawing.
AccessibleContext getAccessibleContext() Get the AccessibleContext associated with this JComponent.
Component getBottomComponent() Returns the bottom or right component. int getDividerLocation() Gets the location of the divider from the L&F
implementation. int getDividerSize() Gets the size of the divider. int getLastDividerLocation() Gets the divider’s last location Component getLeftComponent() Returns the top or left component. int getMaximumDividerLocation() Returns a UI specific value for the maximum
location of the divider. int getMinimumDividerLocation() Returns a UI specific minimum location value
of the divider. int getOrientation() Returns the split pane’s orientation. Component getRightComponent() Returns the right or bottom component Component getTopComponent() Returns the top or left component. splitPaneUI getUI() Returns the SplitPaneUI that is providing the
current L&F. String getUIClassID() Returns the name of the L&F class that renders
this component. boolean isContinuousLayout() Indicates the currently set redrawing behavior. boolean isOneTouchExpandable() Indicates if the pane has a UI widget to
int getTabPlacement() Returns the side at which the tabs are placed in this tabbed pane.
int getTabRunCount() Returns the number of rows (for top or bottom placement) or columns (for left or right placement) currently used ot display the pane’s tabs.
String getTitleAt(int index) Returns the title of the tab at the specified index.
String getTollTipText(MouseEvent event) Returns the ToolTip text for the component that is located at the position where the mouse event occurred.
TabbedPaneUI getUI() Returns the UI object that implements the L&F for this component.
String getUIClassID() Returns the name of the UI class that implements the L&F for this component.
int indexOfcomponent (Component component)
Returns the index of the tab that contains the specified component.
int indexOfTab(Icon icon) Returns the index of the first tab with the specified icon.
int indexOfTab(String title) Returns the index of the first tab with the specified title. Returns -1 if no tab has the specified title.
void insertTab (String title, Icon icon, Component component, String tip, int index
Inserts a component at the specified index. The new tab displays the specified text and icon. If not null
Boolean isEnabledAt(int index) Indicates if the tab located at the specified index is currently enables.
void remove(Component component) Removes the specified component’s tab. void removeAll() Removes ass the pane’s tabs. void removeChangeListener (ChangeListener 1)
Removes a listener for change evens form this tabbed pane.
Sets the specified icon to indicate the disabled state for the tab at the specified index.
void setEnabledAt (int index, boolean enabled)
Indicates if the tab at the specified index is enabled or not.
void setForegroundAt (int index, Color foreground)
Sets the foreground olor of the tab at the specified index to the specified color. If the color is null, the tab’s foreground color will be set to the foreground color of the tabbed pane.
void setIconAt (int index, Icon icon) Sets the specified icon to be the icon of the tab at the specified index.
void setModel (SingleSelectionModel model) Sets the pane’s model to the indicated object. void setSelectedComponent (Component c) Sets the specified component to the selected
state. void setSelectedIndex (int index) Sets the tab at the specified index to the
selected state. void setTabPlacement (int tabPlacement) Specifies that the tabs should be placed on the
side specified for this pane-TOP, LEFT, or BOTTOM.
void setTitleAt (int index, String title) Sets the title of the tab at the specified index to the specified string.
void setUI(TabbedPaneUI ui) Set the UI object that implements the L&F for this component.
void updateUI() Notifies the pane that the L&F has changed.
FileSystemView fsv) file system view to display the contents of the directory represented by the specified string.
boolean accept(File f) Indicates if the specified file should be displayed-True if yes; False otherwise.
void addActionListener(ActionListener l) Adds an ActionListener to the button. void addChoosableFileFilter(FileFilter filter) Adds a filter to the list of filters that appear in
the Files of Type combo box. void approveSelection() Changes the object’s state in response to being
called by the UI when the user hits the Aprove button, also known as the Open or Save button.
void cancelSelection() Changes the object’s state in response to being called by the UI when the user hits the cancel button.
void changeToParentDirectory() Sets the directory viewed by the file chooser to be the parent of the currently viewed directory.
void ensureFilesVisible(File f) Scrolls the display to make the specified file visible.
FileFilter getAcceptAllFileFilter() Returns the file filter that accepts all matches. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this
JFileChooser. JComponent getAccessory() Returns the accessory component int getApproveButtonMnemonic() Returns the mnemonic for the Approve button.
The Approve button is the Open or Save button by which the user approves the operation.
String getApproveButtonText() Returns the text used in the Approve Button in the FileChooserUI.
String getApproveButtonToolTipText() Returns the Approve button’s ToolTip text. FileFilter[] getChoosableFileFilters() Retrieves an array of all the file filters that the
user can select. File getCurrentDirectory() Returns a file object that represents the current
String getDescription(File f) Returns a string that describes the specified file.
String getDialogTitle() Retrieves the string displayed in the file chooser’s title bar.
int getDialogType() Returns the type of the file chooser dialog. FileFilter getFileFilter() Returns the file filter that is currently selected. int getFileSelectionMode() Returns the mode currently used for file
selection. FileSystemView getFileSystemView() Returns the fileSystem view object currently
used. FileView getFileView() Returns the file view currently used, The file
view provides a platform-independent view of a file.
Icon getIcon(Flie f) Returns the icon for the secified file or file category to which the file belongs. The icon used is governed by the underlying file system.
String getName(File f) Returns the string name of the specified file. File getSelectedFile() Returns the file object that represents the
currently selected file. File[] getSelectedFiles() Returns an array of file objects that represents
all files currently selected. String getTypeDescription(File f) Returns the type of the fie represented by the
specified file argument. FileChooserUI getUI() Gets the UI object that implements the L&F
for ths component String getUIClassID() Returns a string that specifieds the name of the
L&F class that renders this component boolean isDirectorySelectionEnabled() Indicates whether or not directories can be
selected, based on the current file selection mode
boolean isFileHidingEnabled() Indicates the file chooser’s policy for
void setDialogType(int dialogType) Sets the type of this dialog; alid values are JFileChooser.OPEN_DIALOG, JFileChooser.SAVE_DIALOG,or JFileChooser.CUSTOM_DIALOG.
void setFileFilter(FileFilter filter) Sets the current filter used to filter files displayed in the view.
void setFileHidingEnabled(boolean b) Sets the polcy for hiding files. void setFileSelectionMode(int mode) Sets the ile chooser’s behavior for selecting file
system elements to display; valid values are JFileChooser.FILES_ONLY, JFileChooser.DIRECTORIES_ONLY,or JFileChooser.FILES_AND_DIRECTORIES.
void setFileSystemView(FileSystemView fsv) Sets the file system view used by the file chooser to discern and represent platform-specified file system information in a platform-independent manner.
void setFileView(FileView fileView) Sets the file view used by the file chooser to retrieve UI information
void setMultiSelectionEnabled(boolean b) Sets the selection policy of the file chooser to that represented by the argument. A value of true allows multiple selections; false allows single selections.
void setSelectedFile(File selectedFile) Sets the specified ile to the selected state. void setSelectedFile(File[] selectedFiles) Sets each of the files in the specified array to
the selected state, if the file chooser currently allows multiple selections.
protected void setup(FileSystemView view) Set the configuration of the file chooser to use the specified file system view.
int showDialog(Component parent,String ApproveButtonText)
Displays a custom dialog with the specified text as the Approve button text. The specified parent is this file chooser.
Constructors / Methods ความหมาย JToolTip() No-arg constructor that creates aToolTip AccessibleContext getAccessibleContext() Gets the AccessibeContext associated with this
component JComponent getComponent() Returns the component that the ToolTip
represents String getToolTipText() Returns the text that is displayed when the
ToolTip is activated ToolTipUI getUI() Returns the L&F object that renders this
component String getUIClassID() Returns the name of the L&F class that renders
this component protected String paamString() Returns a string representation of this
JToolTip void setComponent(JComponent c) Sets the component that the TolTip will
represent void setToolTipText(string tipText) Sets the text that is displayed when the ToolTip
is activated void updateUI() Indcates that the L&F has changed ตัวอยางที่ 1.29 แสดงการสราง ToolTip /*------------------------file ToolTips.java ------------------------*/ import java.awt.* ; import javax.swing.* ; public class ToolTips extends JPanel { public ToolTips() { JButton button1= new JButton("Do Something"); button1.setToolTipText("Describes what means to 'do something'"); JButton button2 = new JButton("Do Nothing"); button2.setToolTipText("T think his is pretty self-explanatory"); add(button1); add(button2); } public static void main(String[]args) { JFrame f = new JFrame("Tool Tips Demo"); ToolTips app = new ToolTips(); f.getContentPane().add(app); f.pack(); f.setVisible(true);
Constructors / Methods ความหมาย public JColorChooser() สราง ColorChooser โดยมีคาเริ่มตนเปน
color.white public JColorChooser(Color c) สราง ColorChooser โดยมีคาเริ่มตนตามที่
กําหนด public Color getColor() คืนคาสีที่เลือกจาก Color chooser กลับมา pubic static Color showDialog(Component component,String title,Color initialColor) throws HeadlessException)
สรางและแสดง ColorChooser ในแบบ modal dialog โดยเมือ่เลือกสีเสร็จแลวและมกีารกดปุม OK dialog ก็จคืนคาสีที่เลือกกลับมา แตถาปุม Cancle ก็จะคนืคาสีปจจุบัน โดย Component คือ parent component ที่สราง dialog ขึ้นมา tile คือขอความ title bar ที่ตองการกําหนดและ initialColor คือคาสีเร่ิมนที่ตองการเลือก
public void clearSelection() เคลียรคอลัมนและแถวทีเ่ลือกไว public int getAutoResizeMode() คืนคา auto resize mode ของ table คา default เปน
AUTO_RESIZE_SUBSEQUENT_COLUMNS public String getColumnName(int column) คืนคาชื่อคอลัมนที่ระบ ุpublic TableModel getModel() คืนคา data model ของ table เปน TableModel
Object public int getRowCount() คืนคาจํานวนแถว public getColumnCount() คืนคาจํานวนคอลัมน public void setAutoResizeMode(int mode) กําหนดการ auto resize table โดยคา mode ที่
public void stGridColor(Color gridColor) กําหนดสีใหกบั grid ผาน gridColor public setModel(TableModel dataModel) กําหนด data table model ใหกับ table public void setPreferredScrollableViewportSize
public int getColumnCount() คืนคาจํานวน column ของ DefaultTableModel public int getRowCount() คืนคาจํานวน row ของ DefaultTableModel public Object getValueAt(int row, int column) คืนคา Object ในตําแหนง row และ column public void removeRow(int row) Remove แถวออกจาก data table model ตาม
index ที่กําหนด public void setValueAt(Object aValue,int rw,int column)
กําหนดขอมูลใหกับ data table model ในตําแหนงที่ row และ column ที่กําหนด
ตารางแสดงคาคงที่และ Method ของ Class JDialog ท่ีสําคัญ คาคงที่/Method ความหมาย
public static final int DISPOSE_ON_CLOSE ทําลายและปด Window โดยอัตโนมัติ(ยังคงอยูในโปรแกรม)
public static final int EXIT_ON_CLOSE ออกจากโปรแกรมและปด Window อัตโนมัติ public static final int DO_NOTHING_ON_CLOSE
ปองกันการกดปุม Close (เมื่อกดแลวไมปด window)
public static final int HIDE_ON_CLOSE ปดแลวซอน Window โดยอัตโนมัติ public JDialog() สราง Dialog แบบไมเปน modal public JDialog(Dialog owner) สราง Dialog แบบไมเปน modalโดยระบวุา
คาคงที่/Method ความหมาย public static final int CROSSHAIR_CURSOR Cursor แบบ Crosshair public static final int DEFAULT_CURSOR Cursor แบบ Default public static final int TEXT_CURSOR Cursor แบบ Text public static final int WAIT_CURSOR Cursor แบบ Wait public static final int SW_RESIZE_CURSOR Cursor แบบ south-west-resize public static final int SE_RESIZE_CURSOR Cursor แบบ south-east-resize public static final int NW_RESIZE_CURSOR Cursor แบบ north-west-resize public static final int NE_RESIZE_CURSOR Cursor แบบ north-east-resize public static final int N_RESIZE_CURSOR Cursor แบบ north-resize public static final int S_RESIZE_CURSOR Cursor แบบ south-resize
public static final int W_RESIZE_CURSOR Cursor แบบ west-resize public static final int E_RESIZE_CURSOR Cursor แบบ east-resize public static final int HAND_CURSOR Cursor แบบ Hand public static final int MOVE_CURSOR Cursor แบบ Move public Cursor(int type) Constructor ใชสราง Cursor ตามในรปูแบบ
ตางๆโดย type หมายถึงคาคงที่ของ Cursor ตามชนิดที่ตองการสรางตางๆ
public java.awt.Rectangle.getBounds() จะเห็นวา Method ดังกลาวจะคืนคามาเปน Rectangle Object ซ่ึง Class นี้จัดเก็บอยูใน Package java.awt โดยมีตัวแปรและ Method ที่สําคัญดังนี ้ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class Rectangle
คาคงที่/Method ความหมาย public int height เก็บความสูงของ Component public int width เก็บความกวางของ Component public int x เก็บตําแหนง x coordinate public int y เก็บตําแหนง y coordinate public Rectangle() สราง Rectangle มีความกวางและความสูงตามที่
กําหนด สวน x,y มีคาเปน 0 public Rectangle(Diamension d) สราง Rectangle ตาม Dimension ที่กําหนด public Rectangle(int width , int height) สราง Rectangle มีความกวางและความสูงตามที่
กําหนด สวน x,y มีคาเปน 0 public Rectangle(int x, int y ,int width , int height)
การทํางานของโปรแกรม Class useBounds มี Method displayBound() ใชสําหรับแสดงชื่อ Component ตําแหนง x, y และความสูง กวางของ Component ที่สงเขามา จากตัวอยางมี Frame f ซ่ึงมี layout เปน Flow layout หลังจาก add Text Field “text” และ Button b1 ใหกับ Component แลว หลังจากนั้นก็เรียกใช Method displayBound() พรอมกับสงคา b1 เปน parameter ใหกับ Method ซ่ึงคา Bound ของ Component ที่แสดงออกมาจะเปนดังผลลัพธ 1.28 Point Class Point ใชสําหรับเก็บคา coordinate x และ y ของจุดๆหนึ่ง ซ่ึงมตีัวแปรและ Method ที่สําคัญดังนี ้ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class Point
คาคงที่ / Method ความหมาย public int x เก็บคา x Coordinate public int y เก็บคา y Coordinate public Point() สราง Point ที่มีจุด Origin เปน (0,0) public Point(int x, int y) สราง Point ที่มีจุด Origin เร่ิมตนที่ x,y ที่กาํหนด public double getX() คืนคา Coordinate x ของ Point เปน double public double getY() คืนคา Coordinate y ของ Point เปน double หากตองการจดัการอยางใดอยางหนึ่งเกี่ยวกับ Point เราสามารถเรียกใช Method ของ Class Component เหลานี้ขึ้นมาทาํงานได
Method ความหมาย public void setLocation(Point p) เล่ือนตําแหนงการแสดงของ Component ไปยัง
ตําแหนง Point ที่ตองการ public Point getLocation() คืนคาตําแหนงจุดที่ Component วางอยูบน top-
public Point getLocationOnScreen() คืนคาตําแหนงจุดที่ Component วางอยูบนจอภาพกลับมาเปน Point Object แตหาก Component ดังกลาวยังไมสามารถมองเห็นไดบนจอภาพก็จะเกดิ illegalComponentStateException
ตัวอยางที่ 1.39 แสดงการใชงาน Point /*--------------------file usePoint.java ----------------------*/ import java.awt.* ; import javax.swing.* ; public class usePoint extends JPanel { static JButton b1; public usePoint() { setLayout(new FlowLayout()); b1=new JButton("OK"); add(new JLabel("Test Point")); add(b1); } public static void disPlayPoint(Component comp) { if(comp != null) { Point pointOnContainer = comp.getLocation(); Point pointOnScreen = comp.getLocationOnScreen(); System.out.println("Point on top-level window component"); System.out.println("\t x coordinate :"+pointOnContainer.getX()); System.out.println("\t y coordinate :"+pointOnContainer.getY()); System.out.println("Point on Screen"); System.out.println("\t x coordinate :"+pointOnScreen.getX()); System.out.println("\t y coordinate :"+pointOnScreen.getY()); } else return ; } public static void main(String[] args) {
คาคงที่และ Method ความหมาย public static final int CANCEL_OPTION คาคงที่ของปุม Cancel public static final int CLOSE_OPTION คาคงที่ของปุม Close public static final int OK_OPTION คาคงที่ของปุม Ok protected transient Object[] options คาคงที่ของปุมที่กําหนดขึ้นอง public static final int YES_OPTION คาคงที่ของปุม Yes public static final int ERROR_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type
ประเภท Error Message public static final int INFORMATION_MESSAGE
คาคงที่ใชกําหนด Icon ของ Message type ประเภท Information Message
public static final int WARNING_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Warning Message
public static final int QUESTION_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Question Message
public static final int PLAIN_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Plain Message
public static final int DEFAULT_OPTION คาคงที่ใชกําหนดปุม option button โดย Default
ที่ตองการแสดงบน Dialog ขอความบน title bar และ option type ผาน message ,title, option type และ icon ตามลําดับ และคืนคากลับมาเปน int ตามคาคงที่ของปุมตางๆ
public static String showInputDialog(Component parentComponent, Object message)