201871010106-丁宣元 《面向对象程序设计(java)》第十四周学习总结

              201871010106-丁宣元 《面向对象程序设计(java)》第十四周学习总结

正文开头:

项目

内容

这个作业属于哪个课程

https://home.cnblogs.com/u/nwnu-daizh/

这个作业的要求在哪里

https://www.cnblogs.com/nwnu-daizh/p/11953993.html 

作业学习目标

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

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

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

正文内容:

第一部分:总结第十二章理论知识

                    第十二章    Swing用户界面组件

  

 12.1 Swing和模型-视图-控制器设计模式

 1.设计模式:是一种方法。

  每个模式描述了一个不断重复发生的设计问题,以及该问题的核心解决方案

 2.模型-视图-控制器设计模式

  a.组件的三个要素:内容,外观,行为

  b.模式的三个独立的类:

    模型:存储内容model

    视图:显示内容view

    控制器:处理用户输入的内容controller

    模型必须实现改变内容和查找内容

  c.模型-视图-控制器分析

      JButton是一个继承了JComponent的包装器类,JComponent包含了一个DefaultButtonModel对象,一些视图数据和一个负责按钮试图的BasicButtonUI对象。

    12-2 布局管理概述

  1.布局管理器是一组类。共5个,每一种布局管理类对应一种布局策略。

    实现 java.awt.LayoutManager 接口

  2.5种布局管理器:(1)FlowLayout:流布局(Applet和Panel的默认布局管理器

          (2)BorderLayout:边框布局( Window、Frame和Dialog的默认布局管理器,自动扩展组件大小)

          (3)GridLayout:网格布局

          (4)GridBagLayout: 网格组布局

          (5)CardLayout :卡片布局

    注:容器组件名.setLayout(布局类对象名)

      每个容器都有一个默认的布局管理器,但可以重新设置

            eg:panel.setLayout(new GridLayout(4,4));网格布局

      Component的类层次结构

        

 

 

       FlowLayout: 组件采用从左到右,从上到下逐行摆放

         API:FlowLayout( );

           FlowLayout( int  aligh );

          FlowLayOut(int aligh,int hgap,int vgap);hgap水平间距,vgap垂直间距

       BorderLayout:边界布局将容器划分为五个区域:东、南、西、北,中;      

           BorderLayout( );

          BorderLayout(int hgap ,int vgap);

          GridLayout: 给定行数 和列数的网格布局

           GridLayout(int rows,int columns,int hgap,int vgap);

12-3文本输入:

 1. 文本域(JTextField)

      获取单行文本输入

      eg:JPanel panel = new JPanel();

        JTextField textField = new JTextField("Default input", 20);

        panel.add(textField);

      API:String getText() ; 

        void setText(String text) :获取或设置文本组件中的文本 

         boolean isEditable() ;是否可编辑

         void setEditable(boolean b) 获取或设置editable特性,这个特性决定了用户是否可以编辑文本组件中的内容。

 2 .文本区(JTextArea)

  用户可输入多行文本。可以指定文本区的行数和列

  如果文本区的文本超出显示范围,多余的文本会被剪裁

  API:JTextArea(int rows, int cols) 构造一个rows行cols列的文本区对象

    JTextArea(String text,int rows, int cols) 用初始文本构造一个文本区对象

    void setRows(int rows) 设置文本域使用的行数

     void append(String newText) 将给定文本附加到文本区中已有文本之后

3.标签和标签组件

  标签是容纳文本的组件。可以利用标签标识组件

  步骤:用相应的文本构造一个JLable组件

     放在需要标识的组件的最近位置

  API:JLable(String text)  

    JLable(Icon icon)    图标

    JLable(String text,int align)

    JLable(String text,Icon icon,int align)

    String getText()  

     void setText(String text) 获取或设置标签的文本

4.密码域

  一种特殊类型的文本域。每个输入的字符都用回显字符实现   eg:*

    API:JPasswordField():空的密码文本框。

    JPasswordField(String text):创建指定初始文本信息的密码文本框。

    JPasswordField(String text,int columns):创建指定文本和列数的密码文本框。

    JPasswordField(int columns):创建指定列数的密码文本框。

   5.滚动窗格:

        需要滚动条,将文本区加入到滚动窗格中

  12-4选择组件

  1. 复选框

    想要接收的输入是“是”或“非”,就可以使用复选框组件。用户通过单击某个复选框来选择相应的选项,再点击则取消选择

  2.单选按钮

    只选择几个选项中的一个。

    构造器:

      JRadioButton(String label,Icon icon); 创建一个带标签和图标的单选按钮

      JRadioButton(String label,boolean state);

    3.边框

  如果在一个窗口中有多组复选框或单选按钮,需要可视化的形式指明哪些按钮属于同一组。

  Swing提供了一 组很有用的边框 ( borders)。

  创建:BorderFactory类的静态方法创建。

  风格有:凹斜面:BorderFactory.createLoweredBevelBorder()

       凸斜面:BorderFactory.createRaisedBevelBorder()

      蚀刻:BorderFactory.createEtchedBorder()

          4.组合框

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

      方法:faceCombo = new JComboBox();

         faceCombo.setEditable(true); 组合框可编辑

        faceCombo.addItem("Serif");

  5.  滑动条:

      可以从一组离散值中进行选择,允许进行连续值得选择。

 第二部分:实验部分

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

  测试程序1

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

       掌握布局管理器的用法;

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

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

  代码:

    Calculator.java

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(() -> {//lambda表达式
          CalculatorFrame frame = new CalculatorFrame();
         frame.setTitle("Calculator");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭
         frame.setVisible(true);//可见
      });
   }
}

  CalculatorFrame.java

package calculator;

import javax.swing.*;

/**
 * A frame with a calculator panel.
 */
public class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      add(new CalculatorPanel());
      pack();//使用所有组件的最佳大小计算框架的高度和宽度
   }
}

  CalculatorPanel.java

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;
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;

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

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

      // add the display

      display = new JButton("0");
      display.setEnabled(false);//只可视,不可点击
      add(display, BorderLayout.NORTH);

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

      // add the buttons in a 4 x 4 grid  4*4的网格

      panel = new JPanel();
      panel.setLayout(new GridLayout(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//实现InsertAction接口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//CommandAction实现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);
   }
}

   结果:

计算5*6的结果:

     测试程序2

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

  掌握文本组件的用法;

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

  代码:

    TextComponentTestjava

 

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(() -> {//lambda表达式
          TextComponentFrame frame = new TextComponentFrame();
         frame.setTitle("TextComponentTest");//标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置可关闭
         frame.setVisible(true);//设置可见
      });
   }
}

 

  TextComponentFrame.java

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//TextComponentFrame继承JFrame
{
   public static final int TEXTAREA_ROWS = 8;//8行
   public static final int TEXTAREA_COLUMNS = 20;//20列

   public TextComponentFrame()//构造器
   {
       JTextField textField = new JTextField();//构造一个空白文本域
       JPasswordField passwordField = new JPasswordField();//密码域

      JPanel northPanel = new JPanel();//面板
      northPanel.setLayout(new GridLayout(2, 2));//将面板的默认布局构造器(流布局)修改为网格布局,且网格为2*2
      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);//显示在北方

      JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);//文本区为8行20列
      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();
   }
}

  结果:

输入信息:滚动条:

   疑惑:lambda表达式还是不太理解

测试程序3

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

  掌握复选框组件的用法;

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

   代码:

  CheckBoxTest.java

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(() -> {
          CheckBoxFrame frame = new CheckBoxFrame();
         frame.setTitle("CheckBoxTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

  CheckBoxFrame.java

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()//构造器
   {
      // add the sample text label

      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 -> {//lambda表达式
         int mode = 0;
         if (bold.isSelected()) mode += Font.BOLD;
         if (italic.isSelected()) mode += Font.ITALIC;
         label.setFont(new Font("Serif", mode, FONTSIZE));
      };

      // add the check boxes

      JPanel buttonPanel = new JPanel();

      bold = new JCheckBox("Bold");
      bold.addActionListener(listener);//两个复选框实现同一个监听器
      bold.setSelected(true);//setSelected()选定或取消选定的复选框
      buttonPanel.add(bold);

      italic = new JCheckBox("Italic");
      italic.addActionListener(listener);//两个复选框实现同一个监听器
      buttonPanel.add(italic);

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

   结果:

 

  测试程序4

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

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

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

  代码:该程序用来选择字体大小

  RadioButtonTest.java

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;
   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);

      // add the radio buttons

      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);

      // this listener sets the label font size

      ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));//定义了一个动作监听器来把字体大小设为特定的值

      button.addActionListener(listener);
   }
}

  结果:

 

  测试程序5

    在elipse IDE中调试运行教材494页程序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,结合运行结果理解程序;

  掌握组合框组件的用法;

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

  代码:

  ComboBoxTest.java

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(() -> {
         var frame = new ComboBoxFrame();
         frame.setTitle("ComboBoxTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

  ComboBoxFrame.java

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;//JComboBox是一个泛型类,JComboBox<String>包含String类型的对象
   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 InputMessage;
import java.awt.EventQueue;

import javax.swing.JFrame;

public class MessageTest {
    public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             JFrame frame = new Message();
             frame.setTitle("UserGUITest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
}

 

package InputMessage;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import java.awt.EventQueue;

public class Message extends JFrame{
    public static final int TEXTAREA_ROWS=2;
    public static final int TEXTAREA_COLUMNS=15;
    public Message() {
        setSize(700,550);
        
        JPanel nPanel = new JPanel();                    
        add(nPanel,BorderLayout.NORTH);
        
        JLabel nLabel = new JLabel("姓名:",JLabel.RIGHT);
        nPanel.add(nLabel);
        JTextArea textarea = new JTextArea(TEXTAREA_ROWS,TEXTAREA_COLUMNS);
        nPanel.add(textarea);//文本区
        textarea.setLineWrap(true);
        Border etched1 = BorderFactory.createEtchedBorder();
        textarea.setBorder(etched1);
        
        JLabel adressLabel = new JLabel("地址:",JLabel.RIGHT);
        nPanel.add(adressLabel);
        JTextArea adressLabel1 = new JTextArea(TEXTAREA_ROWS,TEXTAREA_COLUMNS*2);
        nPanel.add(adressLabel1);
        Border etched21 = BorderFactory.createEtchedBorder();
        adressLabel1.setBorder(etched21);
        adressLabel1.setLineWrap(true);
        
        
        JPanel cPanel = new JPanel();
        cPanel.setLayout(new GridLayout(3,2));
        add(cPanel,BorderLayout.CENTER);
        
        JPanel Panel = new JPanel();
        cPanel.add(Panel);
        
        JPanel mPanel = new JPanel();
        mPanel.setLayout(new FlowLayout());
        cPanel.add(mPanel);
        mPanel.setSize(300,200);
        
        JPanel sexPanel = new JPanel();                                
        mPanel.add(sexPanel);
        Border etched2 = BorderFactory.createEtchedBorder();//加边框
        Border titled1 = BorderFactory.createTitledBorder(etched2,"性别");
        sexPanel.setBorder(titled1);

        JRadioButton mButton = new JRadioButton("男",false);//单选按钮
        sexPanel.add(mButton); 
        JRadioButton fButton = new JRadioButton("女",false);
        sexPanel.add(fButton);
        
        
        JPanel hPanel = new JPanel();                            
        mPanel.add(hPanel);
        Border titled2 = BorderFactory.createTitledBorder(etched2,"爱好");
        hPanel.setBorder(titled2);
        JCheckBox reading = new JCheckBox("阅读");
        hPanel.add(reading);
        JCheckBox singing = new JCheckBox("唱歌");
        hPanel.add(singing);
        JCheckBox dancing = new JCheckBox("跳舞");
        hPanel.add(dancing);
       
        
        JPanel ButtonPanel = new JPanel();
        cPanel.add(ButtonPanel);
        JButton sub = new JButton("提交");
        ButtonPanel.add(sub);
        JButton re = new JButton("重置");
        ButtonPanel.add(re);
        
        
        JTextArea southText = new JTextArea("录入信息显示区!",7,15);     
        //southText.setLineWrap(true);
        add(southText,BorderLayout.SOUTH);
        
        sub.addActionListener(event->{      //提交操作            
            String sex="";
            if(mButton.isSelected())
                sex="男";
            else
                sex="女";
            String hobby="";
            if(reading.isSelected()) 
                hobby="阅读 ";
            if(singing.isSelected()) 
                hobby="唱歌 ";
            if(dancing.isSelected()) 
                hobby="跳舞 ";
            if(southText.getText().equals("录入信息显示区!"))            
                southText.setText(" ");
            southText.append("姓名:"+textarea.getText()+"    地址:"+adressLabel1.getText()+"     性别:"+sex+"    爱好:"+hobby+"\n");
        });
        
        re.addActionListener(event->{//重置操作,全部变为空白
            southText.setText("  ");
            textarea.setText("  ");
            adressLabel1.setText("  ");
            mButton.setSelected(false);
            fButton.setSelected(false);
            reading.setSelected(false);
            singing.setSelected(false);
            dancing.setSelected(false);
        });
    }
}

 

 

  

结果:

  提交:

重置后:

 

 

 

 

 实验总结:

  通过本次实验,我掌握了:1.GUI布局管理器的用法      2.了解Java Swing文本输入组件用途及常用API

3.了解Java Swing选择输入组件用途及常用API

  结和第十一章和第十二章的内容,我进一步了解了javaCUI界面的知识,由于是可视化的内容,引起了自己的兴趣,感觉很有意思。但在理解代码上面还是存在一些不足,经老师实验课讲解有了进一步的理解。在结对编程上,存在的问题挺多。首先思路感觉正确,但在实现的时候,发现做了许多多余的工作,经修正后,使用布局管理器,减轻了工作量。在以后的练习中,首先要有明确的思路,多讨论,多请教。

 

posted @ 2019-12-02 21:40  小Q布丁  阅读(187)  评论(1编辑  收藏  举报