Draw a Circle in J Scroll Pane Java

Java Programming Tutorial

Programming Graphical User Interface (GUI) - Part 2

JDK demo includes a folder "jfc", which has many interesting demo on Swing and Java2D.

More on Swing's JComponents

The form hierarchy of Swing's top-level containers (JFrame, JDialog, JApplet) are as follows. These top-level Swing containers are heavyweight, that rely on the underlying windowing subsystem of the native platform.

Swing_ContainerClassDiagram.png

The form hierarchy of Swing'south JComponentsouth is as follows. JComponent and its descendants are lightweight components.

Swing_JComponentClassDiagram.png

ImageIcon

Swing_ButtonIcon.png

Many Swing's JComponents (such every bit JLabel and JButton) support a text label and an image icon. For example, the figure shows three buttons: i with text characterization, ane with an image icon, and ane with both text and icon.

The javax.swing.ImageIcon class models an epitome icon. An ImageIcon is a fixed-size picture, typically pocket-size, and mainly used for decorating GUI components. The ImageIcon grade implements javax.swing.Icon interface, and hence, often upcasted and referenced as Icon.

To construct an ImageIcon, provide the prototype filename or URL. Paradigm file blazon of GIF, PNG, JPG and BMP are supported. For example,

            String imgFilename = "images/duke.png";        ImageIcon iconDuke =          new ImageIcon(imgFilename);           ImageIcon iconDuke = null; String imgFilename = "images/knuckles.png"; java.net.URL imgURL =          getClass().getClassLoader().getResource(imgFilename);        if (imgURL != null) {    iconDuke =          new ImageIcon(imgURL);          } else {    System.err.println("Couldn't notice file: " + imgFilename); }

Using URL is more flexible equally information technology can admission resources in a JAR file, and produces an error message if the file does not exist (which results in a null URL).

Many JComponents (such equally JLabel, JButton) accepts an ImageIcon in its constructor, or via the setIcon() method. For example,

ImageIcon iconDuke = null; String imgFilename = "images/knuckles.gif";   URL imgURL = getClass().getClassLoader().getResource(imgFilename); if (imgURL != null) {    iconDuke =  new ImageIcon(imgURL); } else {    System.err.println("Couldn't detect file: " + imgFilename); }          JLabel lbl =          new JLabel("The Duke", iconDuke, JLabel.CENTER);          lbl.setBackground(Color.LIGHT_GRAY); lbl.setOpaque(true);   Container cp = getContentPane(); cp.add(lbl);

An ImageIcon uses an java.awt.Paradigm object to hold the paradigm data. You tin call back this Image object via the ImageIcon'southward getImage() method. The Image object is used in the drawImage() method for custom drawing (which shall be discussed later).

Setting the Appearances and Backdrop of JComponents

Virtually of the Swing Components supports these features:

  • Text and icon.
  • Keyboard short-cutting (called mnemonics), eastward.g., activated via the "Alt" key in Windows Arrangement.
  • Tool tips: brandish when the mouse-arrow pauses on the component.
  • Look and feel: customized appearance and user interaction for the operating platform.
  • Localization: different languages for different locale.

All JComponents (such as JPanel, JLabel, JTextField and JButton) back up these set methods to set up their appearances and properties:

            public void          setBackground(Colour          bgColor)     public void          setForeground(Color          fgcolor)     public void          setFont(Font          font)     public void          setBorder(Border          border)     public void          setPreferredSize(Dimension          dim) public void          setMaximumSize(Dimension          dim) public void          setMinimumSize(Dimension          dim)    public void          setOpaque(boolean          isOpaque)     public void          setToolTipText(String          toolTipMsg)        

Swing'southward JLabel and buttons (AbstractButton subclasses): support both text and icon, which tin exist specified in the constructor or via the setters.

            public void          setText(String          strText)     public void          setIcon(Icon          defaultIcon)     public void          setHorizontalAlignment(int          alignment)     public void          setVerticalAlignment(int          alignment)     public void          setHorizontalTextPosition(int          textPosition)     public void          setVerticalTextPosition(int          textPosition)        

JTextField supports:

            public void          setHorizontalAlignment(int          alignment)        

Swing's buttons back up mnemonic (to be triggered via keyboard brusque-cut with alt key).

            public void          setMnemonic(int          mnemonic)        
Example

Swing_JComponentSetterTest.png

This case creates 3 JComponents: a JLabel, a JTextField and a JButton, and sets their appearances (background and foreground colors, font, preferred size and opacity). It also sets the horizontal text alignment for the JTextField.

Images:

cross.gif nought.gif

ane two 3 4 v 6 vii 8 9 10 11 12 13 14 xv sixteen 17 eighteen 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 forty 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 sixty 61 62 63 64 65 66 67 68 69 seventy 71 72 73 74 75 76 77 78 79 lxxx 81 82 83 84 85 86 87 88 89 90 91 92
import coffee.awt.*; import java.awt.event.*; import coffee.net.URL; import javax.swing.*;    @SuppressWarnings("series") public form SwingJComponentSetterTest extends JFrame {          private Cord imgCrossFilename = "images/cross.gif";    individual String imgNoughtFilename = "images/nought.gif";          public SwingJComponentSetterTest() {                ImageIcon iconCross = zippo;       ImageIcon iconNought = null;       URL imgURL = getClass().getClassLoader().getResource(imgCrossFilename);       if (imgURL != null) {          iconCross = new ImageIcon(imgURL);       } else {          Organization.err.println("Couldn't observe file: " + imgCrossFilename);       }       imgURL = getClass().getClassLoader().getResource(imgNoughtFilename);       if (imgURL != cipher) {          iconNought = new ImageIcon(imgURL);       } else {          System.err.println("Couldn't find file: " + imgNoughtFilename);       }         Container cp = getContentPane();       cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, ten));                JLabel label = new JLabel("JLabel", iconCross, SwingConstants.Middle);       label.setFont(new Font(Font.DIALOG, Font.ITALIC, fourteen));       label.setOpaque(true);         characterization.setBackground(new Color(204, 238, 241));         label.setForeground(Colour.RED);                        label.setPreferredSize(new Dimension(120, 80));       label.setToolTipText("This is a JLabel");         cp.add(label);                JButton push = new JButton();        push.setText("Button");       button.setIcon(iconNought);       button.setVerticalAlignment(SwingConstants.BOTTOM);         button.setHorizontalAlignment(SwingConstants.Correct);        button.setHorizontalTextPosition(SwingConstants.LEFT);        button.setVerticalTextPosition(SwingConstants.TOP);           button.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 15));       push button.setBackground(new Colour(231, 240, 248));       button.setForeground(Color.BLUE);       button.setPreferredSize(new Dimension(150, 80));       push.setToolTipText("This is a JButton");       push button.setMnemonic(KeyEvent.VK_B);         cp.add(button);                JTextField textField = new JTextField("Text Field", 15);       textField.setFont(new Font(Font.DIALOG_INPUT, Font.Plainly, 12));       textField.setForeground(Color.Cerise);       textField.setHorizontalAlignment(JTextField.RIGHT);         textField.setToolTipText("This is a JTextField");       cp.add(textField);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("JComponent Test");       setLocationRelativeTo(null);        setSize(500, 150);         setVisible(true);                System.out.println(label);       Organisation.out.println(button);       System.out.println(textField);    }          public static void primary(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new SwingJComponentSetterTest();           }       });    } }
javax.swing.JLabel[, 41, x, 120x80, alignmentX=0.0, alignmentY=0.0, edge=, flags=25165832,       maximumSize=, minimumSize=, preferredSize=java.awt.Dimension[width=120,tiptop=lxxx],       defaultIcon=file:.../cross.gif, disabledIcon=,        horizontalAlignment=Middle, horizontalTextPosition=Abaft,       iconTextGap=4, labelFor=, text=JLabel, verticalAlignment=Middle, verticalTextPosition=CENTER] javax.swing.JButton[, 171, 10, 150x80, alignmentX=0.0, alignmentY=0.v,       border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@c5e2cf, flags=424,       maximumSize=, minimumSize=, preferredSize=coffee.awt.Dimension[width=150,elevation=fourscore],       defaultIcon=file:/.../nought.gif, disabledIcon=, disabledSelectedIcon=,       margin=javax.swing.plaf.InsetsUIResource[top=ii,left=14,bottom=2,correct=14],       paintBorder=true, paintFocus=true, pressedIcon=, rolloverEnabled=true, rolloverIcon=,       rolloverSelectedIcon=, selectedIcon=, text=Button, defaultCapable=true] javax.swing.JTextField[, 331, 39, 109x21, layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,       alignmentX=0.0, alignmentY=0.0, edge=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1991de1,       flags=296, maximumSize=, minimumSize=, preferredSize=,        caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],       disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229], editable=truthful,       margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],       selectedTextColor=sunday.swing.PrintColorUIResource[r=51,k=51,b=51],       selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],       columns=15, columnWidth=7, command=, horizontalAlignment=Correct]

The above conspicuously showed that there are many more properties that can be controlled.

Display Area, Edge and Insets

Brandish Surface area

You can employ the following get methods to get the dimensions of the brandish surface area of a JComponent. Each component maintains its own co-ordinates with origin (tiptop-left corner) at (0, 0), width and height. You can also get the origin (x, y) relative to its parent or the screen.

public int getWidth() public int getHeight() public Dimension getSize()     public int getX() public int getY() public Signal getLocation()     public Indicate getLocationOnScreen()        

For example:

1 2 three iv 5 6 7 eight ix 10 11 12 13 14 xv 16 17 18 xix 20 21 22 23 24 25 26 27 28 29 thirty
import coffee.awt.*; import javax.swing.*;   public class TestSize {    public static void main(Cord[] args) {       JFrame frame = new JFrame("Brandish Area");       Container cp = frame.getContentPane();       cp.setLayout(new FlowLayout());       JButton btnHello = new JButton("Hello");       btnHello.setPreferredSize(new Dimension(100, 80));       cp.add(btnHello);         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       frame.setSize(300, 150);         frame.setLocationRelativeTo(nothing);         frame.setVisible(truthful);                      System.out.println(btnHello.getSize());       Organisation.out.println(btnHello.getLocation());       Arrangement.out.println(btnHello.getLocationOnScreen());         System.out.println(cp.getSize());       System.out.println(cp.getLocation());       System.out.println(cp.getLocationOnScreen());         Organization.out.println(frame.getSize());       Arrangement.out.println(frame.getLocation());       System.out.println(frame.getLocationOnScreen());    } }
java.awt.Dimension[width=100,height=80]    java.awt.Point[10=91,y=5]                   java.awt.Point[x=590,y=349]                  coffee.awt.Dimension[width=282,elevation=105]          
java.awt.Point[x=0,y=0]
java.awt.Point[x=499,y=344]
java.awt.Dimension[width=300,height=150]
java.awt.Point[x=490,y=308]
coffee.awt.Indicate[10=490,y=308]

Swing_ComponentDisplayArea.png

Border

Swing supports these border types (in parcel javax.swing.border), which tin be applied to all JComponentdue south:

  1. EmptyBorder: empty, transparent border which takes upwardly infinite simply does no drawing.
  2. LineBorder: line border of capricious thickness and of a single color.
  3. TitledBorder: with the improver of a String title in a specified position and justification.
  4. StrokeBorder: border of an arbitrary stroke.
  5. BevelBorder: ii-line bevel border.
  6. SoftBevelBorder: raised or lowered bevel with softened corners.
  7. EtchedBorder: etched-in or etched-out with highlight/shadow.
  8. MatteBorder: matte-similar border of either a solid color or a tiled icon.
  9. CompoundBorder: compose two Borderdue south - inner and outer.

To set up a border to a JComponent, the easier way is to choose a static method from the BorderFactory class (instead of using the constructor of the Border class). For example,

JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createLineBorder(Colour.CYAN, 15));        

The BorderFactory class provides these static methods to create borders:

public static Edge createLineBorder(Color color, [int thickness, boolean rounded])     public static Border createEmptyBorder([int top, int left, int bottom, int right])     public static TitledBorder createTitledBorder(String title)     public static TitledBorder createTitledBorder(Border border, [String title,        int titleJustification, int titlePosition, Font titleFont, Color titleColor])     public static CompoundBorder createCompoundBorder([Border outsideBorder, Border insideBorder])     More than: Refer to the API

Graphics_Borders.gif

Borders are included into the display surface area of a JComponent as illustrated.

To exclude the border, yous could use the method getInSets() to retrieve the 4 borders in an Insets object (says insets), and use insets.left, insets.right, insets.acme, and insets.bottom to retrieve the width of the 4 borders. For example,

            Insets insets = frame.getInsets(); Organisation.out.println(insets);     int realWidth = frame.getWidth() - insets.left - insets.right; int realHeight = frame.getHeight() - insets.elevation - insets.lesser; Arrangement.out.println("real width = " + realWidth);     Organisation.out.println("existent height = " + realHeight);        
Case

Swing_TestDisplayAreaAndBorder.png

This example illustrates the brandish area, border and the diverse dimension.

1 2 3 4 5 6 seven 8 9 10 xi 12 13 14 15 16 17 18 xix 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
import java.awt.*; import javax.swing.*;    public class TestDisplayAreaAndBorder extends JFrame {        public TestDisplayAreaAndBorder() {       Container cp = getContentPane();       cp.setLayout(new FlowLayout());         JTextArea comp = new JTextArea(10, 25);         comp.setBackground(new Color(200, 200, 200));       comp.setForeground(Color.BLUE);       comp.setBorder(BorderFactory.createLineBorder(Color.CYAN, 15));                    comp.setPreferredSize(new Dimension(350, 200));       cp.add(comp);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Advent and Border");       setSize(400, 300);       setVisible(truthful);         StringBuffer msg = new StringBuffer();       msg.suspend("Width = " + comp.getWidth());       msg.append("\nHeight = " + comp.getHeight());       msg.suspend("\nOrigin-X = " + comp.getX());       msg.append("\nOrigin-Y = " + comp.getY());       msg.append("\nOrigin-Ten (on screen) = " + comp.getLocationOnScreen().x);       msg.append("\nOrigin-Y (on screen) = " + comp.getLocationOnScreen().y);         Insets insets = comp.getInsets();       msg.append("\nInsets (top, right, bottom, left)  = "          + insets.top + "," + insets.right + "," + insets.bottom + "," + insets.left);       msg.suspend("\nReal Width  = " + (comp.getWidth() - insets.left - insets.correct));       msg.suspend("\nReal Height  = " + (comp.getHeight() - insets.top - insets.bottom));         comp.setText(msg.toString());    }          public static void master(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new TestDisplayAreaAndBorder();           }       });    } }

Positioning Your Application Window

You tin can position your main application window (JFrame), or top-level container, on the screen, via:

             public void setSize(int width, int height) public void setLocation(int x, int y) public void setBounds(int 10, int y, int width, int top) public void setSize(Dimension dim) public void setLocation(Point origin) public void setBounds(Rectangle r)       public int getWidth() public int getHeight() public int getX() public int getY() public Dimension getSize() public Indicate getLocation() public Rectangle getBounds()        

Yous can get the screen size via static method Toolkit.getDefaultToolkit().getScreenSize(). For example,

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();   int screenWidth = dim.width; int screenHeight = dim.heigth;

You can also run your application in full-screen style (with or without decorations such as championship bar), instead of window-mode. Read "Swing How-To".

A quick style to heart your awarding on the screen is to use setLocationRelativeTo(null):

setSize(WINDOW_WIDTH, WINDOW_HEIGHT);  setLocationRelativeTo(nix);                                  setVisible(truthful);        

Text Components: JTextField, JTextArea, JEditorPane

Swing_JTextComponentClassDiagram.png

Swing provides half-dozen text components, every bit shown in the higher up class diagram. All text components extends from JTextComponent.

  1. JTextField, JPasswordField, JFormattedTextField: For displaying only one line of editable text. Like buttons, they trigger ActionEvent when user hits the "enter" key.
  2. JTextArea: Plain text area for displaying multiple lines of editable text, unformatted. All the texts are in the aforementioned font.
  3. JEditorPane, JTextPane: A styled text area which can use more than one font. They back up embedded images and embedded components. JEditorPane can load HMTL-formatted text from a URL.
Example: JTextField, JPasswordField, JFormattedTextField, and JTextArea

Swing_JTextComponentDemo.png

This example illustrates unmarried-line JTextField, JPasswordField, JFormattedField, and multi-line JTextArea wrapped inside an JScrollPane.

1 2 three 4 5 6 7 viii 9 ten 11 12 xiii 14 fifteen 16 17 18 19 twenty 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
import java.awt.*; import java.awt.event.*; import javax.swing.*;    @SuppressWarnings("serial") public grade JTextComponentDemo extends JFrame {          JTextField tField;    JPasswordField pwField;    JTextArea tArea;    JFormattedTextField formattedField;          public JTextComponentDemo() {              JPanel tfPanel = new JPanel(new GridLayout(3, 2, ten, 2));       tfPanel.setBorder(BorderFactory.createTitledBorder("Text Fields: "));                tfPanel.add(new JLabel("  JTextField: "));       tField = new JTextField(10);       tfPanel.add(tField);       tField.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             tArea.append("\nYou have typed " + tField.getText());          }       });                tfPanel.add(new JLabel("  JPasswordField: "));       pwField = new JPasswordField(ten);       tfPanel.add(pwField);       pwField.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             tArea.append("\nYou password is " + new Cord(pwField.getPassword()));          }       });                tfPanel.add(new JLabel("  JFormattedTextField"));       formattedField = new JFormattedTextField(java.util.Calendar             .getInstance().getTime());       tfPanel.add together(formattedField);                tArea = new JTextArea("A JTextArea is a \"patently\" editable text component, "             + "which means that although it can display text "             + "in any font, all of the text is in the same font.");       tArea.setFont(new Font("Serif", Font.ITALIC, 13));       tArea.setLineWrap(true);              tArea.setWrapStyleWord(true);         tArea.setBackground(new Color(204, 238, 241));               JScrollPane tAreaScrollPane = new JScrollPane(tArea);       tAreaScrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));       tAreaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);                Container cp = this.getContentPane();       cp.setLayout(new BorderLayout(5, 5));       cp.add(tfPanel, BorderLayout.Due north);       cp.add(tAreaScrollPane, BorderLayout.Middle);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("JTextComponent Demo");       setSize(350, 350);       setVisible(truthful);    }          public static void main(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new JTextComponentDemo();            }       });    } }
JPasswordField

Employ getPassword() to get the password entered in a char[]. [TODO: Security Issues]

JFormattedTextField (Advanced)

[TODO]

JTextArea wrapped in a JScrollPane

Information technology is common to wrap a JTextArea inside a JScrollPane, so as to scroll the text area (horizontally or vertically). To practise so, allocate a JScrollPane with the JTextArea equally the argument.

JTextArea tArea = new JTextArea(...);   JScrollPane tAreaScrollPane = new JScrollPane(tArea);   tAreaScrollPane.setVerticalScrollBarPolicy(...);        tAreaScrollPane.setHorizontalScrollBarPolicy(...);        
JTextArea'southward Properties

You can supervene upon the document, or append or insert more text.

public void append(Cord          str)     public void replaceRange(String          str, int          startPos, int          endPos)       public void insert(String str, int          pos)            
JEditorPane as HTML Browser

Y'all can use JEditorPane to display an HTML document (merely no CSS and JavaScript). Again, information technology is common to wrap a JEditorPane inside a JScrollPane. For example,

JEditorPane editorPane = new JEditorPane();   editorPane.setEditable(faux); endeavour {        URL url = new URL("http://www3.ntu.edu.sg/home/ehchua/programming/index.html");    editorPane.setPage(url); } catch (MalformedURLException e) {    e.printStackTrace(); } catch (IOException e) {    e.printStackTrace(); }  JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setContentPane(editorScrollPane);
JTextPane (Avant-garde)

JTextPane is used for formatted styled text display; whereas JTextArea is used for obviously text display. Although you can set the font and style for JTextArea, all the text is display in the same font. In JTextPane, yous can gear up different fonts and styles for different sections of text.

You can apply JTextPane for to develop an editor (such as NotePad or NotePad++) with different sections of text displayed in unlike fonts and colors.

Case: See Swing Tutorial'southward "Text Component Features". This is an excellent example that illustrates many features and concepts.

Text Component API: It provides many features, from cut and paste to changing the selected text. Meet Swing Tutorial's "Text Component API".

Buttons and ComboBox: JButton, JCheckBox, JRadioButton, JComboBox

Swing_AbstractButtonClassDiagram.png

Read: Swing Tutorial's "How to Use Buttons, Check Boxes, and Radio Buttons".

A user can click a push button (or a carte item) to trigger a specific action. Swing supports mouse-less operations, where user could use a keyboard short-cut (chosen mnemonic) to activate the action.

Buttons and carte du jour-items are inherited from AbstractButton, every bit shown in the class diagram.

Yous could place a text string (called push button'south characterization) too as an icon on the push. You could use unlike icons for dissimilar button states: defaultIcon, disabledIcon, pressedIcon, selectedIcon, rolloverIcon, disabledSelectedIcon, rolloverSelectedIcon. The defaultIcon tin can be set via the constructor or setIcon() method. The other icons tin be set via setXxxIcon() methods. You can set the alignment of text and button via setHorizontalAlignment() and setVerticalAlignment() methods. You tin can fix the position of the text relative to the icon via setHorizontalTextPosition() and setVerticalTextPosition().

Swing supports many type of buttons.

Command Buttons: JButton

Click to fires an ActionEvent to all its registered ActionListenersouth.

Toggle Buttons: JRadioButton, JCheckBox, JToggleButton

Toggle buttons are two-state buttons: SELECTED or DESELECTED.

For radio button, yous can choose none or one amongst the grouping. JRadioButtondue south are typically added into a ButtonGroup to ensure exclusive selection. JRadioButton fires ItemEvent to its ItemListenersouth. It also fires ActionEvent to its ActionListeners. Both ItemEvent and ActionEvent tin can be used.

For checkboxes, you tin choose none or more among the grouping. JCheckBoxes fire ItemEvent besides as ActionEvent. Nosotros typically use ItemEvent as nosotros may need to distinguish between item-states of SELECTED and DESELECTED.

The ItemListner (of ItemEvent) declares one abstract method itemStateChanged(ItemEvent east).

JComboBox

JComboBox can be used to provide a drop-downward bill of fare. It supports unmarried-selection and multiple-selection. JComboBox receives a Object array (typically a Cord array), which provides the items in the drop-down listing. JComboBox fires ItemEvent. We could apply JComboBox's getSelectedIndex() to become the index of the selected item; or getSelectedItem() to become the selected Object. JComboBox also fires ActionEvent.

Example on JButton, JRadioButton and JComboBox

Swing_CounterRadioCombo.png

In this case, nosotros shall modify our counter awarding to include two radio buttons for specifying counting up/downwards, and a combo-box to select the count-step size.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 fifteen 16 17 18 19 20 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 lxx 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 ninety 91 92 93 94 95 96
import java.awt.*; import java.awt.event.*; import javax.swing.*;    @SuppressWarnings("serial") public form SwingCounterRadioCombo extends JFrame {    individual JTextField tfCount;    individual int count = 0;      private boolean countingUp = true;     private int footstep = 1;             public SwingCounterRadioCombo () {       Container cp = getContentPane();       cp.setLayout(new FlowLayout());                cp.add together(new JLabel("Counter:"));       tfCount = new JTextField("0", 5);       tfCount.setEditable(false);       tfCount.setHorizontalAlignment(JTextField.Correct);       cp.add(tfCount);                JRadioButton rbUp = new JRadioButton("Upwardly", true);       rbUp.setMnemonic(KeyEvent.VK_U);       cp.add together(rbUp);       rbUp.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             countingUp = true;          }       });       JRadioButton rbDown = new JRadioButton("Down", true);       rbDown.setMnemonic(KeyEvent.VK_D);       cp.add(rbDown);       rbDown.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             countingUp = fake;          }       });              ButtonGroup btnGp = new ButtonGroup();       btnGp.add together(rbUp);       btnGp.add(rbDown);                add(new JLabel("Stride:"));       concluding Integer[] steps = {i, 2, 3, 4, 5};         final JComboBox<Integer> comboCount = new JComboBox<Integer>(steps);       comboCount.setPreferredSize(new Dimension(threescore, 20));       cp.add together(comboCount);       comboCount.addItemListener(new ItemListener() {          @Override          public void itemStateChanged(ItemEvent e) {             if (due east.getStateChange() == ItemEvent.SELECTED) {                step = (Integer)comboCount.getSelectedItem();             }          }       });                JButton btnCount = new JButton("Count");       btnCount.setMnemonic(KeyEvent.VK_C);       cp.add together(btnCount);       btnCount.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             if (countingUp) {                count += step;             } else {                count -= step;             }             tfCount.setText(count + "");          }       });         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Swing Counter with RadioButton & ComboBox");       setSize(480, 100);       setVisible(true);    }          public static void main(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new SwingCounterRadioCombo();           }       });    } }
Example on JRadioButton, JCheckBox and JComboBox

Swing_ButtonComboBoxDemo.png

In this example, we have two groups of radio buttons: one group to set the horizontal alignment of the JLabel, and processed via ItemEvent; another group sets the vertical alignment and processed via ActionEvent.

ane 2 3 4 five 6 7 8 9 ten eleven 12 thirteen fourteen 15 xvi 17 eighteen 19 xx 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 l 51 52 53 54 55 56 57 58 59 sixty 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 lxxx 81 82 83 84 85 86 87 88 89 ninety 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
import java.awt.*; import java.awt.consequence.*; import java.internet.URL; import javax.swing.*;    @SuppressWarnings("serial") public class ButtonComboBoxDemo extends JFrame {        private JLabel lblForTest;    private Cord imgCrossFilename = "images/cross.gif";    private String lblText = "Cantankerous";    private Icon iconCross;      individual JRadioButton rbLeft, rbCenter, rbRight, rbTop, rbMiddle, rbBottom;    private JCheckBox cbText, cbIcon;    private JComboBox<String> comboColor;          public ButtonComboBoxDemo() {              URL imgURL = getClass().getClassLoader().getResource(imgCrossFilename);       if (imgURL != null) {          iconCross = new ImageIcon(imgURL);       } else {          System.err.println("Couldn't observe file: " + imgCrossFilename);       }       lblForTest = new JLabel(lblText, iconCross, SwingConstants.CENTER);       lblForTest.setOpaque(true);       lblForTest.setBackground(new Colour(204, 238, 241));       lblForTest.setForeground(Color.RED);       lblForTest.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 18));                rbLeft = new JRadioButton("Left");       rbLeft.setMnemonic(KeyEvent.VK_L);       rbCenter = new JRadioButton("Center", true);         rbCenter.setMnemonic(KeyEvent.VK_C);       rbRight = new JRadioButton("Correct");       rbRight.setMnemonic(KeyEvent.VK_R);              ButtonGroup btnGroupH = new ButtonGroup();       btnGroupH.add(rbLeft);       btnGroupH.add together(rbRight);       btnGroupH.add(rbCenter);              JPanel pnlRbtnH = new JPanel(new GridLayout(1, 0));        pnlRbtnH.add(rbLeft);       pnlRbtnH.add together(rbCenter);       pnlRbtnH.add together(rbRight);       pnlRbtnH.setBorder(BorderFactory.createTitledBorder("Horizontal Alignment"));                ItemListener listener = new ItemListener() {          @Override          public void itemStateChanged(ItemEvent e) {             if (e.getStateChange() == ItemEvent.SELECTED) {                if (eastward.getSource() == rbLeft) {                   lblForTest.setHorizontalAlignment(SwingConstants.LEFT);                } else if (east.getSource() == rbCenter) {                   lblForTest.setHorizontalAlignment(SwingConstants.CENTER);                } else if (e.getSource() == rbRight) {                   lblForTest.setHorizontalAlignment(SwingConstants.RIGHT);                }             }          }       };       rbLeft.addItemListener(listener);       rbCenter.addItemListener(listener);       rbRight.addItemListener(listener);                rbTop = new JRadioButton("Superlative");       rbTop.setMnemonic(KeyEvent.VK_T);       rbMiddle = new JRadioButton("Middle", true);         rbMiddle.setMnemonic(KeyEvent.VK_M);       rbBottom = new JRadioButton("Bottom");       rbBottom.setMnemonic(KeyEvent.VK_B);              ButtonGroup btnGroupV = new ButtonGroup();       btnGroupV.add(rbTop);       btnGroupV.add(rbMiddle);       btnGroupV.add(rbBottom);              JPanel pnlRbtnV = new JPanel(new GridLayout(1, 0));        pnlRbtnV.add(rbTop);       pnlRbtnV.add(rbMiddle);       pnlRbtnV.add together(rbBottom);       pnlRbtnV.setBorder(BorderFactory.createTitledBorder("Vertical Alignment"));                rbTop.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent east) {             lblForTest.setVerticalAlignment(SwingConstants.TOP);          }       });       rbMiddle.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             lblForTest.setVerticalAlignment(SwingConstants.Heart);          }       });       rbBottom.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent due east) {             lblForTest.setVerticalAlignment(SwingConstants.BOTTOM);          }       });                cbText = new JCheckBox("Text", true);         cbText.setMnemonic(KeyEvent.VK_T);       cbIcon = new JCheckBox("Icon", true);         cbIcon.setMnemonic(KeyEvent.VK_I);       cbIcon.setSelected(true);              JPanel pnlCbox = new JPanel(new GridLayout(0, 1));        pnlCbox.add(cbText);       pnlCbox.add(cbIcon);              cbText.addItemListener(new ItemListener() {          @Override          public void itemStateChanged(ItemEvent east) {                          if (e.getStateChange() == ItemEvent.SELECTED) {                lblForTest.setText(lblText);             } else {                lblForTest.setText("");             }          }       });       cbIcon.addItemListener(new ItemListener() {          @Override          public void itemStateChanged(ItemEvent e) {                          if (e.getStateChange() == ItemEvent.SELECTED) {                lblForTest.setIcon(iconCross);             } else {                lblForTest.setIcon(null);             }          }       });                String[] strColors = {"Ruby", "Bluish", "Green",                             "Cyan", "Magenta", "Xanthous", "Black"};       final Color[] colors = {Color.Carmine, Color.Bluish, Color.Light-green,                         Colour.CYAN, Color.MAGENTA, Color.Xanthous, Color.BLACK};       comboColor = new JComboBox<String>(strColors);       comboColor.addItemListener(new ItemListener() {          @Override          public void itemStateChanged(ItemEvent due east) {             if (e.getStateChange() == ItemEvent.SELECTED) {                lblForTest.setForeground(colors[comboColor.getSelectedIndex()]);             }          }       });              JPanel pnlCombo = new JPanel(new FlowLayout());       pnlCombo.add together(comboColor);                Container cp = this.getContentPane();       cp.setLayout(new BorderLayout());       cp.add(lblForTest, BorderLayout.Middle);       cp.add(pnlRbtnH, BorderLayout.NORTH);       cp.add(pnlRbtnV, BorderLayout.South);       cp.add together(pnlCbox, BorderLayout.WEST);       cp.add(pnlCombo, BorderLayout.E);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Button and ComboBox Demo");       setSize(400, 300);         setLocationRelativeTo(null);       setVisible(true);    }          public static void main(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          public void run() {             new ButtonComboBoxDemo();            }       });    } }

Menu-Bar: JMenuBar, JMenu, JMenuItem

Swing_JMenuBarClassDiagram.png

The menu-bar is at the same level every bit the content-pane (of the elevation-level container JFrame). It is fix via the JFrame's setJMenuBar() method (similar to setContentPane()).

To create a bill of fare-bar, construct a JMenuBar. A card-bar (JMenuBar) contains menu (JMenu). A menu contains card-item (JMenuItem). JMenuItem is a subclass of AbstractButton, similar to JButton. JMenuItem fires ActionEvent upon activation to all its registered ActionListener.

Instance

Swing_TestJMenuBar.png

This menu-bar contains ii menus (Menu-A and Menu-B). Card-A contains 2 menu-items (Upwardly and Down). Carte-B has 1 menu-particular (Reset).

one 2 3 4 v 6 7 viii ix 10 11 12 13 14 15 16 17 18 19 xx 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
import java.awt.*; import coffee.awt.upshot.*; import javax.swing.*;    public form TestJMenuBar extends JFrame {      JTextField display;    int count = 0;          public TestJMenuBar() {              JMenuBar menuBar;          JMenu bill of fare;                JMenuItem menuItem;          menuBar = new JMenuBar();                menu = new JMenu("Menu-A");       card.setMnemonic(KeyEvent.VK_A);         menuBar.add(menu);           menuItem = new JMenuItem("Upwards", KeyEvent.VK_U);       menu.add(menuItem);        menuItem.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             ++count;             display.setText(count + "");          }       });         menuItem = new JMenuItem("Down", KeyEvent.VK_D);       menu.add together(menuItem);        menuItem.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent east) {             --count;             display.setText(count + "");          }       });                menu = new JMenu("Menu-B");       menu.setMnemonic(KeyEvent.VK_B);         menuBar.add together(menu);           menuItem = new JMenuItem("Reset", KeyEvent.VK_R);       menu.add(menuItem);        menuItem.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             count = 0;             display.setText(count + "");          }       });         setJMenuBar(menuBar);           Container cp = getContentPane();       cp.setLayout(new FlowLayout());       display = new JTextField("0", 10);       cp.add together(display);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Test MenuBar");       setSize(300, 100);       setVisible(true);    }          public static void main(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new TestJMenuBar();           }       });    } }

JOptionPane: Interacting with the User

The javax.swing.JOptionPane provides standard pre-built diglog boxes to interact with user for both input and output. To create a dialog box, use 1 of the static methods JOptionPane.showXxxDialog().

            public static String          showInputDialog(Object          message, [Object          initialSelectionValue]) public static Object          showInputDialog(Component          parentComponent, Object          message,       [String          title], [int          messageType], [Icon          icon], [Object[]          options], [Object          initialValue])      public static int          showConfirmDialog(Component          parentComponent, Object          message,       [String          title], [int          optionType], [int          messageType], [Icon          icon])      public static void          showMessageDialog(Component          parentComponent, Object          message,       [String          title], [int          messageType], [Icon          icon])      public static int          showOptionDialog(Component          parentComponent, Object          bulletin,       String          championship, int          optionType, int          messageType, Icon          icon, Object[]          options, Object          initialValue)        

All these methods block the caller until the user's interaction is complete. Each of these methods also comes has a showInternalXxxDialog() version, which uses an internal frame to hold the dialog box.

Example: Input, Ostend and Message Dialogs
1 2 3 four v 6 vii eight nine ten 11 12 13 fourteen fifteen 16 17 18 19 20 21 22
import javax.swing.*; public class JOptionPaneTest {    public static void main(String[] args) {                     String inStr = JOptionPane.showInputDialog(null, "Ask for user input (returns a String)",             "Input Dialog", JOptionPane.PLAIN_MESSAGE);       System.out.println("You have entered " + inStr);       JOptionPane.showMessageDialog(null, "Brandish a message (returns void)!",             "Bulletin Dialog", JOptionPane.PLAIN_MESSAGE);       int answer = JOptionPane.showConfirmDialog(null, "Ask for confirmation (returns an int)",             "Confirm Dialog", JOptionPane.YES_NO_CANCEL_OPTION);       switch (answer) {          case JOptionPane.YES_OPTION:             System.out.println("You clicked YES"); intermission;          case JOptionPane.NO_OPTION:             Arrangement.out.println("You clicked NO"); break;          example JOptionPane.CANCEL_OPTION:             System.out.println("You clicked Cancel"); break;       }    } }

Swing_JOptionPaneInputDialog.png Swing_JOptionPaneConfirmDialog.png Swing_JOptionPaneMessageDialog.png

Take annotation that input dialog returns the String entered by the user; confirm dialog returns an int (JOptionPane.YES_OPTION, NO_OPTION, CANCEL_OPTION); message dialog returns void. Furthermore, you tin use JOptionPane directly nether primary() to prompt user for input, similar to text-based input via Scanner.

Instance: Prompting User for Input with Validation

Swing_TestInputDialog.png

ane 2 3 iv 5 6 7 8 9 10 xi 12 xiii fourteen xv 16 17 eighteen 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
import java.awt.*; import java.awt.event.*; import javax.swing.*;   public class InputDialogWithValidation extends JFrame {    JTextField tfDisplay;            public InputDialogWithValidation() {       Container cp = getContentPane();       cp.setLayout(new FlowLayout());         tfDisplay = new JTextField(x);       tfDisplay.setEditable(false);       cp.add(tfDisplay);         JButton btn = new JButton("Input");       cp.add(btn);       btn.addActionListener(new ActionListener() {          @Override          public void actionPerformed(ActionEvent e) {             boolean validInput = false;               int numberIn;             String inputStr = JOptionPane.showInputDialog("Enter a number [1-9]: ");             do {                try {                   numberIn = Integer.parseInt(inputStr);                } catch (NumberFormatException ex) {                   numberIn = -ane;                  }                if (numberIn < 1 || numberIn > ix) {                   inputStr = JOptionPane.showInputDialog("Invalid numner! Enter a number [1-9]: ");                } else {                   JOptionPane.showMessageDialog(zilch, "You take entered " + numberIn);                   validInput = true;                }             } while (!validInput);              tfDisplay.setText(numberIn + "");          }       });       setDefaultCloseOperation(EXIT_ON_CLOSE);       setSize(300, 100);       setTitle("Examination Input Dialog");       setVisible(true);    }          public static void main(Cord[] args) {              javax.swing.SwingUtilities.invokeLater(new Runnable() {          public void run() {             new InputDialogWithValidation();           }       });    } }

Pluggable Look and Feel

Swing supports the so-called "pluggable await and feel (plaf)" for its JComponents. The "look" refers to the appearance of the widgets (JComponent); while the "feel" refers to how the widgets carry (due east.thousand., the behaviors of mouse-click for the diverse mouse-buttons). "Pluggable" refers the power of irresolute the look and feel at runtime.

Y'all can choose to utilize the default Coffee look and feel, the native system's await and feel (Windows, Linux, Mac), or the newer cross-platform Nimbus expect and feel.

Pluggable await and feel is supported in Swing's components by separating the components into two classes: JComponent (in package javax.swing) and ComponetUI (in package javax.swing.plaf). The ComponetUI, chosen UI delegate, handles all aspects relating to look and experience. Nevertheless, you shall not collaborate with the UI delegate direct.

These look and feel are supported (in packages javax.swing.plaf and javax.swing.plaf.*):

  1. Coffee Wait and Feel: Also called CrossPlatformLookAndFeel, or Metallic 50&F. The default L&F which provides the aforementioned look and feel beyond all the platforms.
  2. Arrangement Look and Feel: the L&F of the native arrangement (eastward.chiliad., Windows, Linux, Mac).
  3. Nimbus Look and Feel: the newer cross-platform look and feel released in JDK 1.6 update ten.

Swing_LaFJava.png Swing_LaFNativeSystem.png
Swing_LaFNimbus.png Swing_LaFMotif.png

The JFC demos (included in JDK demo) "SwingSet2" and "SwingSet3" show the various L&Fs.

Setting the Look and Feel

You need to set up the Look and Feel every bit the first step in your GUI construction. There are a few means to gear up the Expect and Experience.

Via UIManager.setLookAndFeel()

You tin can utilize the static method UIManager.setLookAndFeel(Cord className) to set the look and experience.

  • You can either use the static method UIManager.getCrossPlatformLookAndFeelClassName(), UIManager.getSystemLookAndFeelClassName() to go the classname string for Java F&F and Native Arrangement L&F; or
  • Use the actual classname cord such as "javax.swing.plaf.metallic.MetalLookAndFeel" (for Coffee L&F), "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" (Windows L&F), "javax.swing.plaf.nimbus.NimbusLookAndFeel" (Nimbus L&F) and "com.sun.java.swing.plaf.motif.MotifLookAndFeel" (Motif L&F).

For example,

            try {        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException eastward) {    due east.printStackTrace(); } catch (ClassNotFoundException e) {    e.printStackTrace(); } take hold of (InstantiationException e) {    east.printStackTrace(); } catch (IllegalAccessException due east) {    e.printStackTrace(); }

The culling Wait and Feel (under Windows System) are:

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");            UIManager.setLookAndFeel("com.sunday.java.swing.plaf.windows.WindowsClassicLookAndFeel");            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

You can use static method UIManager.getInstalledLookAndFeels() to listing all the installed Fifty&F:

UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo laf : lafs) {    System.out.println(laf); }
javax.swing.UIManager$LookAndFeelInfo[Metallic javax.swing.plaf.metallic.MetalLookAndFeel] javax.swing.UIManager$LookAndFeelInfo[Nimbus javax.swing.plaf.nimbus.NimbusLookAndFeel] javax.swing.UIManager$LookAndFeelInfo[CDE/Motif com.sun.coffee.swing.plaf.motif.MotifLookAndFeel] javax.swing.UIManager$LookAndFeelInfo[Windows com.sun.java.swing.plaf.windows.WindowsLookAndFeel] javax.swing.UIManager$LookAndFeelInfo[Windows Classic com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel]
Via the Command Line Option "swing.defaultlaf"

For example,

            java -Dswing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel MySwingApp  java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel MySwingApp
Via the "swing.properties" file

Create a "swing.backdrop" file (placed under "$JAVA_HOME/lib " directory) with a pick "swing.defaultlaf":

            swing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel

Nimbus Await and Experience (JDK 1.6u10)

Reference: Swing Tutorial'due south "Nimbus Look and Feel" @ http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html.

Nimbus is a polished cantankerous-platform await and experience introduced in the JDK one.half-dozen Update 10. The JFC demo "SwingSet3" (under the JDK demo) shows the Nimbus look and experience for the diverse Swing JComponents. "Nimbus uses Java 2D vector graphics to draw the user interface (UI), rather than static bitmaps, so the UI tin can be crisply rendered at any resolution. Nimbus is highly customizable. Yous can use the Nimbus await and feel as is, or you can skin (customize) the look with your own make."

To enable Nimbus L&F:

  1. Use UIManager.setLookAndFeel():
    attempt {        UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");  } catch (Exception e) {    e.printStackTrace(); }    try {        for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {       if ("Nimbus".equals(lafInfo.getName())) {          UIManager.setLookAndFeel(lafInfo.getClassName());          pause;       }    } } catch (Exception e) {    try {           UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());    } catch (Exception e1) {       e1.printStackTrace();    } }
    Take note that the Nmibus package in JDK ane.6u10 is "com.sunday.java.swing.plaf.nimbus.NimbusLookAndFeel"; while in JDK one.vii, information technology is chosen "javax.swing.plaf.nimbus.NimbusLookAndFeel".
  2. Employ command-line option "swing.defaultlaf":
    java -Dswing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel MySwingApp
  3. Use a "swing.properties" file (under the "$JAVA_HOME/lib"):
                    swing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel

A Nimbus component can take 4 dissimilar sizes: large, regular, pocket-size and mini. You can choose the size via:

myButton.putClientProperty("JComponent.sizeVariant", "mini");        

Y'all can change the colour theme via:

UIManager.put("nimbusBase", new Color(...));       UIManager.put("nimbusBlueGrey", new Colour(...));   UIManager.put("control", new Color(...));             for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels() {     if ("Nimbus".equals(info.getName())) {         UIManager.setLookAndFeel(info.getClassName());         intermission;     } } ......

You can customize the look and feel, which is across the scope of this article.

More than on Layout Manager

Reference: Swing Tutorial's "Laying Out Components Within a Container" @ http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html.

Key Points on Layout Managing director

Layout in Production

Use NetBeans' visual GroupLayout to layout the components in production; or GridBagLayout if you prefer to code yourself (why?). The rest of LayoutManagers (such as FlowLayout, BorderLayout, GridLayout) are meant for prototyping.

The two components yous need to worry most layout are JPanel and the content-pane of the tiptop-level containers (such as JFrame, JApplet and JDialog).

  • JPanel defaults to FlowLayout (with alignment of Heart, hgap and vgap of five pixels); or you tin set the layout of a JPanel in its constructor.
  • All content-panes default to BorderLayout (with hgap and vgap of 0). In BorderLayout, the add(aComponent) without specifying the zone adds the component to the Center. Second add() will override the first add together().

Absolute Positioning without LayoutManager shall be avoided, as it does non adjust well on screens with different resolutions; or when the window is resize.

Hints on sizes and alignments

Yous can provide hints on the minimum, preferred and maximum sizes of a component via setMinimumSize(), setPreferredSize() and setMaximumSize() methods. However, some layout managers ignore these requests, particularly the maximum size. You can as well practice these by extending a subclass and overriding the getXxxSize() call-back methods.

The setSize() method must exist issued at the correct bespeak, or else it will not work (equally it was overridden by another implicit setSize()). [TODO: Cheque]

Similarly, you can provide hints on horizontal and vertical alignments (of the edges) among components via setAlignmentX() and setAlignmentY() methods. BoxLayout honors them merely other layout managers may ignore these hints. You can likewise extend a subclass and override the getAlignmentX() and getAlignmentY() telephone call-back methods.

[TODO] setSize(), pack(), validate() and invalidate() for Container, revalidate() and repaint() for Component, doLayout().

Methods validate() and doLayout()

If you change a property of a LayoutManager, such equally hgap or vgap of GridLayout, yous need to event a doLayout() to force the LayoutManager to re-layout the components using the new property.

A container has merely i LayoutManager. Even so, you lot can change the LayoutManager via setLayout(newLayoutManager). You need to follow with a validate() to ask the container to re-layout the components.

Code Example

This example creates half dozen buttons, which are arranged in 3x2 and 2x3 GridLayout alternately upon clicking whatever button.

1 2 3 4 5 half dozen vii 8 nine ten 11 12 thirteen 14 15 xvi 17 18 19 xx 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 fifty 51 52 53 54 55 56 57 58 59 60
import java.awt.*; import java.awt.effect.*; import javax.swing.*;    @SuppressWarnings("serial") public class SetLayoutTest extends JFrame {    individual int rows = three;    private int cols = 2;    private Container cp;            public SetLayoutTest() {       cp = this.getContentPane();       cp.setLayout(new GridLayout(rows, cols, iii, iii));                ButtonsListener listener = new ButtonsListener();                JButton[] buttons = new JButton[rows * cols];       for (int i = 0; i < buttons.length; ++i) {          buttons[i] = new JButton("Click [" + (i+ane) + "]");          cp.add(buttons[i]);          buttons[i].addActionListener(listener);       }         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("setLayout() Test");       setSize(280, 150);       setLocationRelativeTo(null);         setVisible(true);    }          individual grade ButtonsListener implements ActionListener {       @Override       public void actionPerformed(ActionEvent due east) {                    int temp = rows;          rows = cols;          cols = temp;                      cp.setLayout(new GridLayout(rows, cols, five, 5));          cp.validate();         }    }          public static void main(String[] args) {              SwingUtilities.invokeLater(new Runnable() {          public void run() {             new SetLayoutTest();            }       });    } }

Alternatively, you tin can also modify the rows and columns of GridLayout via setRows() and setColumns() methods, and doLayout(). For example,

@Override public void actionPerformed(ActionEvent eastward) {        int temp = rows;    rows = cols;    cols = temp;      GridLayout layout = (GridLayout)cp.getLayout();    layout.setRows(rows);    layout.setColumns(cols);    cp.doLayout(); }

add(), remove(), removeAll() Components from a Container

You tin can use aContainer.add together(aComponent) to add together a component into a container. You can as well use aContainer.remove(aComponent) or aContainer.removeAll() to remove a component or all the components. You demand to outcome a validate() call to the container after adding or removing components.

Code Case

This case starts with 2 buttons: ane to "add together" a button and ane to "remove" a button. The buttons are arranged in FlowLayout on the content-pane. For demonstration purpose, I remove all the buttons and re-add all the buttons.

ane ii 3 iv five half dozen 7 viii 9 x 11 12 13 fourteen 15 16 17 xviii 19 20 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 fifty 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
import java.awt.*; import java.awt.issue.*; import javax.swing.*;    @SuppressWarnings("serial") public grade AddRemoveComponentsTest extends JFrame {    private int numButtons = 2;     Container cp;                   JButton[] buttons;              ButtonsListener listener;             public AddRemoveComponentsTest() {       cp = getContentPane();                listener = new ButtonsListener();              createButtons();         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Add/Remove Components Test");       setSize(400, 150);       setLocationRelativeTo(naught);       setVisible(true);    }          private void createButtons() {                     cp.removeAll();       cp.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));                buttons = new JButton[numButtons];         int i = 0;              practise {          buttons[i] = new JButton("Add");          cp.add together(buttons[i]);          buttons[i].addActionListener(listener);          ++i;       } while (i < numButtons - 1);              if (i == numButtons - 1) {          buttons[i] = new JButton("Remove");          cp.add together(buttons[i]);          buttons[i].addActionListener(listener);       }       cp.validate();        repaint();         }          individual course ButtonsListener implements ActionListener {       @Override       public void actionPerformed(ActionEvent due east) {                    if (e.getActionCommand().equals("Add")) {             ++numButtons;          } else {             if (numButtons >= 2) {                --numButtons;             }          }                    createButtons();       }    }          public static void main(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          public void run() {             new AddRemoveComponentsTest();            }       });    } }

Component Orientation

Most languages from written form left-to-right, only some otherwise. You can gear up the orientation on Component via:

            public void          setComponentOrientation(ComponentOrientation o)            

Since JDK 1.four, layout managers, such equally FlowLayout and BorderLayout, can layout components according to component-orientation of the container. Some new terms were introduced. For instance, in BorderLayout, instead of using Eastward, WEST, NORHT, SOUTH (which are absolute), the term LINE_START, LINE_END, PAGE_START, PAGE_END were added which tin can accommodate itself according to the component orientation. LINE_START is the same as WEST, if the component orientation is LEFT_TO_RIGHT. On the other hand, it is E, if the component orientation is RIGHT_TO_LEFT. Similarly, in FlowLayout'due south alignment, LEADING and TRAILING were added in place of LEFT and RIGHT.

Code Instance
i two 3 4 5 6 seven eight 9 10 eleven 12 13 14 15 xvi 17 18 19 twenty 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 sixty 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 lxxx
import java.awt.*; import java.awt.event.*; import javax.swing.*;    @SuppressWarnings("serial") public class BorderLayoutTest extends JFrame {    public static terminal String TITLE = "BorderLayout Demo";          private Container cp;      private JButton btnNorth, btnSouth, btnCenter, btnEast, btnWest;    private boolean leftToRight = true;          public BorderLayoutTest() {       cp = this.getContentPane();       btnNorth = new JButton("PAGE_START [Hibernate]");       btnSouth = new JButton("PAGE_END [Hibernate]");       btnWest = new JButton("LINE_START [Hibernate]");       btnEast = new JButton("LINE_END [Hibernate]");       btnCenter = new JButton("Eye [Bear witness ALL, Alter ORIENTATION]");       btnCenter.setPreferredSize(new Dimension(300, 100));          ActionListener listener = new ButtonListener();       btnNorth.addActionListener(listener);       btnSouth.addActionListener(listener);       btnEast.addActionListener(listener);       btnWest.addActionListener(listener);       btnCenter.addActionListener(listener);                addButtons();         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setTitle(TITLE);        pack();         setLocationRelativeTo(null);         setVisible(true);                 }          private void addButtons() {       cp.removeAll();       cp.setComponentOrientation(leftToRight ?             ComponentOrientation.LEFT_TO_RIGHT : ComponentOrientation.RIGHT_TO_LEFT);       cp.add together(btnNorth, BorderLayout.PAGE_START);       cp.add together(btnSouth, BorderLayout.PAGE_END);       cp.add(btnWest, BorderLayout.LINE_START);       cp.add(btnEast, BorderLayout.LINE_END);       cp.add(btnCenter, BorderLayout.Heart);       cp.validate();    }          individual class ButtonListener implements ActionListener {       @Override       public void actionPerformed(ActionEvent evt) {          JButton source = (JButton)evt.getSource();          if (source == btnCenter) {             leftToRight = !leftToRight;               addButtons();          } else {             cp.remove(source);             cp.validate();          }       }    }          public static void main(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new BorderLayoutTest();            }       });    } }

Absolute Positioning Without a Layout Manager

Graphics_AbsolutePositioning.png

You could use accented position instead of a layout manager (such every bit FlowLayout or BorderLayout) past invoking method setLayout(aught). You tin then position you lot components using the method setBounds(int xTopLeft, int yTopLeft, int width, int tiptop). For example:

1 2 3 4 5 6 7 viii ix 10 11 12 13 xiv xv 16 17 18 xix xx 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37
import java.awt.*; import javax.swing.*;    public class CGAbsolutePositioning extends JFrame {        public CGAbsolutePositioning() {       Container cp = getContentPane();       cp.setLayout(zero);          JPanel p1 = new JPanel();       p1.setBounds(30, 30, 100, 100);       p1.setBackground(Color.RED);       cp.add together(p1);         JPanel p2 = new JPanel();       p2.setBounds(150, fifty, 120, 80);       p2.setBackground(Colour.BLUE);       cp.add(p2);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Absolute Positioning Demo");       setSize(400, 200);       setVisible(true);    }          public static void main(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new CGAbsolutePositioning();           }       });    } }

More on Event-Handling

Both AWT and Swing applications uses the AWT effect-treatment classes (in package coffee.awt.effect). Swing added a few new effect handling classes (in package javax.swing.event), simply they are not oftentimes used.

AWT GUI Components (such every bit Button, TextField, and Window) can trigger an AWTEvent upon user's activation.

User Activeness Event Triggered Event Listener interface
Click a Push button, JButton ActionEvent ActionListener
Open, iconify, close Frame, JFrame WindowEvent WindowListener
Click a Component, JComponent MouseEvent MouseListener
Change texts in a TextField, JTextField TextEvent TextListener
Type a primal KeyEvent KeyListener
Click/Select an item in a Option, JCheckbox, JRadioButton, JComboBox ItemEvent, ActionEvent ItemListener, ActionListener

The subclasses of AWTEvent are as follows:

AWT_EventClassDiagram.png

coffee.util.EventObject

All event objects extends java.util.EventObject, which takes the source object in this constructor, and provides a getSource() method.

            public EventObject(Object source)    public Object getSource()

Take note that the constructor takes an Object; and getSource() returns an instance of type Object. You may demand to downcast it back to its original type.

ActionEvent & ActionListener

An ActionEvent is fired, when an action has been performed by the user. For examples, when the user clicks a button, chooses a menu item, presses enter key in a text field. The associated ActionListener interface declares just one abstruse method, as follows:

public interface          ActionListener          extends coffee.util.EventListener {          public void actionPerformed(ActionEvent evt);           }

From the ActionEvent argument evt, you may utilize evt.getActionCommand() to get a String related to this event, for example, the button'southward label, the Cord entered into the textfield. This is specially useful if the same ActionEvent handler is used to handle multiple source objects (due east,one thousand., buttons or textfields), for identifying the source object that triggers this ActionEvent.

Swing's Action

Read Swing Tutorial's "How to Employ Actions".

A javas.swing.Action is a ActionEvent listener. If two or more than components (e.g., a menu item and a button) perform the same function in response to an ActionEvent, you tin can utilise an Action object to specify both the country and functionality of the components (whereas actionPerformed() defines only the part). For instance, you lot tin specify the states such as the text, icon, shortcut fundamental, tool-tip text, for all the source components.

You tin attach an Activity object to a component via aComponent .setAction(anAction) method:

  1. The component's state (e.m., text, icon) is updated to match the country of the Activity.
  2. The component adds the Activity object as an ActionEvent listener.
  3. If the country of the Activity changes, the component'southward state is updated to match the Action.

To create an Activeness object, you extend AbstractAction to provide the state and implement the actionPerformed() method to response to the ActionEvent.

Example

Swing_TestAction.png

In this example, a menu-particular and a button share the same Action. The Action object specifies the states (text, tooltip'south text, and a mnemonic alt short-cut primal) and override the actionPerformed(). Take annotation that the label on the buttons are updated to match the Action's names.

1 two 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
import javax.swing.*; import java.awt.*; import java.awt.event.*;  @SuppressWarnings("serial") public class TestAction extends JFrame {    private JTextField tfCount;    individual int count;          public TestAction() {              Activeness countUpAction = new CountUpAction("Count Upward",             "To count upwards", new Integer(KeyEvent.VK_U));       Activeness countDownAction = new CountDownAction("Count Down",             "To count down", new Integer(KeyEvent.VK_D));       Action resetAction = new ResetAction("Reset",             "To reset to goose egg", new Integer(KeyEvent.VK_R));         Container cp = getContentPane();       cp.setLayout(new FlowLayout());                cp.add together(new JLabel("Counter: "));       tfCount = new JTextField("0", 8);       tfCount.setHorizontalAlignment(JTextField.RIGHT);       cp.add(tfCount);       JButton btnCountUp = new JButton();       cp.add(btnCountUp);       JButton btnCountDown = new JButton();       cp.add(btnCountDown);       JButton btnReset = new JButton();       cp.add(btnReset);              btnCountUp.setAction(countUpAction);       btnCountDown.setAction(countDownAction);       btnReset.setAction(resetAction);                JMenuBar menuBar = new JMenuBar();       JMenu carte du jour;       JMenuItem menuItem;;                menu = new JMenu("Count");       menu.setMnemonic(KeyEvent.VK_C);       menuItem = new JMenuItem(countUpAction);          menu.add(menuItem);       menuItem = new JMenuItem(countDownAction);        menu.add(menuItem);       menuBar.add(menu);                menu = new JMenu("Reset");       menu.setMnemonic(KeyEvent.VK_R);       menuItem = new JMenuItem(resetAction);         menu.add(menuItem);       menuBar.add together(menu);         setJMenuBar(menuBar);        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Activeness Exam");       setSize(550, 120);       setVisible(truthful);    }          public grade CountUpAction extends AbstractAction {              public CountUpAction(Cord proper noun, Cord shortDesc, Integer mnemonic) {          super(name);          putValue(SHORT_DESCRIPTION, shortDesc);          putValue(MNEMONIC_KEY, mnemonic);       }         @Override       public void actionPerformed(ActionEvent e) {          ++count;          tfCount.setText(count + "");       }    }      public class CountDownAction extends AbstractAction {              public CountDownAction(String name, String shortDesc, Integer mnemonic) {          super(name);          putValue(SHORT_DESCRIPTION, shortDesc);          putValue(MNEMONIC_KEY, mnemonic);       }         @Override       public void actionPerformed(ActionEvent e) {          --count;          tfCount.setText(count + "");       }    }      public course ResetAction extends AbstractAction {              public ResetAction(String name, String shortDesc, Integer mnemonic) {          super(name);          putValue(SHORT_DESCRIPTION, shortDesc);          putValue(MNEMONIC_KEY, mnemonic);       }         @Override       public void actionPerformed(ActionEvent e) {          count = 0;          tfCount.setText(count + "");       }    }          public static void chief(String[] args) {              javax.swing.SwingUtilities.invokeLater(new Runnable() {          public void run() {             new TestAction();            }       });    } }

WindowEvent & WindowListener/WindowAdapter

Interface WindowListener is used for handling WindowEvent triggered via the three special buttons (minimize, maximize/restore down, and shut) on the superlative-right corner of the window or other means. In that location are 7 abstract methods declared in the interface, as follows:

public interface          WindowListener          extends coffee.util.EventListener {    public void          windowClosing(WindowEvent evt);                public void          windowActivated(WindowEvent evt);              public void          windowDeactivated(WindowEvent evt);            public void          windowOpened(WindowEvent evt);                 public void          windowClosed(WindowEvent evt);                 public void          windowIconified(WindowEvent evt);              public void          windowDeiconified(WindowEvent evt);         }

The about commonly-used method is WindowClosing(), which is chosen when the user attempts to close this window via the "window-shut" push or "file-leave" menu item.

            @Override public void WindowClosing(WindowEvent evt) {        ......        ......    System.exit(0);    }
WindowAdapter

A WindowEvent listener must implement the WindowListener interface and provides implementation to ALL the 7 abstract methods alleged. An empty-body implementation is required even if you are not using that particular handler. To better productivity, an adapter form called WindowAdapter is provided, which implements WindowListener interface and provides default implementation to all the 7 abstruse methods. You can then derive a subclass from WindowAdapter and override just methods of interest and get out the rest to their default implementation.

This example shows how to extend a WindowAdapter class, using an bearding inner class, to handle a window-endmost event.

public class GUIApplication extends JFrame {    public GUIApplication() {         ......       this.addWindowListener(new WindowAdapter() {          @Override          public void windowClosing(WindowEvent evt) {             System.leave(0);          }       });    }    ...... }
JFrame'south setDefaultCloseOperation()

In Swing's JFrame, a special method called setDefaultCloseOperation() is provided to handle clicking of the "window-close" button. For instance, to go out the program upon clicking the close-window button, you can use the post-obit instead of WindowListener or WindowAdapter.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        

Similarly, most of the outcome listener interface has its equivalent adapter, eastward.g., MouseAdapter for MouseListener interface, KeyAdapter for KeyListener interface, MouseMotionAdapter for MouseMotionListener interface. There is no ActionAdapter for ActionListener, because in that location is only one abstract method inside the ActionListener interface, with no demand for an adapter.

A word of circumspection: If yous implement the WindowListener yourself and misspell a method name says windowClosing() to winowClosing(), the compiler will bespeak an error to notify you lot that windowClosing() method was not implemented. Even so, if you extend from WindowAdapter class and misspell a method name, the compiler treats the misspell method every bit a new method in the subclass, and uses the default implementation provided by WindowAdapter for handling that event. This small typo error took me a few disturbing hours to debug. This trouble is resolved via the annotation @Override introduced in JDK i.5, which tells the compiler to issue an mistake if the annotated method does non override its superclass.

KeyEvent & KeyListener/KeyAdapter

The KeyListener interface defines three abstract methods:

void          keyTyped(KeyEvent evt)           void          keyPressed(KeyEvent evt)         void          keyReleased(KeyEvent evt)        

At that place are two kinds of key events:

  1. The typing of a valid character, e.chiliad., 'a', 'A'. This is chosen a primal-typed effect.
  2. The pressing or releasing of a fundamental, e.g., upwards-arrow, enter, 'a', shift+'a'. This is a key-pressed or primal-released issue.

Use keyTyped() to procedure central-typed event, which produces a valid Unicode character. You can use evt.getKeyChar() to retrieve the char typed. getKeyChar() can differentiate betwixt 'a' and 'A' (pressed shift+'a').

Yous can utilise keyPressed() and keyReleased() for all the keys, grapheme cardinal or others (such as upwards-arrow and enter). Yous tin can utilize evt.getKeyCode() to retrieve the int Virtual Key (VK) lawmaking, east.g., KeyEvent.VK_UP, KeyEvent.VK_ENTER, KeyEvent.VK_A. Y'all can also apply evt.getKeyChar() to call up the unicode character, if the outcome produced a valid Unicode character.

getKeyCode() vs. getKeyChar()
  • If you lot press 'a' fundamental, getKeyChar() returns 'a' and getKeyCode() returns VK_A.
  • If yous printing shift+'a', 2 key-pressed events and i cardinal-typed event triggered. getKeyChar() returns 'A' and getKeyCode() returns VK_SHIFT in the first key-pressed result and VK_A in the second event. The outset fundamental-pressed issue is oft ignored by the program.

Observe that Virtual Key codes, central-char are used, instead of bodily key code, to ensure platform and keyboard-layout independent.

For Example,

1 two 3 4 five half-dozen 7 eight 9 10 11 12 13 fourteen 15 16 17 xviii nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
import java.awt.*; import java.awt.issue.*; import javax.swing.*;    public class KeyListenerTest extends JFrame implements KeyListener {        public KeyListenerTest() {       Container cp = getContentPane();       cp.addKeyListener(this);              cp.setFocusable(truthful);              cp.requestFocus();         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Testing Key Listener");       setSize(300, 200);       setVisible(true);    }      @Override    public void keyTyped(KeyEvent e) {       char keyChar = e.getKeyChar();       System.out.println("keyTyped: Key char is " + keyChar);    }      @Override    public void keyPressed(KeyEvent e) {       int keyCode = e.getKeyCode();       char keyChar = eastward.getKeyChar();       Organisation.out.println("keyPressed: VK Code is " + keyCode + ", Key char is " + keyChar);    }      @Override    public void keyReleased(KeyEvent eastward) {}              public static void principal(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new KeyListenerTest();            }       });    } }

Endeavour pressing 'a', 'A' (shift+'a'), enter, upward-arrow, etc, and observe the cardinal-char and VK-code produced by keyTyped() and keyPressed().

Below is a sample handler for a key listener:

@Override public void keyPressed(KeyEvent eastward) {    switch (e.getKeyCode()) {       case KeyEvent.VK_UP: ......; interruption       case KeyEvent.VK_DOWN: ......; break       case KeyEvent.VK_LEFT: ......; break       case KeyEvent.VK_RIGHT: ......; interruption    } }   @Override public void keyTyped(KeyEvent e) {        switch (e.getKeyChar()) {       case 'due west': ......; break       case 'a': ......; intermission       case 'z': ......; break       case 's': ......; pause    } }

The commonly-used virtual cardinal codes are:

  • VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN: arrow keys
  • VK_KP_LEFT, VK_KP_RIGHT, VK_KP_UP, VK_KP_DOWN: arrow key on numeric keypad
  • VK_0 to VK_9, VK_A to VK_Z: numeric and alphebet keys. Also produce a Unicode char for the getKeyChar()
  • VK_ENTER, VK_TAB, VK_BACKSPACE

MouseEvent & MouseListener/MouseAdapter

The MouseListener interface is associated with MouseEvent (triggered via mouse-button press, release and click (press followed by release)) on the source object. It declares v abstract methods:

public void          mouseClicked(MouseEvent evt)       public void          mouseEntered(MouseEvent evt)       public void          mouseExited(MouseEvent evt)        public void          mousePressed(MouseEvent evt)       public void          mouseReleased(MouseEvent evt)        

From the MouseEvent statement evt, you can:

  • employ evt.getX() and evt.getY() to retrieve the (x, y) coordinates of the location of the mouse.
  • use evt.getXOnScreen() and evt.getYOnScreen() to retrieve the absolute(x, y) coordinates on the screen.
  • utilise evt.getClickCount() to retrieve the number of clicks, e.m., two for double-click.
  • use evt.getButton() to determine which push button (MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3, or MouseEvent.NOBUTTON) is clicked.

An adapter class MouseAdapter is available, which provides default (empty) implementation to the v abstract methods alleged in the MouseListener interface. You lot tin can create a mouse listener by subclassing the MouseAdapter and override the necessary methods. For example,

            aSource.addMouseListener(new MouseAdapter() {      @Override    public void mouseClicked(MouseEvent evt) {           } });

MouseEvent & MouseMotionListener/MouseMotionAdapter

The MouseEvent is associated with two interfaces: MouseListener (for mouse clicked/pressed/released/entered/exited) described earlier; and the MouseMotionListener (for mouse moved and dragged). The MouseMotionListener interface declares 2 abstract methods:

public void mouseDragged(MouseEvent evt);       public void mouseMoved(MouseEvent evt);        

From the MouseEvent argument, yous can use getX(), getY(), getXOnScreen(), getYOnScreen() to find the position of the mouse cursor, as described before.

The mouseDragged() can be used to draw a arbitrary-shape line using mouse-pointer. The mouse-dragged issue starts when you lot pressed a mouse button, and will be delivered continuously until the mouse-button is released. For case,

@Override public void MouseDragged(MouseEvent evt) {            ...... }
Swing's MouseInputListener/MouseInputAdapter

Swing added a new event listener called MouseInputListener which combines MouseListener and MouseMotionListener as follows. You only need to implement one interface instead of 2 interfaces.

interface javax.swing.upshot.MouseInputListener    extends coffee.awt.MouseListener, java.awt.MouseMotionListener {      }

Swing_MouseDragDemo.png

Example: Using mouse-drag to draw a red rectangle. (You lot demand to understand "Custom Graphics" - the next article - to read this program.)

one two 3 four 5 6 7 8 9 10 11 12 xiii 14 15 sixteen 17 18 19 twenty 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 seventy 71 72 73 74 75 76 77 78 79 fourscore 81 82
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.effect.*;    @SuppressWarnings("series") public class MouseDragDemo extends JFrame {    private int startX, startY, endX, endY;      individual JLabel statusBar;            public MouseDragDemo() {                     JPanel drawPanel = new JPanel() {          @Override          public void paintComponent(Graphics g) {             super.paintComponent(1000);               g.setColor(Color.Red);                          int x = (startX < endX) ? startX : endX;             int y = (startY < endY) ? startY : endY;             int width = endX - startX + ane;             if (width < 0) width = -width;             int height = endY - startY + 1;             if (peak < 0) tiptop = -height;             g.drawRect(x, y, width, height);          }       };         statusBar = new JLabel();       drawPanel.setLayout(new FlowLayout(FlowLayout.LEFT));       drawPanel.add(statusBar);                       MyMouseDraggedListener listener = new MyMouseDraggedListener();       drawPanel.addMouseListener(listener);       drawPanel.addMouseMotionListener(listener);         setContentPane(drawPanel);       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setTitle("Mouse-Elevate Demo");       setSize(400, 250);       setVisible(true);    }      private class MyMouseDraggedListener extends MouseInputAdapter {       @Override       public void mousePressed(MouseEvent evt) {          startX = evt.getX();          startY = evt.getY();          statusBar.setText("(" + startX + "," + startY + ")");       }       @Override       public void mouseDragged(MouseEvent evt) {          endX = evt.getX();          endY = evt.getY();          statusBar.setText("(" + endX + "," + endY + ")");          repaint();         }       @Override          public void mouseReleased(MouseEvent evt) {          endX = evt.getX();          endY = evt.getY();          statusBar.setText("(" + endX + "," + endY + ")");          repaint();         }    }          public static void principal(Cord[] args) {              SwingUtilities.invokeLater(new Runnable() {          @Override          public void run() {             new MouseDragDemo();            }       });    } }

[TODO] GUI programming is huge. Need to divide into a few manufactures.

REFERENCES & Resources

  1. "Creating a GUI With JFC/Swing" (aka "The Swing Tutorial") @ http://docs.oracle.com/javase/tutorial/uiswing/.
  2. JFC Demo (nether JDK demo "jfc" directory).
  3. "SwingLabs" java.net project @ http://java.net/projects/swinglabs.
  4. Java2D Tutorial @ http://docs.oracle.com/javase/tutorial/2d/alphabetize.html.
  5. JOGL (Java Binding on OpenGL) @ http://java.cyberspace/projects/jogl/.
  6. Java3D (@ http://java3d.coffee.net/).

meighancoust1957.blogspot.com

Source: https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html

0 Response to "Draw a Circle in J Scroll Pane Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel