Graphical User Interface (GUI)

AWT and Swing

Abstract Window Toolkit (AWT):

  Introduced in Java 1.0 Provides classes and other tools for building programs that have a graphical user interface

  The term “Abstract” refers to the AWT’s ability to run on multiple platforms.

  Building a GUI involves creating “abstract” components such as buttons and windows, which are then mapped to “concrete” components for a specific platform.

Swing: Introduced in Java SE 1.2 Swing is more powerful and sophisticated than the AWT.

  Swing is built around the existing AWT, so it helps to understand the AWT first.

  Many Swing classes correspond to AWT classes.

For example, Swing’s JButton class corresponds to the AWT’s Button class.

Java Foundation Classes (JFC)

  The Java Foundation Classes (JFC) are a graphical framework for building portable Java-based graphical user interfaces (GUIs).

  JFC consists of:

    Abstract Window Toolkit (AWT)

    Swing 

    Java 2D

    Together, they provide a consistent user interface for Java programs, regardless whether the underlying user interface system is Windows, Mac OS X or Linux.

Creating a Graphical User Interface

  GUI programming in Java is based on three concepts:

    Components: A component is an object that the user can see on the screen and—in most cases—interact with.

    Containers: A container is a component that can hold other components.

    Events: An event is an action triggered by the user, such as a key press or mouse click.

  Designing a graphical user interface involves 1)creating components, 2)putting them into containers, 3)arranging for the program to respond to events.

Basic Principles:

  Components are objects, so they’re created by invoking a constructor E.g., a button would be created by using a constructor belonging to the Button class.

  Button b = new Button("Testing");

  For a component to be visible, it must be added to a container, typically a frame

  Actions. events and listeners: An event object is an object that the Java system creates at run-time to represent a user action,

  e.g., a mouse click To detect when an event occurs, a special “listener” object can be attached to a component.

  When the user performs an action that involves the component, a method belonging to the listener object will be called automatically.

Frames

  In Java terminology, a frame is a window with a title and a border

  It is a top level window, and may also have a menu bar.

  Frame classes:

    AWT: java.awt.Frame

    Swing: javax.swing.JFrame

    Frames play an important role in the AWT because a GUI program normally displays a frame when it’s executed.

-The Frame Class

  Frames are created using one of the constructors in the JFrame class,

  e.g.:

    JFrame f = new JFrame("Title goes here");

    JFrame methods:

     Set the size of the frame:

      setSize(WIDTH, HEIGHT);

    Set/get title:

      setTitle(“Frame Title”);

      String s=f.getTitle();

    Set the size of the frame:

      setSize(WIDTH, HEIGHT);

    Set position of the frame:

      setLocation(x,y);

    Select closing options:

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Set the frame visibility:

      setVisible(true);

      setVisible(false);                       (The Frame object still exists; it can be made to reappear later by calling setVisible again.)

 

exa:

 

    JFrame f = new Frame("Frame Test");  //new一个Frame

    f.setTitle("A Simple Frame"); 

    f.setSize(300, 200);

    f.setLocation(100,100);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.setVisible(true);

-Frame size:

  By default, a frame will be 0*0;

  There is no good sizes, as users’ screens may have different resolutions We can get the screen size via the following steps: //大小为屏幕的四分之一

  Toolkit kit=Toolkit.getDefaultToolkit();

  Dimension screenSize=kit.getScreenSize();

  int screenWidth=screenSize.width;

  int screenHeight=screenSize.height;

  int frameWidth=screenWidth/2;

  int frameHeight=screenHeight/2;

  this.setSize(frameWidth, frameHeight);

Adding Components to a Frame

  java.awt.Component

  A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user.

  Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.

  The superclass of all GUI elements

        

 

 

  Display something inside a frame

  It can be done by drawing a string directly on the frame,

  but that is not a good practice.

  We normally create components, e.g., menu, button, …,

  and then add them to a frame Component classes:

    javax.swing.JComponent;

    java.awt.Component;

 

  public class MyComponent extends JComponent {

     public void paintComponent( Graphics g ){

      //code for drawing

     }

    }

  myFrame.add(new MyComponent());

 

 

 

exa2

  private Image image;

  public class MyComponent extends JComponent {

    public void paintComponent( Graphics g ){

    image=new ImageIcon("aut.jpg").getImage();

    g.drawImage(image, 0,0,null);

    }

  }

Button and Event handling

Create a button object (JButton):

  JButton blue = new JButton(“Blue");

  f.add(b);

 

  The button has no effect now To make the button work, we need an event listener

 

Event Handling

  General process:

  When the user performs an action, Java creates an object containing information about the event.

  An event source (e.g., a button) can register listener objects and send event objects to listeners Event objects will then be sent to listeners when events occurs

  The listener objects will then use the information in the event objects to determine their reaction to the event.

      

  ActionListener interface:

  We can create our own action listeners by implementing the ActionListener interface To implement the ActionListener interface, the class must have an actionPerfermed method (override)

  

  class MyListener implements ActionListener{

   ..…

  public void actionPerformed(ActionEvent event){

     // reaction to button click

    }

   }

Attach a listener object to each button:

  MyListener listener=new MyListener();

  button.addActionListener(listener);

 

sol1:

  public ButtonTest() {

    buttonPanel=new JPanel();

    JButton blueButton=new JButton("blue");

    JButton redButton=new JButton("red");

    ActionListener blueAction= new ColorAction (Color.BLUE);

     ActionListener redAction= new ColorAction (Color.RED);

     blueButton.addActionListener(blueAction);

    redButton.addActionListener(redAction);

     … }

 

  public class ColorAction implements ActionListener{

    private Color backgoundColor;

    public ColorAction(Color c){

    backgoundColor=c;

    }

    @Override

    public void actionPerformed(ActionEvent e) {

       buttonPanel.setBackground(backgoundColor);

      }

    }

sol2:

  public class ButtonTest2 extends JFrame implements ActionListener {

    ……

    blueButton.addActionListener(this);

    redButton.addActionListener(this);

    ……

   }

  public void actionPerformed(ActionEvent e) {

    Object source=e.getSource();

     if(source==blueButton){

      buttonPanel.setBackground(Color.BLUE);

    }

    if(source==redButton){

      buttonPanel.setBackground(Color.RED);

       }

    }

Panel and Layout Management

-JPanel:

  A generic lightweight container Components can be added to a panel

  Then a panel can be added to a frame

  Add components into a panel:

    aPanel.add(component);

  Clear a panel:

    aPanel.removeAll();

  Update a panel:

    aPanel.revalidate();

    aPanel.updateUI();

    aPanel.repaint();

 

-Layout in a container:

  You can set layout for a container to arrange multiple components

  Every container has a default layout manager that determines the sizes and positions of components within the container

  By using layout managers, containers can be resized gracefully.

  

  buttonPanel.add(blueButton);

  buttonPanel.add(redButton);

  frame.add(buttonPanel, BorderLayout.SOUTH);

GridLayout:

  Arranges all components in rows and columns

  In constructor of the grid layout object, you need to specify how many rows and columns you need:

  Panel.setLayout(new GridLayout(3,4));

        

Other GUI Components

JTextField:

  Allow users to input text

  You can add it to a panel or other container:

  

  JPanel panel=new JPanel();

  JTextField textField=new JTextField(“Default Text”, 20);

  panel.add(textField)

  You can get the text in a TextField by using:

  String text= textField.getText();

JLabel:

  Hold text (display only)

  Normally used to identify components

  

  JLabel label=new JLabel(“User name: ” , JLabel.Right);

  The text in a label can be re-set:

  label.setText(“password”);

JTextArea:

   Allow user input multiple lines of text

  Users can use “Enter” to separate different lines

  Each line ends with “\n”

  JTextArea textArea=new JTextArea(8, 40);

 

JScollPane:

   A text area does not have scrollbars

  You can place the text area inside a scroll pane

  JTextArea textArea=new JTextArea(8, 40);

  JScrollPane scrollPane=new JScrollPane(textArea);

JCheckBox:

  A checkbox is a small box that the user can “check” by clicking with the mouse:

   Clicking on the box causes a check mark to appear:

   Clicking a second time removes the check mark from the box

  JCheckBox sound= new JCheckBox(“Enable sounds”);

 

  Use the setSelected method to turn a checkbox or/off:

  sound.setSelected(true);

 

  The isSelected method then returns the current state of a check box

  ActionListener is needed to attach to a checkbox

 

  ……

  bold = new JCheckBox("Bold");

  bold.addActionListener(listener);

  bold.setSelected(true);

  buttonPanel.add(bold);

  italic = new JCheckBox("Italic");

  italic.addActionListener(listener);

  ……

  ActionListener listener = new ActionListener() {

    public void actionPerformed(ActionEvent event) {

     int mode = 0;

    if (bold.isSelected())

    mode += Font.BOLD;

     if (italic.isSelected())

     mode += Font.ITALIC;

     label.setFont(new Font("Serif", mode, FONTSIZE));

    }

  };

Radio Buttons:

   In many cases, we want the user to check one of several boxes:

  When one box is checked, others are turned off automatically

  In Swing, radio buttons can be constructed by following:

  Construct a ButtonGroup object:

  ButtonGroup group = new ButtonGroup();

 

  Create JRadioButton objects, and add to the button group:

  JRadioButton button = new JRadioButton(“left”, true);

  group.add(button);

 

  Attach with action listeners

  button.addActionListener(listener);

Combo Boxes:

   If you want the users to choose from many options, then you need a combo box:

  In Java 7, JComboBox is a generic class JComboBox<String> …

  You can add items to a combo box via:

  JComboBox<String> combo=new JComboBox();

  combo.addItem(“China”);

  you can get the selected item by using getSelectedItem(), but the item may have any type, and you need to cast the type.

  Alternatively, the following method can give you selected item with the correct type:

  combo.getItemAt(combo.getSelectedIndex());

  Attach with action listeners

posted @ 2017-12-18 00:24  CaiCongyu  阅读(316)  评论(0编辑  收藏  举报