Java实验 实验九

实践九 java Swing概述

1、JFrame常用方法

import javax.swing.*;

import java.awt.*;

public class Example9_1 {

    public static void main(String args[]) {

        JFrame window1=new JFrame("第一个窗口");

        JFrame window2=new JFrame("第二个窗口");

        Container con=window1.getContentPane();

        con.setBackground(Color.yellow) ;       //设置窗口的背景色

        window1.setBounds(60,100,188,108);

        window2.setBounds(260,100,188,108);

        window1.setVisible(true);

        window1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        window2.setVisible(true);

        window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

运行结果:

2、菜单条、菜单、菜单项

import javax.swing.*;

 class WindowMenu extends JFrame {

    JMenuBar menubar;

    JMenu menuFruit,menuFruit2;

    JMenuItem bananaItem,pearItem;

    JMenu appleMenu;

    JMenuItem redAppleItem,yellowAppleItem;

    public WindowMenu(){}

    public WindowMenu(String s,int x,int y,int w,int h) {

       init(s);

       setLocation(x,y);

       setSize(w,h);

       setVisible(true);

       setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    }

    void init(String s){

       setTitle(s);             //设置窗口的标题   

       menubar=new JMenuBar();

       menuFruit=new JMenu("水果菜单"); //menuFruit做根菜单

       menuFruit2=new JMenu("干果菜单"); //menuFruit做根菜单

       bananaItem=new JMenuItem("香蕉");

       bananaItem.setIcon(new ImageIcon("banana.jpg"));

       pearItem=new JMenuItem("甜梨");

       pearItem.setIcon(new ImageIcon("pear.jpg"));

       appleMenu=new JMenu("苹果");

       redAppleItem = new JMenuItem("红苹果");

       redAppleItem.setIcon(new ImageIcon("redApple.jpg"));

       yellowAppleItem = new JMenuItem("黄苹果");

       yellowAppleItem.setIcon(new ImageIcon("yellowApple.png"));

       menuFruit.add(bananaItem); //菜单添加菜单项

       menuFruit.add(pearItem);   //菜单添加菜单项

       menuFruit.addSeparator();  //在菜单添加分隔线

       menuFruit.add(appleMenu);  //菜单也可以添加菜单

       appleMenu.add(redAppleItem);  //菜单添加菜单项

       appleMenu.add(yellowAppleItem);  //菜单添加菜单项

       menubar.add(menuFruit); //菜单条添加menuFruit菜单

       menubar.add(menuFruit2); //菜单条添加menuFruit菜单

       setJMenuBar(menubar);   //窗口放置菜单条

       bananaItem.addActionListener(e->{

        System.out.print("ok");

           JFrame f1=new JFrame();

           f1.setBounds(100, 100, 200, 200);

           f1.setVisible(true);

       });

    }

}

public class Example9_2 {

public static void main(String[] args) {

      WindowMenu win=new WindowMenu("带菜单的窗口",20,30,600,290);

  }

}

运行结果:

3、常用容器

  1. JPanel面板—构造方法:JPanel p=new JPanel();
  2. JTabbedPane选项卡窗格 add(String text,Component c);
  3. JScrollPane滚动窗格
  4. JLayeredPane分层窗格 add(Jcomponnent com, int layer);

import java.awt.*;

import javax.swing.*;

 class ComponentInWindow extends JFrame {

   JTextField text;

   JButton button;

   JCheckBox checkBox1,checkBox2,checkBox3;

   JRadioButton radio1,radio2;

   ButtonGroup group;

   JComboBox<String> comBox;

   JTextArea area;

   public ComponentInWindow() {

      init();

      setVisible(true);

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }

   void init() {

      setLayout(new FlowLayout());

      add(new JLabel("文本框:"));

      text=new JTextField(10);

      add(text);

      add(new JLabel("按钮:"));

      button=new JButton("确定");

      add(button);

      add(new JLabel("选择框:"));

      checkBox1 = new JCheckBox("喜欢音乐");

      checkBox2 = new JCheckBox("喜欢旅游");

      checkBox3 = new JCheckBox("喜欢篮球");  

      add(checkBox1);

      add(checkBox2);

      add(checkBox3);

      add(new JLabel("单选按钮:"));

      group = new ButtonGroup();

      radio1 = new JRadioButton("男");

      radio2 = new JRadioButton("女");

      group.add(radio1);

      group.add(radio2);

      add(radio1);

      add(radio2);

      add(new JLabel("下拉列表:"));

      comBox = new JComboBox<String>();

      comBox.addItem("音乐天地");

      comBox.addItem("武术天地");

      comBox.addItem("象棋乐园");

      add(comBox);

      add(new JLabel("文本区:"));

      area = new JTextArea(6,12);

      add(new JScrollPane(area));

   }

}

public class Example9_3 {

   public static void main(String args[]) {

      ComponentInWindow win=new ComponentInWindow();

      win.setBounds(100,100,450,260);

      win.setTitle("常用组件");

   }

}

运行结果:

去除滚动窗格://add(new JScrollPane(area));

add(area);

4、常用布局

1、FlowLayout布局,边界布局,默认布局

2、BorderLayout布局,边框包布局,默认布局

3、CardLayout布局,卡片布局

4、GridLayout布局,网格布局

5、java.swing.border包中的BoxLayout布局类

6、null布局,空布局

import java.awt.*;

import javax.swing.*;

 class PanelGridLayout extends JPanel {  

    PanelGridLayout () {

       GridLayout grid=new GridLayout(12,12);  //网格布局

       setLayout(grid);

       Label label[][]=new Label[12][12];

       for(int i=0;i<12;i++) {

         for(int j=0;j<12;j++) {

            label[i][j]=new Label();

            if((i+j)%2==0)

               label[i][j].setBackground(Color.black);

            else

               label[i][j].setBackground(Color.white);

            add(label[i][j]);

         }

       }

    }

}

 class PanelNullLayout extends JPanel {

   JButton button;

   JTextField text;

   PanelNullLayout() {

      setLayout(null);  //空布局

      button = new JButton("确定");

      text = new JTextField();

      add(text);

      add(button);

      text.setBounds(100,30,90,30);

      button.setBounds(190,30,66,30);

   }

}   

class ShowLayout extends JFrame {

PanelGridLayout pannelGrid; //网格布局的面板

PanelNullLayout panelNull ; //空布局的面板

JTabbedPane p;              //选项卡窗格

ShowLayout() {

   pannelGrid = new PanelGridLayout();

   panelNull  = new PanelNullLayout();

   p = new JTabbedPane();

   p.add("网格布局的面板",pannelGrid);

   p.add("空布局的面板",panelNull);

   add(p,BorderLayout.CENTER);

   add(new JButton("窗体是BorderLayout布局"),BorderLayout.NORTH);

   add(new JButton("南"),BorderLayout.SOUTH);

   add(new JButton("西"),BorderLayout.WEST);

   add(new JButton("东"),BorderLayout.EAST);

   setBounds(10,10,570,390);

   setVisible(true);

   setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

   validate();

}

}

public class Example9_4 {

public static void main(String[] args) {

new ShowLayout();

}

}

运行结果:

5、

import javax.swing.*;

public class WindowBoxLayout extends JFrame  {

    Box boxH;               //行式盒

    Box boxVOne,boxVTwo;    //列式盒

    public WindowBoxLayout() {

        setLayout(new java.awt.FlowLayout());

        init();

        setVisible(true);

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    }

    void init() {

        boxH =Box.createHorizontalBox();

        boxVOne=Box.createVerticalBox();

        boxVTwo=Box.createVerticalBox();

        boxVOne.add(new JLabel("姓名:"));

        boxVOne.add(new JLabel("职业:"));

        boxVTwo.add(new JTextField(10));

        boxVTwo.add(new JTextField(10));

        boxH.add(boxVOne);

        boxH.add(Box.createHorizontalStrut(10));

        boxH.add(boxVTwo);

        add(boxH);       

    }

}

public class Example9_5 {

   public static void main(String args[]) {

      WindowBoxLayout win=new WindowBoxLayout();

      win.setBounds(100,100,310,260);

      win.setTitle("嵌套盒式布局容器");

   }

}

运行结果:

6、事件处理:ActionEvent事件

import javax.swing.*;

import java.awt.event.*;

public class WindowActionEvent extends JFrame {

   JTextField text;

   ActionListener listener;             //listener是监视器

   public WindowActionEvent() {

      setLayout(new FlowLayout());    //创建流式布局FlowLayout

      text = new JTextField(10);

      add(text);

      listener = new ReaderListen();       //用ReaderListen类创建责计算字符串长度的监视器

      text.addActionListener(listener);   //向text文本框注册监视器,text是事件源,listener是监视器

      setVisible(true);

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }

}

public class ReaderListen implements ActionListener {

   public void actionPerformed(ActionEvent e) {

      String str=e.getActionCommand();   //通过e获取封装在事件中的“命令”字符串

      System.out.println(str+":"+str.length());

      System.out.println(e.getSource());              //输出事件源

   }

}

public class Example9_6 {

   public static void main(String args[]) {

      WindowActionEvent win=new WindowActionEvent();

      win.setTitle("处理ActionEvent事件");

      win.setBounds(100,100,310,260);

   }

}

运行结果:

7、输出到窗口

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionListener;

public class WindowActionEvent extends JFrame {

    JTextField text;

    JTextArea ta;

    ActionListener listener;             //listener是监视器

    public WindowActionEvent() {

        setLayout(new FlowLayout());      //创建流式布局FlowLayout

        text = new JTextField(10);

        add(text);

        ta=new JTextArea(5,10);

        add(new JScrollPane (ta));

        listener = new ReaderListen(this);       //用ReaderListen类创建责计算字符串长度的监视器

        text.addActionListener(listener);   //向text文本框注册监视器,text是事件源,listener是监视器

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class ReaderListen implements ActionListener {

    WindowActionEvent win;

    ReaderListen(WindowActionEvent win){

        this.win=win;

    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==win.text) {//事件e的事件源等于win.text

            String str=win.text.getText();   //获取文本框中文本

            win.ta.append(str+":"+str.length()+"\n");

        }

    }

}

public class Example9_6 {

    public static void main(String args[]) {

        WindowActionEvent win=new WindowActionEvent();

        win.setTitle("处理ActionEvent事件");

        win.setBounds(100,100,310,260);

    }

}

运行结果:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class WindowActionEvent extends JFrame {

    JTextField text;

    JTextArea ta;

    ActionListener listener;//listener是监视器

    JButton bt;

    public WindowActionEvent() {

        setLayout(new FlowLayout());      //创建流式布局FlowLayout

        text = new JTextField(10);

        add(text);

        bt = new JButton("确定");

        add(bt);

        ta=new JTextArea(5,10);

        add(new JScrollPane (ta));

        listener = new ReaderListen(this);       //用ReaderListen类创建责计算字符串长度的监视器

        bt.addActionListener(listener);

        text.addActionListener(listener);   //向text文本框注册监视器,text是事件源,listener是监视器

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    class ReaderListen implements ActionListener {

        WindowActionEvent win;

        ReaderListen(WindowActionEvent win){

            this.win=win;

        }

        public void actionPerformed(ActionEvent e) {

            if(e.getSource()==win.text |e.getSource()==win.bt) {//事件e的事件源等于win.text

                String str=win.text.getText();   //获取文本框中文本

                win.ta.append(str+":"+str.length()+"\n");

            }

        }

    }

}

public class Example9_6 {

    public static void main(String args[]) {

        WindowActionEvent win=new WindowActionEvent();

        win.setTitle("处理ActionEvent事件");

        win.setBounds(100,100,310,260);

    }

}

简化:内部类作为事件处理类

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class WindowActionEvent extends JFrame {

    JTextField text;

    JTextArea ta;

    ActionListener listener;//listener是监视器

    JButton bt;

    public WindowActionEvent() {

        setLayout(new FlowLayout());      //创建流式布局FlowLayout

        text = new JTextField(10);

        add(text);

        bt = new JButton("确定");

        add(bt);

        ta = new JTextArea(5, 10);

        add(new JScrollPane(ta));

        listener = new ReaderListen();       //用ReaderListen类创建责计算字符串长度的监视器

        bt.addActionListener(listener);

        text.addActionListener(listener);   //向text文本框注册监视器,text是事件源,listener是监视器

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    class ReaderListen implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == text | e.getSource() == bt) {//事件e的事件源等于win.text

                String str = text.getText();   //获取文本框中文本

                ta.append(str + ":" + str.length() + "\n");

            }

        }

    }

}

class Example9_7 {

    public static void main(String args[]) {

        WindowActionEvent win=new WindowActionEvent();

        win.setTitle("处理ActionEvent事件");

        win.setBounds(100,100,310,260);

    }

}

进一步简化:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class WindowActionEvent extends JFrame implements ActionListener{

    JTextField text;

    JTextArea ta;

    ActionListener listener;//listener是监视器

    JButton bt;

    public WindowActionEvent() {

        setLayout(new FlowLayout());      //创建流式布局FlowLayout

        text = new JTextField(10);

        add(text);

        bt = new JButton("确定");

        add(bt);

        ta = new JTextArea(5, 10);

        add(new JScrollPane(ta));

        bt.addActionListener(this);

        text.addActionListener(this);   //向text文本框注册监视器,text是事件源,listener是监视器

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

            if (e.getSource() == text | e.getSource() == bt) {//事件e的事件源等于win.text

                String str = text.getText();   //获取文本框中文本

                ta.append(str + ":" + str.length() + "\n");

            }

        }

    }

    class Example9_8 {

    public static void main(String args[]) {

        WindowActionEvent win=new WindowActionEvent();

        win.setTitle("处理ActionEvent事件");

        win.setBounds(100,100,310,260);

    }

}

设计文本框、字体等:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class WindowActionEvent extends JFrame implements ActionListener{

    JTextField text;

    JTextArea ta;

    ActionListener listener;//listener是监视器

    JButton bt;

    public WindowActionEvent() {

        setLayout(new FlowLayout());      //创建流式布局FlowLayout

        text = new JTextField(10);

        text.setBackground(Color.pink);

        text.setForeground(Color.BLUE);

        Font font=new Font("宋体",Font.BOLD|Font.ITALIC,20);

        text.setFont(font);

        add(text);

        bt = new JButton("确定");

        add(bt);

        ta = new JTextArea(7, 20);

        ta.setFont(font);

        add(new JScrollPane(ta));

        bt.addActionListener(this);

        text.addActionListener(this);   //向text文本框注册监视器,text是事件源,listener是监视器

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

            if (e.getSource() == text | e.getSource() == bt) {//事件e的事件源等于win.text

                String str = text.getText();   //获取文本框中文本

                ta.append(str + ":" + str.length() + "\n");

            }

        }

    }

    class Example9_8 {

    public static void main(String args[]) {

        WindowActionEvent win=new WindowActionEvent();

        win.setTitle("处理ActionEvent事件");

        win.setBounds(100,100,310,260);

    }

}

8、计算器:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

class NumberView extends JFrame implements ActionListener, ItemListener {

    public JTextField inputNumberOne,inputNumberTwo;

    public JComboBox<String> choiceFuhao;

    public JTextArea textShow;

    public JButton button;

    String fuhao ;

    public NumberView() {

        init();

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    void init() {

        setLayout(new FlowLayout());

        Font font = new Font("宋体",Font.BOLD,22);

        inputNumberOne = new JTextField(5);

        inputNumberTwo = new JTextField(5);

        inputNumberOne.setFont(font);

        inputNumberTwo.setFont(font);

        choiceFuhao = new JComboBox<String>();

        choiceFuhao.setFont(font);

        button = new JButton("计算");

        button.setFont(font);

        choiceFuhao.addItem("选择运算符号:");

        String [] a = {"+","-","*","/"};

        for(int i=0;i<a.length;i++) {

            choiceFuhao.addItem(a[i]);

        }

        choiceFuhao.setSelectedIndex(-1);//初始状态列表中没有选项被选中

        textShow = new JTextArea(9,30);

        textShow.setFont(font);

        choiceFuhao.addItemListener(this); //operator是监视器

        button.addActionListener(this);//computer是监视器

        add(inputNumberOne);

        add(choiceFuhao);

        add(inputNumberTwo);

        add(button);

        add(new JScrollPane(textShow));

    }

    public void itemStateChanged(ItemEvent e)  {

        fuhao =choiceFuhao.getSelectedItem().toString();

    }

    public void actionPerformed(ActionEvent e) {

        try {

            double number1 = Double.parseDouble(inputNumberOne.getText());

            double number2 = Double.parseDouble(inputNumberTwo.getText());

            double result = 0;

            boolean isShow = true;

            if(fuhao.equals("+")) {

                result = number1+number2;

            }

            else if(fuhao.eq

运行结果:

  1. 简单计算器:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

class NumberView extends JFrame implements ActionListener, ItemListener {

    public JTextField inputNumberOne,inputNumberTwo;

    public JComboBox<String> choiceFuhao;

    public JTextArea textShow;

    public JButton button;

    String fuhao ;

    public NumberView() {

        init();

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    void init() {

        setLayout(new FlowLayout());

        Font font = new Font("宋体",Font.BOLD,22);

        inputNumberOne = new JTextField(5);

        inputNumberTwo = new JTextField(5);

        inputNumberOne.setFont(font);

        inputNumberTwo.setFont(font);

        choiceFuhao = new JComboBox<String>();

        choiceFuhao.setFont(font);

        button = new JButton("计算");

        button.setFont(font);

        choiceFuhao.addItem("选择运算符号:");

        String [] a = {"+","-","*","/"};

        for(int i=0;i<a.length;i++) {

            choiceFuhao.addItem(a[i]);

        }

        choiceFuhao.setSelectedIndex(-1);//初始状态列表中没有选项被选中

        textShow = new JTextArea(9,30);

        textShow.setFont(font);

        choiceFuhao.addItemListener(this); //operator是监视器

        button.addActionListener(this);//computer是监视器

        add(inputNumberOne);

        add(choiceFuhao);

        add(inputNumberTwo);

        add(button);

        add(new JScrollPane(textShow));

}

 public void itemStateChanged(ItemEvent e)  {

        fuhao =choiceFuhao.getSelectedItem().toString();

    }

    public void actionPerformed(ActionEvent e) {

        try {

            double number1 = Double.parseDouble(inputNumberOne.getText());

            double number2 = Double.parseDouble(inputNumberTwo.getText());

            double result = 0;

            boolean isShow = true;

            if(fuhao.equals("+")) {

                result = number1+number2;

            }

            else if(fuhao.equals("-")) {

                result = number1-number2;

            }

            else if(fuhao.equals("*")) {

                result = number1*number2;

            }

            else if(fuhao.equals("/")) {

                result = number1/number2;

            }

            else isShow = false;

            if(isShow)

                textShow.append(number1+" "+fuhao+" "+number2+" = "+result+"\n");

        }

        catch(Exception exp) {

            textShow.append("\n请输入数字字符\n");

        }

    }

}

public class Example9_8 {

    public static void main(String args[]) {

        NumberView win=new NumberView();

        win.setBounds(100,100,600,360);

        win.setTitle("简单计算器");

    }

}

运行结果:

  1. 处理鼠标事件

import java.awt.*;

import java.awt.event.*;

import java.awt.event.MouseListener;

import javax.swing.*;

class WindowMouse extends JFrame implements MouseListener {

    JButton button;

    JTextArea area;

    WindowMouse() {

        init();

        setVisible(true);

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    }

    void init() {

        setLayout(new FlowLayout());

        area = new JTextArea(10,28);

        Font font = new Font("宋体",Font.PLAIN,22);

        area.setFont(font);

        button = new JButton("按钮");

        button.addMouseListener(this);

        addMouseListener(this);

        add(button);

        add(new JScrollPane(area));

    }

    public void mousePressed(MouseEvent e) {

        if(e.getSource() == button&&e.getButton() == MouseEvent.BUTTON1) {

            area.append("在按钮上按下鼠标左键:\n");

            area.append(e.getX()+","+e.getY()+"\n");

        }

        else if(e.getSource() == this&&e.getButton() == MouseEvent.BUTTON1) {

            area.append("在窗体中按下鼠标左键:\n");

            area.append(e.getX()+","+e.getY()+"\n");

        }

    }

    public void mouseReleased(MouseEvent e) {}

    public void mouseEntered(MouseEvent e)  {

        if(e.getSource() instanceof JButton)

            area.append(e.getSource()+"\n鼠标进入按纽,位置:"+e.getX()+","+e.getY()+"\n");

        if(e.getSource() instanceof JFrame)

            area.append("\n鼠标进入窗口,位置:"+e.getX()+","+e.getY()+"\n");

    }

    public void mouseExited(MouseEvent e) {}

    public void mouseClicked(MouseEvent e) {

        if(e.getClickCount()>=2)

            area.setText("鼠标连击\n");

    }

}

public class Example9_10 {

    public static void main(String args[]) {

        WindowMouse win=new WindowMouse();

        win.setTitle("处理鼠标事件");

        win.setBounds(10,10,560,380);

    }

}

运行结果:

11.带消息对话框的窗口

package P19P18后;//实验十

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class WindowMess extends JFrame implements ActionListener {

    JTextField inputEnglish;

    JTextArea show;

    String regex = "[a-zA-Z]+";

    WindowMess() {

        inputEnglish=new JTextField(22);

        inputEnglish.addActionListener(this);

        show=new JTextArea();

        add(inputEnglish, BorderLayout.NORTH);

        add(show,BorderLayout.CENTER);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==inputEnglish) {

            String str=inputEnglish.getText();

            if(str.matches(regex)) {

                show.append(str+",");

            }

            else { //弹出消息对话框。

                JOptionPane.showMessageDialog(this,"输入了非法字符","消息对话框",

                        JOptionPane.ERROR_MESSAGE);

                inputEnglish.setText(null);

            }

        }

    }

}

public class Example9_16 {

    public static void main(String args[]) {

        WindowMess win=new WindowMess();

        win.setTitle("带消息对话框的窗口");

        win.setBounds(80,90,350,300);

    }

}

运行结果:

12.带输入对话框的窗口

package P19P18后;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.InputMismatchException;

import java.util.Scanner;

class WindowInput extends JFrame implements ActionListener {

    JTextArea showResult;

    JButton openInput;

    WindowInput() {

        openInput=new JButton("弹出输入对话框");

        showResult=new JTextArea();

        Font f =new Font("宋体",Font.PLAIN,23);

        showResult.setFont(f);

        add(openInput,BorderLayout.NORTH);

        add(new JScrollPane(showResult),BorderLayout.CENTER);

        openInput.addActionListener(this);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

        String str=JOptionPane.showInputDialog

                (this,"输入数字,用空格分隔","输入对话框",JOptionPane.PLAIN_MESSAGE);

        if(str!=null) {

            Scanner scanner = new Scanner(str);

            double sum=0;

            int k=0;

            while(scanner.hasNext()){

                try{

                    double number=scanner.nextDouble();

                    if(k==0)

                        showResult.append(""+number);

                    else

                        showResult.append("+"+number);

                    sum=sum+number;

                    k++;

                }

                catch(InputMismatchException exp){

                    String t=scanner.next();

                }

            }

            showResult.append("="+sum+"\n");

        }

    }

}

public class Example9_17 {

    public static void main(String args[]) {

        WindowInput win=new WindowInput();

        win.setTitle("带输入对话框的窗口");

        win.setBounds(80,90,600,300);

    }

}

运行结果:

13.带颜色对话框的窗口

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.InputMismatchException;

import java.util.Scanner;

class WindowColor extends JFrame implements ActionListener {

    JButton button;

    WindowColor() {

        button=new JButton("打开颜色对话框");

        button.addActionListener(this);

        setLayout(new FlowLayout());

        add(button);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

        Color newColor=JColorChooser.showDialog(this,"调色板",getContentPane().getBackground());

        if(newColor!=null) {

            getContentPane().setBackground(newColor);

        }

    }

}

public class Example9_19 {

    public static void main(String args[]) {

        WindowColor win=new WindowColor();

        win.setTitle("带颜色对话框的窗口");

        win.setBounds(80,90,200,300);

    }

}

运行结果:

14.使用文件对话框读写文件

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;

class WindowReader extends JFrame implements ActionListener {

    JFileChooser fileDialog ;

    JMenuBar menubar;

    JMenu menu;

    JMenuItem itemSave,itemOpen;

    JTextArea text;

    BufferedReader in;

    FileReader fileReader;

    BufferedWriter out;

    FileWriter fileWriter;

    WindowReader() {

        init();

        setSize(300,400);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    void init() {

        text=new JTextArea(10,10);

        text.setFont(new Font("楷体_gb2312",Font.PLAIN,28));

        add(new JScrollPane(text),BorderLayout.CENTER);

        menubar=new JMenuBar();

        menu=new JMenu("文件");

        itemSave=new JMenuItem("保存文件");

        itemOpen=new JMenuItem("打开文件");

        itemSave.addActionListener(this);

        itemOpen.addActionListener(this);

        menu.add(itemSave);

        menu.add(itemOpen);

        menubar.add(menu);

        setJMenuBar(menubar);

        fileDialog=new JFileChooser();

    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==itemSave) {

            int state=fileDialog.showSaveDialog(this);

            if(state==JFileChooser.APPROVE_OPTION) {

                try{

                    File dir=fileDialog.getCurrentDirectory();

                    String name=fileDialog.getSelectedFile().getName();

                    File file=new File(dir,name);

                    fileWriter=new FileWriter(file);

                    out=new BufferedWriter(fileWriter);

                    out.write(text.getText());

                    out.close();

                    fileWriter.close();

                }

                catch(IOException exp){}

            }

        }

        else if(e.getSource()==itemOpen) {

            int state=fileDialog.showOpenDialog(this);

            if(state==JFileChooser.APPROVE_OPTION) {

                text.setText(null);

                try{

                    File dir=fileDialog.getCurrentDirectory();

                    String name=fileDialog.getSelectedFile().getName();

                    File file=new File(dir,name);

                    fileReader=new FileReader(file);

                    in=new BufferedReader(fileReader);

                    String s=null;

                    while((s=in.readLine())!=null) {

                        text.append(s+"\n");

                    }

                    in.close();

                    fileReader.close();

                }

                catch(IOException exp){}

            }

        }

    }

}

public class Example9_19_1 {

    public static void main(String args[]) {

        WindowReader win=new WindowReader();

        win.setTitle("使用文件对话框读写文件");

        win.setBounds(80,90,200,300);

    }

}

运行结果:

15.计算每个人总成绩

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

import java.awt.event.*;

public class Example9_22 {

    public static void main(String args[]) {

        WinTable Win=new WinTable();

    }

}

class WinTable extends JFrame implements ActionListener {

    JTable table;Object a[][];

    Object name[]={"姓名","英语成绩","数学成绩","总成绩"};

    JButton button;

    WinTable() {

        a=new Object[8][4];

        for(int i=0;i<8;i++) {

            for(int j=0;j<4;j++) {

                if(j!=0)

                    a[i][j]="0";

                else

                    a[i][j]="姓名";

            }

        }

        button=new JButton("计算每人总成绩");

        table=new JTable(a,name);

        button.addActionListener(this);

        Container con=getContentPane();

        con.add(new JScrollPane(table),BorderLayout.CENTER);

        con.add(new JLabel("修改或录入数据后,需回车确认"),BorderLayout.NORTH);

        con.add(button,BorderLayout.SOUTH);

        setSize(300,300);

        setVisible(true);

        validate();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

        for(int i=0;i<8;i++) {

            double sum=0;

            boolean boo=true;

            for(int j=1;j<=2;j++){

                try{  sum=sum+Double.parseDouble(a[i][j].toString());

                }

                catch(Exception ee){

                    boo=false;

                    table.repaint();

                }

                if(boo==true) {

                    a[i][3]=""+sum;

                    table.repaint();

                }

            }

        }

    }

}

运行结果:

  • 40
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值