201871010104- 첸 유아 니안 주 학습 요약은 "객체 지향 프로그래밍 (자바)"

                                                            201871010104- 첸 유아 니안 주 학습 요약은 "객체 지향 프로그래밍 (자바)"

계획 함유량
이 작품은 과정 속 https://www.cnblogs.com/nwnu-daizh/
어디 작업이 필요 https://www.cnblogs.com/lily-2018/p/11441372.html
작업 학습 목표

(1)은 GUI 레이아웃 매니저 사용법을 마스터;

(2) 마스터 자바 스윙 텍스트 입력 구성 요소 및 공용 API를;

(3) 선택 입력 자바 스윙 구성 요소와 일반적으로 사용되는 API를 제어;

부 : 이론적 지식의 요약

A, 스윙 및 MVC 디자인 패턴

1. MVC 모델은 자바 GUI 구성 요소의 설계에 적용 할 수 있습니다

유일한 모드 2.MVC 모드 GUI 구성 요소 디자인, 다양한 디자인 패턴이있다

둘째, 레이아웃 매니저

1. 레이아웃 관리자 클래스의 집합이다.

- 구현 java.awt.LayoutManager의 인터페이스

- 어셈블리 컨테이너의 위치 및 크기를 판정한다

2. 각 컨테이너는 기본 레이아웃 매니저와 관련있다.

3. (1) FlowLayout의 : 플로우 레이아웃 (애플릿 패널 및 기본 레이아웃 매니저)

        라인 디스플레이로 오른쪽 위에서 아래로, 라인 왼쪽에서 구성 요소를 사용하여

        setLayout의 (신규 FlowLayout의 (INT 정렬, INT hgap에, INT의 vgap에))

(2)의 BorderLayout : 보더 레이아웃 (창, 프레임 및 대화의 기본 레이아웃 매니저)

(3) GridLayout과 : 그리드 레이아웃

1 GridLayout과 () : 하나의 별도의 그리드 레이아웃을 생성

2 GridLayout과 (INT 행, INT는 COLS) 격자의 행 및 열 일련 번호를 생성 레이아웃

3 GridLayout과 (INT 행, 열 INT, INT hgap에, INT vgap에) 수평 및 수직 간격은 구성 요소 사이에 제공 될 수있다

(4)의 GridBagLayout : 그리드 레이아웃 그룹

           그것은 조립 행의 복수, 복수 열로 확장 할 수 있도록 조립 일관된 크기를 필요로하지 않습니다.

(5) CardLayout : 카드 레이아웃

       용기 setLayout의 () 메소드에 의해 제공된 새로운 레이아웃.

       컨테이너는 조립 .setLayout (클래스 레이아웃 객체 이름)의 이름을 지정합니다.

새로운 학습 내용 :

셋째, 텍스트 입력

텍스트 필드 (JTextField를) 한 줄의 텍스트 입력을 얻기위한.

사용  텍스트 필드 : JPanelpanel = 새로운 JPanel의 ();

JTextFieldtextField 새로운 JTextField를 ( "기본 입력"(20)) =;

panel.add (에 textField) - 첫 번째 매개 변수 "기본 입력"

텍스트 필드 표시 기본값 기본 입력 - 두번째 파라미터 20 : 표시 텍스트 필드 (20 개)는 컬럼의 폭을 나타낸다.

-로는 열 수를-다시 설정, 당신은 setColumns 방법을 사용할 수 있습니다.

 (5) 상기 선택 성분

텍스트 레이블 구성 요소를 받기. 이들의 임의의 변형 (예를 들어, 경계가없는)없이,도 사용자 입력에 응답한다. 

1.bold = JCheckBox에 새로운 ( "굵은")를, 라벨을 나타내는 영역 자동 체크 박스.

2. JCheckBox에 (문자열 레이블, 아이콘 아이콘) 레이블과 아이콘 상자 구성은 초기 기본값은 선택되어 있지 않습니다.

3.JCheckBox (문자열 라벨 부울 상태), 체크 박스에 지정된 라벨 구성되고 선택 상태 초기화.

파트 II : 실험 부분

실험 1 :  제 12 장 샘플 프로그램, 시험 절차 및 그룹의 논의를 소개합니다.

시험 절차 (1)

1) 프로그램 자료 479 12-1 elipse의 IDE 바인딩 인식 프로그램의 실행 결과를 실행;

2) 레이아웃 관리자를 사용 마스터;

3) GUI 인터페이스 이벤트 처리 기술의 목적을 이해합니다.

4) 코드 레이아웃 관리 응용 프로그램에 주석을 추가;

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);//设置可见性
      });
   }
}
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

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

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表达式
         var 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()//构造器
   {
      var textField = new JTextField();
      var passwordField = new JPasswordField();

      var 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);//显示在窗口的上方

      var textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
      var scrollPane = new JScrollPane(textArea);

      add(scrollPane, BorderLayout.CENTER);//显示在窗口中心

   // 添加按钮,将文本追加到文本区域
      var southPanel = new JPanel();

      var insertButton = new JButton("Insert");//定义Button按钮:insert
      southPanel.add(insertButton);//添加insert按钮
      insertButton.addActionListener(event ->
         textArea.append("User name: " + textField.getText() + " Password: "
            + new String(passwordField.getPassword()) + "\n"));

      add(southPanel, BorderLayout.SOUTH);//显示在窗口下方
      pack();
   }
}

运行结果:

 

 

 存在的问题:如果在文本框中输入的密码过长,就显示不了,只能通过放大窗口来显示。

测试程序3

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

2)掌握复选框组件的用法;

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

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

    //添加复选框

      var 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

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

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

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

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(() -> {
         var 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()//构造器
   {      
	// 给标签加上文本

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

   /**
    * 添加一个单选按钮,用于设置示例文本的字体大小.
    * @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;
      var 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

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

2)掌握边框的用法;

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

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)
   {
      var button = new JRadioButton(buttonName);
      button.addActionListener(event -> demoPanel.setBorder(b));
      group.add(button);
      buttonPanel.add(button);
   }
}

运行结果:

测试程序6

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

2) 掌握组合框组件的用法;

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

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

  

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()//构造器
   {
      //加上标签文本

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

      // 制作组合框并加上名字

      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

      var 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 十四周结对编程 
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new FrameTest();
         frame.setTitle("陈园园");
         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);
       }
   }   
}

运行结果:

 

 结对编程照片:

实验总结: 

     通过本次的学习,了解了各种组件的制作,在理论课上,老师的讲解之下对程序以及各个概念的了解。如:复选框,单选框,边框和组合框,还有关于文本输入的文本域,标签和标签组件,密码域等。除了个别程序看不懂之外,其它都可以理解。还有就是在实验课上,学长讲解的关于上节课没有掌握完全的知识,与lambda表达式的类似的另外三种编程写法。本节课的学习,感觉很有意思也很充实,以后也会继续努力。结对编程方面,就是将这节课所学的代码进行了一个综合,创建一个新的GUI界面。

 

 

 

 

 

  

 

  

  

 

 

 

 

 

추천

출처www.cnblogs.com/chanyeol1127/p/11956927.html