201871010119-帖佼佼《面向对象程序设计(java)》第十四周学习总结

博文正文开头格式:(2分)

项目

内容

这个作业属于哪个课程

 https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

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

作业学习目标

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

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

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

随笔博文正文内容包括:

第一部分:总结第十二章本周理论知识(25分)

1.布局管理器

(1)为了设计美观合理的GUI界面,需要考虑组件在容器组件中的位置和相互关系,就需要学习布局设计的知识。

(2)在java的GUI应用程序界面设计中,布局控制通过为容器设置布局管理器来实现的。

  按钮放置在一个JPanel对象中,组件放在容器中,布局管理器决定容器中的组件具体放置的位置和大小;

  边框布局会扩展所有·边框布局管理器是每个JFrame内容窗格的默认布局管理器;边框组件的厚度不会随窗口大小改变而改变;

  网格布局:每个单元大小都是一样的,缩放窗口,计算器按钮随之变大或变小,但所有按钮尺寸保持一致;

  构造器:panel.steLayout(new GridLayout(5,4)); ;void pack() 缩放窗口

5种布局管理器

(1)FlowLayout: 流布局(Applet和Panel的默认布局管理器):从左到右,从上到下逐行摆放。

(2)BorderLayout:边框布局( Window、Frame和Dialog的默认布局管理器):分上下左右中五个方位

(3)GridLayout: 网格布局

(4)GridBagLayout: 网格组布局:容许组件扩展到多行、多列。

(5)CardLayout :卡片布局:把组件象一系列卡片一样叠放,一个时刻只能看到最上面的。

通过setLayout( )方法为容器设置新的布局。格式 :容器组件名.setLayout( 布局类对象名)。

a.FlowLayout (流布局管理器)

– FlowLayout( ):生成一个默认的流式布局对象

– FlowLayout(int align): 设定每一行组件的对齐方式(FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT)

– FlowLayout(int align,int hgap,int vgap):可以设定组件间的水平和垂直距离(缺省时组件之间没有空隙)

b.边框布局管理器是每个JFrame的内容窗格的默认布局管理器

  向容器中加入组件时,若使用两个参数的add()方法,第二个参数必须说明加入组件在容器中的放置位置;

  位置参数是BorderLayout 类的常量:CENTER、NORTH、SOUTH、EAST、 WEST.

c.网格布局按行列排列所有的组件;在网格布局对象的构造器中,需要指定行数和列数:panel.setLayout(new GridLayout(6,10));

  放置组件的每个单元具有相同的尺寸。
  添加组件,从第一行和第一列开始,然后是第一行的第二列。以此类推
d.
GridLayout的构造函数如下:

(1)GridLayout():生成一个单行单列的网格布局
(2)GridLayout(int rows,int cols):生成一个设定行数和列数的网格布局
(3)GridLayout(int rows,int columns,int hgap,int vgap):可以设置组件之间的水平和垂直间隔。

布局管理器应用总结:

   FlowLayout是 Applet 和面板的缺省布局管理器。组件从左上角到右下角进行排列。

  BorderLayout 按北、南、东、西、中的不同区域划分将组件排列于容器中。

  GridLayout 将组件按行和列排列。所有组件大小相同。
  GridBagLayout 能将组件放置在最精确的位置。各组件的大小可以不同

2.文本域(JTextField) : 用于获取单行文本输入。
   用于文本输入的组件继承于JTextComponent抽象类

  文本域和文本区组件用于获取文本输入;  

(1)文本域(JTextField)只能进行单行文本输入; 

(2)文本区(JTextArea)能进行多行文本输入;  

(3)JPassword也只能单行文本输入,但不会显示内容;

  三个类均继承于抽象类JTextComponent类,子类获取(get)、设置(set)文本的方法由超类JTextComponent提供;

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

3.文本域

  把文本域添加到窗口:将文本域添加到面板或其他容器中, ·任意时候可以构造文本域使用setText方法,从JTextComponent中继承;

4.标签

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

  可以用标签标识组件:构造一个JLabel组件将;

  JLabel的构造器允许指定初始文本和图标,也可以选择内容的排列方式;可以用SwingConstants接口中的常量来指定排列方式;

5、标签的常用用途之一就是标识组件.

6.密码域:

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

7.滚动窗格

  将文本区插入到滚动窗格中 textArea=new JTextArea(8,40); JScrollPane scrollPane=new JScrollPane(textArea);  如果文本超过文本区,则滚动条将会自动的出现;

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

8.复选框:指定文本标签:bold = new JCheckBox("Bold");选定或取消复选框:bold.setSelected(true);;方法isSelected返回每个复选框的状态;

  复选框构造器

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

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

3.JCheckBox(String label,boolean state);用指定的标签和初始化选

9:为单选按钮组构建一个ButtonGroup的对象,将JRadioButton类对象添加到按钮中,在新按钮被按下时,取消前一个被按下的按钮;

  单选按钮的构造器:
1.JRadioButton(String label,Icon icon);创建一个带标签和图标的单选按钮
2.JRadioButton(String label,boolean state);用指定的标签和初始化状态构造单选按钮

组合框:

  文本域和预定的选项组合起来;JCmboBox类提供了组合框的组件;setEditable方法可让组合框成为可编辑状态;getselectedItem方法获取当前的选项或被编辑的文本;方法addItem增加选项;
10.菜单

  菜单是GUI编程中经常用到的一种组件。位于窗口顶部的菜单栏(menu bar)中包括下拉菜单的名字。点击一个名字就可以打开包含菜单项(menuitems)和子菜单(submenus)的菜单.

11.单选按钮菜单项与普通单选按钮的工作方式一样,必须将它们加入的按钮组中。当按钮组中的一个按钮被选中时,其它按钮就自动变为选择项。

12.弹出菜单:创建一个弹出菜单与创建一个常规菜单的方法类似 ,但是弹出菜单没有标题。

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

第二部分:实验部分

实验1:测试程序1(5分)

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

掌握布局管理器的用法;

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

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

实验代码如下:

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();    //创建一个CalculatorFrame类对象
         frame.setTitle("Calculator");      //调用setTitle方法设置框架标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //调用setDefaultCloseOperation方法设置取消按钮
         frame.setVisible(true);//调用setVisible方法设置组件可见。
      });
   }
}

  

package calculator;
import javax.swing.*;

/**
 * A frame with a calculator panel.
 */
public class CalculatorFrame extends JFrame    //CalculatorFrame类继承JFrame类
{
   public CalculatorFrame()    //CalculatorFrame构造器
   {
      add(new CalculatorPanel());   //add方法添加新建的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    //CalculatorPanel类继承JPanel类
{
   private JButton display;     //私有成员域的定义
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;

   public CalculatorPanel()    //CalculatorPanel构造器
   {
      setLayout(new BorderLayout());    //setLayout方法为容器设置布局管理器,将布局管理器类对象设置为边框布局管理器

      result = 0;	//初始化私有成员域的变量
      lastCommand = "=";
      start = true;

      // add the display

      display = new JButton("0");  //创建一个 JButton类对象
      display.setEnabled(false);  //调用setEnabled方法,值为false,说明按钮不可选择,
      add(display, BorderLayout.NORTH);
      //调用add方法,向display容器中加入组件,BorderLayout.NORTH说明了组件添加在容器中的位置,NORTH
      InsertAction insert = new InsertAction();     //创建一个InsertAction类对象insert
      CommandAction command = new CommandAction();  //创建一个CommandAction类对象command

      // add the buttons in a 4 x 4 grid

      panel = new JPanel();     
      panel.setLayout(new GridLayout(4, 4));    //调用setLayout方法设置面板的布局管理器为4行4 列的网格布局管理器

      addButton("7", insert);   //调用addButton方法将带有7的标签插入
      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);
      //调用add方法,向panel容器中加入组件,BorderLayout.center说明了组件添加在容器中的位置居中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)    
   //addButton方法,入口参数为label以及ActionListener动作监听器对象listener
   {
      JButton button = new JButton(label);   //创建一个JButton类对象,参数为标签值的标签
      button.addActionListener(listener);   //调用addActionListener方法
      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)    //actionPerformed方法,ActionEvent event事件对象的入口参数
      {
         String input = event.getActionCommand();   //调用getActionCommand方法
         if (start)
         {
            display.setText("");//调用setText方法设置文本组件中的文本
            start = false;	//不计算
         }
         display.setText(display.getText() + input);//调用getText方法获取文本组件的文本
      }
   }

   /**
    * 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);    //setText方法设置文本组件中的文本为command命令值,即“-”号
               start = false; //不运行
            }
            else lastCommand = command;
         }
         else
         {
            calculate(Double.parseDouble(display.getText()));//调用parseDouble方法将获取的文本组件的文本为数字,把字符串转换成数字
            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)     //calculate方法
   {
      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);    
   }
}

  运行结果如下:

                        

上述运行结果计算了 7 + 99 = 106 这个式子;

实验1:测试程序2(5分)

在elipse IDE中调试运行教材486页程序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(() -> {    //lambda表达式
         TextComponentFrame frame = new TextComponentFrame();  //创建一个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;   //常量的定义,8行20列
   public static final int TEXTAREA_COLUMNS = 20;

   public TextComponentFrame()    //TextComponentFrame构造器
   {
      JTextField textField = new JTextField();     //创建JTextField文本域类对象对象
      JPasswordField passwordField = new JPasswordField();  //创建JPasswordField密码域类对象

      JPanel northPanel = new JPanel();     //创建一个JPanel类对象
      northPanel.setLayout(new GridLayout(2, 2));   //调用setLayout方法设置面板的布局为2行2列的网格布局管理器
      northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
      //新建一个JLabel标签User name,在最右边,调用add方法添加到northPanel上
      northPanel.add(textField); //调用add方法添加文本域
      northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
    //新建一个JLabel标签Password,在最右边,调用add方法添加到northPanel上
      northPanel.add(passwordField); //添加密码域文本

      add(northPanel, BorderLayout.NORTH);//添加northPanel面板到边框布局管理器的north位置

      JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
      //创建一个新的TEXTAREA_ROWS行, TEXTAREA_COLUMNS列文本域
      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");
      //创建一个JButton类对象,Insert按钮
      southPanel.add(insertButton);   //在southPanel上添加insertButton,即将Insert按钮添加到southPanel上
      insertButton.addActionListener(event ->
         textArea.append("User name: " + textField.getText() + " Password: "
            + new String(passwordField.getPassword()) + "\n"));
      //调用addActionListener方法添加动作监听器类对象,append方法将给定的文本追加到文本区中已有文本的尾部
      add(southPanel, BorderLayout.SOUTH);//添加southPanel面板到边框布局管理器的SOUTH位置
      pack();//调整窗口的大小,考虑组建的首选大小
   }
}

  运行结果如下:

实验1:测试程序3(5分)

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

掌握复选框组件的用法;

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

实验代码如下:

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

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      //新建一个JLabel对象,The quick brown fox jumps over the lazy dog.标签
      label.setFont(new Font("Serif", Font.BOLD, FONTSIZE));
      //调用setFont方法
      add(label, BorderLayout.CENTER);//将label添加到边框布局管理器的中间位置

      // 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;
         //如果bold是可选择的,字体会加粗
         if (italic.isSelected()) mode += Font.ITALIC;
         //如果italic是可选择的,字体会边倾斜
         label.setFont(new Font("Serif", mode, FONTSIZE));//设置字体,衬线以及字体的大小
      };

      // add the check boxes
      //添加到复选框
      JPanel buttonPanel = new JPanel();

      bold = new JCheckBox("Bold"); //创建一个JCheckBox对象,
      bold.addActionListener(listener);//添加事件监听器对象
      bold.setSelected(true);//调用setSelected方法表示可选择
      buttonPanel.add(bold); //将bold添加到buttonPanel上

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

      add(buttonPanel, BorderLayout.SOUTH);   //将buttonPanel添加到边框布局管理器的SOUTH位置
      pack();//调整窗口的大小,考虑组件的首选大小
   }
}

  

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(() -> {    //lambda表达式
         CheckBoxFrame frame = new CheckBoxFrame();  //创建一个CheckBoxFrame类对象
         frame.setTitle("CheckBoxTest");   //设置框架的标题为CheckBoxTest
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//调用setDefaultCloseOperation方法设置窗口是否可见
         frame.setVisible(true);//调用setVisible方法设置组件是否可见
      });
   }
}

  运行结果如下:

    

实验总结:

在选中不同的复选框Bold和italic时,The quick brown fox jumps over the lazy dog.这句话的字体会发生相应的变化,如果选中Bold这个框时,它的字体是不倾斜的,但是去掉后,选了italic之后,它的字体会变得倾斜,同时选中之后,会加粗并且倾斜。

实验1:测试程序4(5分)

在elipse IDE中调试运行教材491页程序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(() -> {   //lambda表达式
         RadioButtonFrame frame = new RadioButtonFrame();  //创建一个RadioButtonFrame(单选按钮框架)对象
         frame.setTitle("RadioButtonTest");    //调用setTitle方法设置框架的标题为RadioButtonTest
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //调用setDefaultCloseOperation方法设置窗口是否可见
         frame.setVisible(true);    //调用setVisible方法设置组件是否可见
      });
   }
}

  

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

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      //创建一个带有“The quick brown fox jumps over the lazy dog.”字符串的JLabel对象
      label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));//调用setFont方法设置字体的状态,字形大小,默认
      add(label, BorderLayout.CENTER);
      //将面板添加到边框布局管理器的居中位置
      // add the radio buttons

      buttonPanel = new JPanel();
      group = new ButtonGroup();
      
      addRadioButton("Small", 8);     //调用addRadioButton方法将带有"Small"字符串标签添加到单选按钮组当中,字体设置为8号
      addRadioButton("Medium", 12);   //调用addRadioButton方法将带有"Medium"字符串标签添加到单选按钮组当中,字体设置为12号
      addRadioButton("Large", 18);    //调用addRadioButton方法将带有"Large"字符串标签添加到单选按钮组当中,字体设置为18号
      addRadioButton("Extra large", 36); //调用addRadioButton方法将带有"Extra large"字符串标签添加到单选按钮组当中,字体设置为36号

      add(buttonPanel, BorderLayout.SOUTH);//将buttonPanel添加到边框布局管理器的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)  //addRadioButton方法
   {
      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));
      //动作监听器对象,调用setFont方法设置字体的字形大小
      button.addActionListener(listener);
   }  //将动作监听器对象添加到按钮
}

  运行结果如下:

实验1:测试程序5(5分)

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

掌握边框的用法;

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

实验代码如下:

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() // BorderFrame构造器
	{
		demoPanel = new JPanel(); // 创建两个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);   //调用setBorder方法设置标题字符串的边框

		setLayout(new GridLayout(2, 1));     //设置布局管理器为2行1列的网格布局
		add(buttonPanel);   //添加按面板buttonPanel
		add(demoPanel);   //添加面板demoPanel
		pack();  //调整窗口的大小,考虑组件首选大小
	}

	public void addRadioButton(String buttonName, Border b) // addRadioButton方法来添加单选按钮
	{
		JRadioButton button = new JRadioButton(buttonName); // 创建一个JRadioButton对象
		button.addActionListener(event -> demoPanel.setBorder(b));
		// addActionListener动作监听器,调用setBorder方法来设置这个组件的边框
		group.add(button);  //将按钮添加到按钮组当中
		buttonPanel.add(button);   //在添加到面板当中
	}
}

  

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(() -> {  //lambda表达式
         BorderFrame frame = new BorderFrame();   //创建一个BorderFrame对象
         frame.setTitle("BorderTest");   //调用setTitle方法设置框架的标题为BorderTest
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //调用setDefaultCloseOperation方法设置窗口是否可见
         frame.setVisible(true);  //调用setVisible方法设置组件是否可见
      });
   }
}

  运行结果如下:

            

    

    

实验1:测试程序6(5分)

在elipse IDE中调试运行教材498页程序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(() -> {    //lambda表达式
         ComboBoxFrame frame = new ComboBoxFrame();
         frame.setTitle("ComboBoxTest");   //调用setTitle方法设置框架的标题为ComboBoxTest
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //调用setDefaultCloseOperation方法设置窗口是否可见
         frame.setVisible(true);   //调用setVisible方法设置组件是否可见
      }); 
   }
}

  

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<String>是泛型类,包含String类型的对象
   private JLabel label;
   private static final int DEFAULT_SIZE = 24;  //常量的定义

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

      label = new JLabel("The quick brown fox jumps over the lazy dog.");
      //创建一个JLabel对象,标签内容为The quick brown fox jumps over the lazy dog.
      label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
      //调用setFont方法设置标题的字体,字形大小为默认
      add(label, BorderLayout.CENTER);
      //将label添加到边框布局管理器的居中位置
      // make a combo box and add face names
      
      faceCombo = new JComboBox<>();    //新建一个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)));   //调用getSelectedIndexd方法获得当前的选项,不是可编辑的

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

      JPanel comboPanel = new JPanel();
      comboPanel.add(faceCombo);	//添加组合框到面板
      add(comboPanel, BorderLayout.SOUTH);   //将面板添加到边框布局管理器的SOUTH位置
      pack();  //调整窗口的大小,考虑组件的首选大小
   }
}

  运行结果如下:

        

            

实验2:结对编程练习包含以下4部分:(30分)

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

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

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

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

      

1)   程序设计思路简述;

2)   符合编程规范的程序代码;

3)   程序运行功能界面截图;

4)   结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。

实验代码如下:

 

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;

public class WinCenter {
    public static void center(Window win){
        Toolkit tkit = Toolkit.getDefaultToolkit();
        Dimension sSize = tkit.getScreenSize();
        Dimension wSize = win.getSize();
        if(wSize.height > sSize.height){
            wSize.height = sSize.height;
        }
        if(wSize.width > sSize.width){
            wSize.width = sSize.width;
        }
        win.setLocation((sSize.width - wSize.width)/ 2, (sSize.height - wSize.height)/ 2);
    }
}

  

import java.awt.EventQueue;

import javax.swing.JFrame;

public class Mian
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
          DemoJFrame page = new DemoJFrame();
        
          page.setTitle("UserGUITest");// 设置标题
          page.setSize(800, 400);// 设置窗口大小
          page.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭操作
          page.setVisible(true);//设置可见性
      });
   }
}

  

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
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;

public class DemoJFrame extends JFrame {
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JPanel jPanel3;
    private JPanel jPanel4;
    private JTextField fieldname;
    private JComboBox comboBox;
    private JTextField fieldadress;
    private ButtonGroup bg;
    private JRadioButton man;
    private JRadioButton woman;
    private JCheckBox sing;
    private JCheckBox dance;
    private JCheckBox reading;

    public DemoJFrame() {
        //设置窗口居中
        WinCenter.center(this);
        jPanel1 = new JPanel();
        setJPanel1(jPanel1);
        jPanel2 = new JPanel();
        setJPanel2(jPanel2);
        jPanel3 = new JPanel();
        setJPanel3(jPanel3);
        jPanel4 = new JPanel();
        setJPanel4(jPanel4);
        // 设置容器的为流布局
        FlowLayout flowLayout = new FlowLayout();
        this.setLayout(flowLayout);
        // 将四个面板添加到容器中
        this.add(jPanel1);
        this.add(jPanel2);
        this.add(jPanel3);
        this.add(jPanel4);

    }

 //设置面板1
    private void setJPanel1(JPanel jPanel) {
        
        // 给面板的布局设置为网格布局 一行4列
        jPanel.setLayout(new GridLayout(1,4));
        JLabel name = new JLabel("姓名:");
        jPanel.setPreferredSize(new Dimension(260, 45));
        name.setSize(260, 45);
        fieldname = new JTextField("");
        fieldname.setSize(80, 20);      
        jPanel.add(name);
        jPanel.add(fieldname);

    }

  //地址爱好添加
    private void setJPanel2(JPanel jPanel) {
        jPanel.setPreferredSize(new Dimension(300, 45));
        // 给面板的布局设置为网格布局 一行4列
        jPanel.setLayout(new GridLayout(1, 4));
        JLabel name = new JLabel("地址:");
        fieldadress = new JTextField();
        fieldadress.setPreferredSize(new Dimension(300, 45));
        //FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);
        JLabel study = new JLabel("爱好:");
        JPanel selectBox = new JPanel();
        selectBox.setBorder(BorderFactory.createTitledBorder(""));
        selectBox.setLayout(new GridLayout(3, 1));
        sing = new JCheckBox("唱歌");
        dance = new JCheckBox("跳舞");
        reading = new JCheckBox("阅读");
        selectBox.add(sing);
        selectBox.add(dance);
        selectBox.add(reading);
        jPanel.add(name);
        jPanel.add(fieldadress);
        jPanel.add(study);
        jPanel.add(selectBox);
    }
//性别按钮的添加
    private void setJPanel3(JPanel jPanel) {
        jPanel.setPreferredSize(new Dimension(700, 150));
        FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
        jPanel.setLayout(flowLayout);
        JLabel sex = new JLabel("性别:");
        JPanel selectBox = new JPanel();
        selectBox.setBorder(BorderFactory.createTitledBorder(""));
        selectBox.setLayout(new GridLayout(2, 1));
        bg = new ButtonGroup();
        man = new JRadioButton("男");
        woman = new JRadioButton("女");
        bg.add(man);
        bg.add(woman);
        selectBox.add(man);
        selectBox.add(woman);
        jPanel.add(sex);
        jPanel.add(selectBox);

    }
//
    private void setJPanel4(JPanel jPanel) {
        // TODO 自动生成的方法存根
    	JTextArea textArea = new JTextArea(3, 20);
	    JScrollPane scrollPane = new JScrollPane(textArea);
	    add(scrollPane, BorderLayout.SOUTH);
        jPanel.setPreferredSize(new Dimension(700, 150));
        FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10);
        jPanel.setLayout(flowLayout);
        jPanel.setLayout(flowLayout);
        JButton sublite = new JButton("提交");
        JButton reset = new JButton("重置");
        sublite.addActionListener((e) -> 
        textArea.append("姓名 " + fieldname.getText()  + "\n"+ "地址" + fieldadress.getText() + 
           	 "\n"));
        reset.addActionListener((e) -> Reset());
        jPanel.add(sublite);
        jPanel.add(reset);
    }

//重置方法
        private void Reset() {
        // TODO 自动生成的方法存根
        fieldadress.setText(null);
        fieldname.setText(null);
        comboBox.setSelectedIndex(0);
        sing.setSelected(false);
        dance.setSelected(false);
        reading.setSelected(false);
        bg.clearSelection();
    }
}

  运行结果如下:

           

 

实验总结:(10分)

   这周主要学习了事件处理以及Swing用户界面组件,理论知识理解的还可以,在前面的几个验证性的实验中,对代码的理解觉得对这章知识掌握的还可以,但是在结对编程的环节当中,确实存在很大的问题,试了很多次,就是改不到老师要求的那种排版,外观丑陋,而且单选按钮以及复选框的信息我无法显示出来,还有就是那个录入信息输出框不在准确的位置。我会在改的。

猜你喜欢

转载自www.cnblogs.com/-8tjj/p/11959016.html