201871010101-陈来弟《面向对象程序设计(JAVA)》 第14周学习总结

实验十二  Swing图形界面组件(一)

实验时间 2019-11-29

 

第一部分:基础知识

Swing和MVC设计模式

(1)设计模式(Design pattern)是设计者一种流行的 思考设计问题的方法,是一套被反复使用,多数人 知晓的,经过分类编目的,代码设计经验的总结。

(2)模型-视图-控制器设计模式(Model –ViewController )是Java EE平台下创建 Web 应用程序 的重要设计模式。

(3)MVC设计模式 – Model(模型):是程序中用于处理程序数据逻 辑的部分,通常模型负责在数据库中存取数据。

– View(视图):是程序中处理数据显示的部分, 通常视图依据模型存取的数据创建。

– Controller(控制器):是程序中处理用户交互 的部分。通常控制器负责从视图读取数据,控制 用户输入,并向模型发送数据。

(4)Java组件有内容、外观、行为三个主要元素;

 布局管理器

(1)布局管理器是一组类。 – 实现 java.awt.LayoutManager 接口 – 决定容器中组件的位置和大小

Java.awt包中定义了5种布局管理类,每一种布 局管理类对应一种布局策略。

每个容器都有与之相关的默认布局管理器。

(2)5种布局管理器:(1)FlowLayout: 流布局(Applet和Panel的默认 布局管理器) (2)BorderLayout:边框布局( Window、Frame和 Dialog的默认布局管理器) (3)GridLayout: 网格布局 (4)GridBagLayout: 网格组布局 (5)CardLayout :卡片布局

3、GridLayout的构造函数如下:1、GridLayout():生成一个单行单列的网格布局

2、GridLayout(int rows,int cols):生成一个设定行数 和列数的网格布局

3、GridLayout(int rows,int columns,int hgap,int vgap): 可以设置组件之间的水平和垂直间隔

 文本输入

(1)文本域(JTextField) : 用于获取单行文本输入。

(2)文本区(JTextArea)组件可让用户输入多行文 本。生成JTextArea组件对象时,可以指定文本 区的行数和列数: textArea = new JTextArea(8, 40);

  (3)文本区与文本域的异同相同之处: 文本域和文本区组件都可用于获取文本输入。

不同之处:  文本域只能接受单行文本的输入;  文本区能够接受多行文本的输入。

(4)文本区JTextArea的常用API:Java.swing. JTextArea 1.2 – JTextArea(int rows, int cols)

构造一个rows行cols列的文本区对象 – JTextArea(String text,int rows, int cols)

用初始文本构造一个文本区对象 – void setRows(int rows)

设置文本域使用的行数 – void append(String newText)

将给定文本附加到文本区中已有文本的后面 – void setLineWrap(boolean wrap)

打开或关闭换行

(5)标签组件:标签是容纳文本的组件。它们没有任何修饰(如没有边界 ),也不响应用户输入。

 标签的常用用途之一就是标识组件,例如标识文本域。其使用步骤如下:

1. 创建一个JLabel组件

2. 将标签组件放置在距离被标识组件足够近的地方。

(6)密码域:密码域是一种特殊类型的文本域。每个输入的字 符都用回显字符实现,典型的回显字符为*。

– JPassWordField(String text, int columns) 构造一个密码域对象

(7)滚动窗格:

Swing中文本区没有滚动条,若需要滚动条。将文 本区放入一个滚动窗格中即可。

常用API—Java.swing. JScrollPane(教材340页) – JScrollPane(Component c) 在组件c上添加滚动条,返回添加后的组件。

 选择组件

复选框  单选按钮  边框  组合框  滑动条

(1)复选框构造器 1.bold = new JCheckBox("Bold"); 复选框自动地带有表示标签。

2. JCheckBox(String label,Icon icon); 构造带有标签与图标的复选框,默认初始未被选择。

3.JCheckBox(String label,boolean state); 用指定的标签和初始化选择状态构造一个复选框

(2)单选按钮的构造器(教材492页) 1.JRadioButton(String label,Icon icon); 创建一个带标签和图标的单选按钮

2.JRadioButton(String label,boolean state); 用指定的标签和初始化状态构造单选按钮

(3)按钮组:为单选按钮组构造一个ButtonGroup的对象。 然后,再将JRadioButton类型的对象添加到按钮 组中。按钮组负责在新按钮被按下的时,取消前一 个按钮的选择状态。

(4)如果在一个窗口中 有多组复选框或单选按 钮,就需要可视化的形 式指明哪些按钮属于同 一组。Swing提供了一 组很有用的边框

(5)如果有多个选择项,使用单选按钮占据的屏幕空 间太大时,就可以选择组合框。

faceCombo = new JComboBox(); faceCombo.setEditable(true);

让组合框可编辑 faceCombo.addItem("Serif"); faceCombo.insertItemAt("Monospace",0);

增加组合框选项 faceCombo.removeItem("Monospace");

faceCombo.removeItemAt(0); 删除组合框选项内容

(6)组合框的事件监听:为了判断组合框的哪个选项被选择,可通过 事件参数调用getSource方法来得到发送事件的组 合框引用,接着调用getSelectdeItem方法获取当 前选择的选项。

(7)滑动条:滑动条可以让用户从一组离散值中进行选择 ,并且它还允许进行连续值得选择。

 菜单

菜单创建  菜单项中的图标  复选框和单选按钮菜单项  弹出菜单  快捷键和加速器  启用和禁用菜单项  工具栏  工具提示

网格组布局 (GridBagLayout):GridBagLayout与GridLayout有点相似,它也是 将组件排在格子里,但是GridBagLayout在网格 的基础上提供更复杂的布局。

GridBagLayout允许单个组件在一个单元中不填 满整个单元,而只是占用最佳大小,也允许单个 组件扩展成不止一个单元,并且可以用任意顺序 加入组件。

定制布局管理器: 程序员可通过自己设计LayoutManager类来实现 特殊的布局方式。

定制布局管理器需要实现LayoutManager接口, 并覆盖以下方法。

 对话框

选项对话框   创建对话框   数据选择   文件对话框  颜色选择器

(1)对话框是一种大小不能变化、不能有菜单的容器窗口; 对话框不能作为一个应用程序的主框架,而必须包含在其 他的容器中。

(2)选项对话框:JOptionPane提供的对话框是模式对话框。当模 式对话框显示时,它不允许用户输入到程序的 其他的窗口。使用JOptionPane,可以创建和自 定义问题、信息、警告和错误等几种类型的对 话框。

(3)数据交换:输入对话框含有供用户输入文本的文本框、一个确认和取 消按钮,是有模式对话框。当输入对话框可见时,要求用户 输入一个字符串。

(4)文件对话框:专门用于对文件(或目录)进行浏览和选择的对 话框,常用的构造方法: – JFileChooser():根据用户的缺省目录创建文件对话框 – JFileChooser(File currentDirectory):根据File型参数 currentDirectory指定的目录创建文件对话框

(5)颜色对话框: javax.swing包中的JColorChooser类的静态方 法: public static Color showDialog(Component component, String title, Color initialColor)创建一个颜色对话框

(6)参数component指定对话框所依赖的组件,title 指定对话框的标题;initialColor 指定对话框返回 的初始颜色,即对话框消失后,返回的默认值。 颜色对话框可根据用户在颜色对话框中选择的颜 色返回一个颜色对象.

第二部分:实验

1、实验目的与要求

(1)掌握GUI布局管理器用法;

(2)掌握Java Swing文本输入组件用途及常用API;

3)掌握Java Swing选择输入组件用途及常用API;

2、实验内容和步骤

实验1: 导入第12章示例程序,测试程序并进行组内讨论。

测试程序1

l 在elipse IDE中运行教材479页程序12-1,结合运行结果理解程序;

l 掌握布局管理器的用法;

l 理解GUI界面中事件处理技术的用途。

l 在布局管理应用代码处添加注释;

12-1 代码:

package calculator;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class Calculator
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         CalculatorFrame frame = new CalculatorFrame();
         frame.setTitle("Calculator");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

 

package calculator;

import javax.swing.*;

/**
 * A frame with a calculator panel.
 */
public class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      add(new CalculatorPanel());
      pack();
   }
}

 

package calculator;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * A panel with calculator buttons and a result display.
 */
public class CalculatorPanel extends JPanel
{
   private JButton display;//定义显示Button组件对象
   private JPanel panel;
   private double result;//定义基本数据对象
   private String lastCommand;
   private boolean start;//布尔型:开始启动为ture

   public CalculatorPanel()//构造器
   {
      setLayout(new BorderLayout());//边框布局管理器

      result = 0;
      lastCommand = "=";
      start = true;

      // 添加显示

      display = new JButton("0");
      display.setEnabled(false);
      add(display, BorderLayout.NORTH);//显示在窗口上方

      InsertAction insert = new InsertAction();
      CommandAction command = new CommandAction();

      // 在一个4*4的网格中添加按钮

      panel = new JPanel();
      panel.setLayout(new GridLayout(4, 4));//网格布局管理器:4行4列

      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", command);

      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", command);

      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", command);

      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);

      add(panel, BorderLayout.CENTER);//显示在窗口中心位置
   }

   /**
    * Adds a button to the center panel.
    * @param label the button label
    * @param listener the button listener
    */
   private void addButton(String label, ActionListener listener)//普通方法
   {
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }

   /**
    * This action inserts the button action string to the end of the display text.
    */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();
         if (start)
         {
            display.setText("");
            start = false;
         }
         display.setText(display.getText() + input);
      }
   }

   /**
    * This action executes the command that the button action string denotes.
    */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String command = event.getActionCommand();

         if (start)
         {
            if (command.equals("-"))
            {
               display.setText(command);
               start = false;
            }
            else lastCommand = command;
         }
         else
         {
            calculate(Double.parseDouble(display.getText()));
            lastCommand = command;
            start = true;
         }
      }
   }

   /**
    * Carries out the pending calculation.
    * @param x the value to be accumulated with the prior result.
    */
   public void calculate(double x)//普通方法:计算数值
   {
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
      else if (lastCommand.equals("=")) result = x;
      display.setText("" + result);
   }
}

其运行结果:

 

 

 

测试程序2

l 在elipse IDE中调试运行教材486页程序12-2,结合运行结果理解程序;

l 掌握文本组件的用法;

l 记录示例代码阅读理解中存在的问题与疑惑。

12-2 代码:

package text;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.42 2018-04-10
 * @author Cay Horstmann
 */
public class TextComponentTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         TextComponentFrame frame = new TextComponentFrame();
         frame.setTitle("TextComponentTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

package text;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

/**
 * A frame with sample text components.
 */
public class TextComponentFrame extends JFrame
{
   public static final int TEXTAREA_ROWS = 8;
   public static final int TEXTAREA_COLUMNS = 20;

   public TextComponentFrame()
   {
      JTextField textField = new JTextField();
      JPasswordField passwordField = new JPasswordField();

      JPanel northPanel = new JPanel();
      northPanel.setLayout(new GridLayout(2, 2));
      //SwingConstants通常用于在屏幕上定位或定向组件的常量的集合
      northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
      northPanel.add(textField);
      northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
      northPanel.add(passwordField);

      add(northPanel, BorderLayout.NORTH);
      
    //构造具有指定行数和列数的新的空 TextArea。
      JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
    //创建一个显示指定组件内容的 JScrollPane对象,只要组件的内容超过视图大小就会显示水平和垂直滚动条。

      JScrollPane scrollPane = new JScrollPane(textArea);

      add(scrollPane, BorderLayout.CENTER);

      // add button to append text into the text area

      JPanel southPanel = new JPanel();

      JButton insertButton = new JButton("Insert");
      southPanel.add(insertButton);

      //将给定文本追加到文档结尾。
      insertButton.addActionListener(event->
         textArea.append("User name: " + textField.getText() + " Password: "
            + new String(passwordField.getPassword()) + "\n"));

      add(southPanel, BorderLayout.SOUTH);
      pack();
   }
}

实验运行结果:

 

 测试程序3

l 在elipse IDE中调试运行教材489页程序12-3,结合运行结果理解程序;

l 掌握复选框组件的用法;

l 记录示例代码阅读理解中存在的问题与疑惑。

12-3 代码:

package checkBox;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class CheckBoxTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         var frame = new CheckBoxFrame();
         frame.setTitle("CheckBoxTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}
package checkBox;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * A frame with a sample text label and check boxes for selecting font
 * attributes.
 */
public class CheckBoxFrame extends JFrame
{
   private JLabel label;
   private JCheckBox bold;
   private JCheckBox italic;
   private static final int FONTSIZE = 24;

   public CheckBoxFrame()//构造器
   {
      //添加示例文本标签

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      label.setFont(new Font("Serif", Font.BOLD, FONTSIZE));
      add(label, BorderLayout.CENTER);//边框布局管理器

      // this listener sets the font attribute of
      // the label to the check box state

      ActionListener listener = event -> {//设置字体为常规、加粗或斜体等
         int mode = 0;
         if (bold.isSelected()) mode += Font.BOLD;
         if (italic.isSelected()) mode += Font.ITALIC;
         label.setFont(new Font("Serif", mode, FONTSIZE));
      };

      // 添加复制框

      JPanel buttonPanel = new JPanel();

      bold = new JCheckBox("Bold");
      bold.addActionListener(listener);
      bold.setSelected(true);
      buttonPanel.add(bold);

      italic = new JCheckBox("Italic");
      italic.addActionListener(listener);
      buttonPanel.add(italic);

      add(buttonPanel, BorderLayout.SOUTH);
      pack();
   }
}

其运算结果:

 

测试程序4

l 在elipse IDE中调试运行教材491页程序12-4,运行结果理解程序;

l 掌握单选按钮组件的用法;

l 记录示例代码阅读理解中存在的问题与疑惑。

12-4 代码:

package radioButton;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class RadioButtonTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         RadioButtonFrame frame = new RadioButtonFrame();
         frame.setTitle("RadioButtonTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

 

package radioButton;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * A frame with a sample text label and radio buttons for selecting font sizes.
 */
public class RadioButtonFrame extends JFrame
{
   private JPanel buttonPanel;
   private ButtonGroup group;//定义一个ButtonGroup对象
   private JLabel label;
   private static final int DEFAULT_SIZE = 36;

   public RadioButtonFrame()//构造器
   {      
      // add the sample text label

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
      add(label, BorderLayout.CENTER);//边框布局管理器:显示在窗口中心

      // 添加单选按钮

      buttonPanel = new JPanel();
      group = new ButtonGroup();

      addRadioButton("Small", 8);
      addRadioButton("Medium", 12);
      addRadioButton("Large", 18);
      addRadioButton("Extra large", 36);

      add(buttonPanel, BorderLayout.SOUTH);//四个按钮显示在窗口下方
      pack();
   }

   /**
    * Adds a radio button that sets the font size of the sample text.
    * @param name the string to appear on the button
    * @param size the font size that this button sets
    */
   public void addRadioButton(String name, int size)
   {
      boolean selected = size == DEFAULT_SIZE;
      JRadioButton button = new JRadioButton(name, selected);
      group.add(button);
      buttonPanel.add(button);

      // 这个监听器设置标签字体大小

      ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));

      button.addActionListener(listener);
   }
}

其运行结果:

 

测试程序5

l 在elipse IDE中调试运行教材494页程序12-5,结合运行结果理解程序;

l 掌握边框的用法;

l 记录示例代码阅读理解中存在的问题与疑惑。

12-5 代码:

package border;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class BorderTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         var frame = new BorderFrame();
         frame.setTitle("BorderTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}
package border;

import java.awt.*;

import javax.swing.*;
import javax.swing.border.*;

/**
 * A frame with radio buttons to pick a border style.
 */
public class BorderFrame extends JFrame
{
   private JPanel demoPanel;
   private JPanel buttonPanel;
   private ButtonGroup group;

   public BorderFrame()
   {
      demoPanel = new JPanel();
      buttonPanel = new JPanel();
      group = new ButtonGroup();

      addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder());
      addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder());
      addRadioButton("Etched", BorderFactory.createEtchedBorder());
      addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
      addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE));
      addRadioButton("Empty", BorderFactory.createEmptyBorder());

      Border etched = BorderFactory.createEtchedBorder();
      Border titled = BorderFactory.createTitledBorder(etched, "Border types");
      buttonPanel.setBorder(titled);

      setLayout(new GridLayout(2, 1));
      add(buttonPanel);
      add(demoPanel);
      pack();
   }

   public void addRadioButton(String buttonName, Border b)
   {
      JRadioButton button = new JRadioButton(buttonName);
      button.addActionListener(event -> demoPanel.setBorder(b));
      group.add(button);
      buttonPanel.add(button);
   }
}

 

 

 测试程序6

在elipse IDE中调试运行教材498页程序12-6,结合运行结果理解程序;

l 掌握组合框组件的用法;

l 记录示例代码阅读理解中存在的问题与疑惑。

12-6 代码:

package comboBox;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.36 2018-04-10
 * @author Cay Horstmann
 */
public class ComboBoxTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         ComboBoxFrame frame = new ComboBoxFrame();
         frame.setTitle("ComboBoxTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

 

package comboBox;

import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * A frame with a sample text label and a combo box for selecting font faces.
 */
public class ComboBoxFrame extends JFrame
{
   private JComboBox<String> faceCombo;
   private JLabel label;
   private static final int DEFAULT_SIZE = 24;

   public ComboBoxFrame()
   {
      // add the sample text label

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
      add(label, BorderLayout.CENTER);

      // make a combo box and add face names

      faceCombo = new JComboBox<>();
      faceCombo.addItem("Serif");
      faceCombo.addItem("SansSerif");
      faceCombo.addItem("Monospaced");
      faceCombo.addItem("Dialog");
      faceCombo.addItem("DialogInput");

      // the combo box listener changes the label font to the selected face name

      faceCombo.addActionListener(event ->
         label.setFont(
            new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), 
               Font.PLAIN, DEFAULT_SIZE)));

      // add combo box to a panel at the frame's southern border

      JPanel comboPanel = new JPanel();
      comboPanel.add(faceCombo);
      add(comboPanel, BorderLayout.SOUTH);
      pack();
   }
}

 其运行结果:

 

实验2:结对编程练习

利用所掌握的GUI技术,设计一个用户信息采集程序,要求如下:

(1) 用户信息输入界面如下图所示:

 

(2) 用户点击提交按钮时,用户输入信息显示在录入信息显示区,格式如下:

 

(3) 用户点击重置按钮后,清空用户已输入信息;

(4) 点击窗口关闭,程序退出。

编程设计:

package comboBox;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
 
public class Chen
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new FrameTest();
         frame.setTitle("Designed by 陈来弟");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}
 
 
 
class FrameTest extends JFrame
{
   
    private JPanel panel;
    private JTextArea text,text2;
    private JRadioButton JRadioButton1,JRadioButton2;
    private ButtonGroup ButtonGroup;
    private JLabel JLabel;
    private JCheckBox h1,h2,h3;
    private JComboBox<String> JComboBox;
    private JButton Button,Button2;
   
   
   public FrameTest()
   {
      setSize(700,500);
      panel=new JPanel();
      panel.setLayout(null);
 
      ButtonGroup=new ButtonGroup();
      JRadioButton1=new JRadioButton("男",false);   JRadioButton1.setBounds(150,330, 80, 50);
      JRadioButton2=new JRadioButton("女",false); JRadioButton2.setBounds(150,300, 80,50);
      ButtonGroup.add(JRadioButton1);
      ButtonGroup.add(JRadioButton2);
     
      addJLabel("性别:",100,300);
      addJLabel("姓名:",100,50);
      addJLabel("地址:",100,150);
      addJLabel("年级:",400,50);
      addJLabel("爱好:",400,150);
     
     
      text=new JTextArea(1,1);text.setBounds(150,70, 120, 30);text.setLineWrap(true);
      text2=new JTextArea(5,3);text2.setBounds(150,160, 130, 100);text2.setLineWrap(true);
     
     
      h1=new JCheckBox("阅读");h1.setBounds(450,160,100,30);
      h2=new JCheckBox("跳舞");h2.setBounds(450,180,100,30);
      h3=new JCheckBox("唱歌");h3.setBounds(450,200,100,30);
 
     
      JComboBox=new JComboBox<>();
      JComboBox.addItem("大一");
      JComboBox.addItem("大二");
      JComboBox.addItem("大三");
      JComboBox.setBounds(500,65, 100, 20);
     
      Button = new JButton("提交");Button.setBounds(200, 400, 100, 35);
      Button2 = new JButton("重置");Button2.setBounds(400, 400, 100, 35);
 
      Button.addActionListener(new Action1());
      Button2.addActionListener(new Action2());
     
      panel.add(h1);
      panel.add(h2);
      panel.add(h3);
      panel.add(Button);
      panel.add(Button2);
      panel.add(JComboBox);
      panel.add(text);
      panel.add(text2);
      panel.add(JRadioButton1);
      panel.add(JRadioButton2);
      add(panel);
     
     
   }
  
  
   public void addJLabel(String n,int a,int b)
   {
       JLabel = new JLabel(n);
       JLabel.setBounds(a,b,100,50);
       panel.add(JLabel);
   }
  
   private class Action1 implements ActionListener
   {
   public void actionPerformed(ActionEvent event)
       {       
       System.out.println("姓名:"+text.getText()+"\n"+"地址:"+text2.getText());
       System.out.println("年级:"+JComboBox.getSelectedItem());
       System.out.println("爱好:");
       if(h1.isSelected()==true)System.out.print(h1.getText());
       if(h2.isSelected()==true)System.out.print(h2.getText());
       if(h3.isSelected()==true)System.out.print(h3.getText());
       System.out.println("\n"+"性别:");
       if(JRadioButton1.isSelected()==true)System.out.println(JRadioButton1.getText());
       if(JRadioButton2.isSelected()==true)System.out.println(JRadioButton2.getText());
       System.out.println("\n");
       }
   }
   private class Action2 implements ActionListener
   {
   public void actionPerformed(ActionEvent event)
       {       
       text.setText(null);
       text2.setText(null);
       h1.setSelected(false);
       h2.setSelected(false);
       h3.setSelected(false);
       ButtonGroup.clearSelection();
       JComboBox.setSelectedIndex(0);
       }
   }  
}

 

其运算结果:

 

 以下是我们小组成员结对编程时候的照片:

  第三部分:实验总结

         本章主要学习内容为掌握GUI布局管理器用法,掌握各类Java Swing组件用途及常用API。本章作业内容较多所以整个完成的过程同样也不是很容易, 在学习过程中,自己对理论知识的学习学的比较混乱,另外,对于本周的实验,实验都有很多相同和类似的地方,在实验过程中任然没有理解的太清楚。在查了课本上的内容之后,稍微有了掌握。在设计方面,我还存在很大的困难,起初没有思路,但通过我们自己小组成员的讨论,还有就是借鉴,最终写出来了。总之,这次的的作业完成的很好。

        

猜你喜欢

转载自www.cnblogs.com/wing2438/p/11956862.html
今日推荐