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

转载于:https://www.cnblogs.com/hahaccy/p/8053980.html

Graphical User Interface(GUI)相关推荐

  1. B站台湾大学郭彦甫|MATLAB 学习笔记|07 Graphical user interface(GUI)设计

    MATLAB学习笔记(07 Graphical user interface(GUI)设计) 如果想获得更好浏览体验的朋友可以转到下面链接 07 (MATLAB R2021a版本提示GUIDE将在未来 ...

  2. 基于Python的自媒体小助手---图形用户界面Graphical User Interface)

    图形用户界面Graphical User Interface,简称 GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界面.GUI 的需求变得明显,因为第一个人/计算机文本界面是通过所谓的 ...

  3. GUI(Graphical User Interface)

    译:用户和图形界面 GUI与程序交互的不同方式,包含3基本要素:输入,处理和输出. 常用GUI框架包括以下几种: wxPython Kivy Flexx PyQt Tkinter Pywin32 Py ...

  4. matlab gui 播放音频,基于MATLAB的GUI(Graphical User Interface)音频实时显示设计

    [博主原创] 摘要:本文章的设计主要讲基于matlab的gui音频实时显示设计,此次设计的gui相当于一个简洁的音乐播放器,界面只有"录音"和"播放"两个控件, ...

  5. GUI(Graphical User Interface)—关于一道题的按钮事件处理知识点总结

    首先得多少了解GUI,才知道我总结的是什么 题目:设计一个界面,要求使用JFrame,JButton(2个),JTextArea控件.实现:JTextArea 用户可以在控件中输入内容:JButton ...

  6. matlab gui .fig,精通MATLAB GUI设计 matlab gui 图形处理 图形用户界面(Graphical User Interface - 下载 - 搜珍网...

    压缩包 : xunzai.com_陈垚光<精通MATLAB GUI设计>.rar 列表 陈垚光<精通MATLAB GUI设计>/第10章/exm10.m 陈垚光<精通MA ...

  7. pix2code:Generating Code from a Graphical User Interface Screenshot

    微信公众号同步文章:让AI自动生成代码,我在研究未来可能让程序员失业的科技 微信公众号文章地址: https://mp.weixin.qq.com/s?__biz=MzI5NDMzMjY1MA==&a ...

  8. java图形用户界面交互_图形用户界面(graphical user interface)

    1 java中提供的类库 1.1 定义 AWT(abstract windows toolkit)抽象窗口工具包:提供了与本地图形界面进行交互的接口,AWT中提供的图形函数与操作系统的图形函数有着对应 ...

  9. 使用tkinter模块在Python中进行GUI编程

    GUI (Graphical User Interface): GUI(图形用户界面): GUI is a simple application which helps the user to int ...

最新文章

  1. php拼音模糊查询,PHP模糊查询技术实例分析【附源码下载】
  2. 【Python】Pandas基础:结构化数据处理
  3. JVM内存分为哪几部分?各个部分的作用是什么?
  4. 女人 这20种男人你永远不必等
  5. redis 启动加载mysql_Redis分析系列:启动加载过程
  6. java中 静态方法与成员方法何时使用
  7. hdu 3074 线段树 OR 树状数组
  8. C语言实例 区分旅客国籍
  9. centos7 识别移动硬盘
  10. TCMalloc小记【转】
  11. Tomcat(一):基础配置详解
  12. Java毕业设计-企业员工考勤打卡管理系统
  13. odb格式Linux,ODB格式文件 如何打开ODB文件 ODB是什么格式的文件 用什么打开 - The X 在线工具...
  14. C预处理器和C函数库
  15. linux文件扫描并打印,Linux办公一条龙—Linux中扫描、打印的实现
  16. 【OpenCV】生成透明的PNG图像
  17. android开发--mp3播放器项目源代码(xml文件解析,.lrc,.mp3文件下载,同时显示歌词)
  18. 主流RGB灯,灯带通用C语言程序
  19. 多python版本共存的环境中,查看 pip 命令对应的 python 版本
  20. A_A02_003 ST-LINK驱动安装

热门文章

  1. 如何从移动硬盘中分出一个区做启动盘
  2. 这款报表工具可以秒杀市面上各种可视化,可惜很多人都没用过
  3. 轻量化网络结构——Xception
  4. Mycat数据库中间件-入门
  5. 【GUI】一、Swing外观框架BeautyEye使用
  6. Spring Security——OAuth2.0
  7. tomcat开机自启动
  8. 工业互联网·化工废水处理PLC远程监控系统
  9. 《工程电磁场》学习笔记3-恒定磁场
  10. 【奇闻】广东百岁老妇入棺前“复生” 已办16小时丧事