图形用户界面设计实验

图形用户界面设计实验,第1张

(一)运行下列程序,并查看布局效果
package case1;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFlowLayout {
    private Frame f;
    private Button button1, button2, button3;

    public static void main(String args[]) {
        MyFlowLayout mflow = new MyFlowLayout();
        mflow.go();
    }

    public void go() {
        f = new Frame("FlowLayout效果");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        // f.setLayout(new FlowLayout());
        f.setLayout(new FlowLayout(FlowLayout.LEADING, 20, 20));
        button1 = new Button("第一个按钮");
        button2 = new Button("第二个按钮");
        button3 = new Button("第三个按钮");
        f.add(button1);
        f.add(button2);
        f.add(button3);
        f.setSize(200, 200);
        f.pack();
        f.setVisible(true);
    }
}


说明:Java提供了多种布局,如FlowLayout、BorderLayout、GridLayout、CardLayout、GridBagLayout等。其中FlowLayout布局的原则是将各个组件按照添加的顺序,从左到右、从上到下进行放置,如果本行放不下所有组件,则放入下一行。Panel容器的默认布局就是FlowLayout布局。

(二)编写程序,绘制如下界面。


说明:BorderLayout布局类似与地图上的方向,用东、西、南、北、中来安排组件的布局,分别用EAST、WEST、SOUTH、NORTH和CENTER来代表各个方向,以上北下南、左西右东占据界面的四边,CENTER占据剩余中间部分。

package case2;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class BorderLayout {
    Frame f;
    Button east, south, west, north, center;

    public static void main(String args[]) {
        BorderLayout mb = new BorderLayout();
        mb.go();
    }

    public void go() {
        f = new Frame("BorderLayout 演示");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });

        f.setBounds(0, 0, 300, 300);
        f.setLayout(new BorderLayout());

        north = new Button("上");
        south = new Button("下");
        east = new Button("右");
        west = new Button("左");
        center = new Button("中");

        f.add(BorderLayout.NORTH, north);
        f.add(BorderLayout.SOUTH, south);
        f.add(BorderLayout.EAST, east);
        f.add(BorderLayout.WEST, west);
        f.add(BorderLayout.CENTER, center);

        f.setVisible(true);
    }
}

(三)编写程序,绘制如下界面。


说明:GirdLayout是一种网格布局,将容器划分成若干行和列的结构,在各个网格中放置组件。在网格布局中的各个组件具有相同的宽和高,其放置顺序也是从左向右开始填充,一行占满后开始填充下一行,仍然是从左到右的顺序。

package case3;

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

public class CardLayout {
    public static void main(String args[]) {
        new CardLayout().go();
    }

    public void go() {
        final Frame f = new Frame("CardLayoutÑÝʾ");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });

        f.setSize(300, 100);
        f.setLayout(new CardLayout());

        final Frame f1 = f;
        for (int i = 1; i <= 5; ++i) {
            Button b = new Button("Button " + i);
            b.setSize(100, 25);
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    CardLayout cl = (CardLayout) f1.getLayout();
                    cl.next(f1);
                }
            });
            f.add(b, "button" + i);
        }
        f.setVisible(true);
    }
}
(四)编写程序,绘制如下界面。掌握AWT组件的用法。

package case4;

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

class MenuTest extends Frame {
    PopupMenu pop;

    public MenuTest() {
        super("Golf Caddy");
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                setVisible(false);
                dispose();
                System.exit(0);
            }
        });
        this.setSize(300, 300);
        this.add(new Label("Choose club."), BorderLayout.NORTH);

        Menu woods = new Menu("Woods");
        woods.add("1 W");
        woods.add("3 W");
        woods.add("5 W");

        Menu irons = new Menu("Irons");
        irons.add("3 iron");
        irons.add("4 iron");
        irons.add("5 iron");
        irons.add("7 iron");
        irons.add("8 iron");
        irons.add("9 iron");
        irons.addSeparator();
        irons.add("PW");
        irons.insert("6 iron", 3);

        MenuBar mb = new MenuBar();
        mb.add(woods);
        mb.add(irons);
        this.setMenuBar(mb);

        pop = new PopupMenu("Woods");
        pop.add("1 W");
        pop.add("3 W");
        pop.add("5 W");

        final TextArea p = new TextArea(100, 100);

        p.setBounds(0, 0, 100, 200);
        p.setBackground(Color.green);
        p.add(pop);
        p.addMouseListener(new MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                if (evt.isPopupTrigger()) {
                    System.out.println("popup trigger");
                    System.out.println(evt.getComponent());
                    System.out.println("" + evt.getX() + " " + evt.getY());
                    pop.show(p, evt.getX(), evt.getY());
                }

            }
        });
        this.add(p, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        new MenuTest().setVisible(true);
    }
}
(五)编写程序,绘制如下界面,掌握Swing组件的用法。

package case5;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;

public class TableDemo extends JFrame {
    private boolean DEBUG = true;

    public TableDemo() { // 实现构造方法
        super("RecorderOfWorkers"); // 首先调用父类JFrame的构造方法生成一个窗口
        MyTableModel myModel = new MyTableModel();// myModel存放表格的数据
        JTable table = new JTable(myModel);// 表格对象table的数据来源是myModel对象
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));// 表格的显示尺寸

        // 产生一个带滚动条的面板
        JScrollPane scrollPane = new JScrollPane(table);
        // 将带滚动条的面板添加入窗口中
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        addWindowListener(new WindowAdapter() {// 注册窗口监听器
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // 把要显示在表格中的数据存入字符串数组和Object数组中
    class MyTableModel extends AbstractTableModel {
        // 表格中第一行所要显示的内容存放在字符串数组columnNames中
        final String[] columnNames = { "First Name", "Position", "Telephone", "MonthlyPay", "Married" };
        // 表格中各行的内容保存在二维数组data中
        final Object[][] data = { { "Zhang San", "Executive", "01066660123", new Integer(8000), new Boolean(false) },
                { "Li Si", "Secretary", "01069785321", new Integer(6500), new Boolean(true) },
                { "Wang Wu", "Manager", "01065498732", new Integer(7500), new Boolean(false) },
                { "Da Xiong", "Safeguard", "01062796879", new Integer(4000), new Boolean(true) },
                { "Kang Fu", "Salesman", "01063541298", new Integer(7000), new Boolean(false) } };
        // 下述方法是重写AbstractTableModel中的方法,其主要用途是被JTable对象调用,///以便在表格中正确的显示出来。程序员必须根据采用的数据类型加以恰当实现。

        // 获得列的数目
        public int getColumnCount() {
            return columnNames.length;
        }

        // 获得行的数目
        public int getRowCount() {
            return data.length;
        }

        // 获得某列的名字,而目前各列的名字保存在字符串数组columnNames中
        public String getColumnName(int col) {
            return columnNames[col];
        }

        // 获得某行某列的数据,而数据保存在对象数组data中
        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        // 判断每个单元格的类型
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        // 将表格声明为可编辑的
        public boolean isCellEditable(int row, int col) {

            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }

        // 改变某个数据的值
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of "
                        + value.getClass() + ")");
            }
            if (data[0][col] instanceof Integer && !(value instanceof Integer)) {
                try {
                    data[row][col] = new Integer(value.toString());
                    fireTableCellUpdated(row, col);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(TableDemo.this,
                            "The \"" + getColumnName(col) + "\" column accepts only integer values.");
                }
            } else {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
            }
            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();
            for (int i = 0; i < numRows; i++) {
                System.out.print(" row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    System.out.print(" " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }

    public static void main(String[] args) {
        TableDemo frame = new TableDemo();
        frame.pack();
        frame.setVisible(true);
    }
}
(六)运行下列程序,查看输出效果,掌握事件处理的概念。
package case6;

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

public class ButtonTest {
    public static void main(String[] args) {
        ButtonFrame frame = new ButtonFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

/**
 * A frame with a button panel
 */
class ButtonFrame extends JFrame {
    public ButtonFrame() {
        setTitle("ButtonTest");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        // add panel to frame
        ButtonPanel panel = new ButtonPanel();
        add(panel);
    }

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;
}

/**
 * A panel with three buttons.
 */
class ButtonPanel extends JPanel {
    public ButtonPanel() {
        // create buttons
        JButton yellowButton = new JButton("Yellow");
        JButton blueButton = new JButton("Blue");
        JButton redButton = new JButton("Red");

        // add buttons to panel
        add(yellowButton);
        add(blueButton);
        add(redButton);

        // create button actions
        ColorAction yellowAction = new ColorAction(Color.YELLOW);
        ColorAction blueAction = new ColorAction(Color.BLUE);
        ColorAction redAction = new ColorAction(Color.RED);

        // associate actions with buttons
        yellowButton.addActionListener(yellowAction);
        blueButton.addActionListener(blueAction);
        redButton.addActionListener(redAction);
    }

    /**
     * An action listener that sets the panel's background color.
     */
    private class ColorAction implements ActionListener {
        public ColorAction(Color c) {
            backgroundColor = c;
        }

        public void actionPerformed(ActionEvent event) {
            setBackground(backgroundColor);
        }

        private Color backgroundColor;
    }
}

(七)Java进行图形界面设计时的一般步骤是什么?

①选择容器;②确定布局;③向容器中添加组件;④进行事件处理。

(八)AWT中有哪几种布局管理器?

FlowLayout, BorderLayout, GridLayout, GridBagLayout, CardLayout。

(九)框架(Frame)和面板(Panel)的默认布局管理器是什么?

框架(Frame)默认的布局管理器是BorderLayout类型;
面板(Panel)默认的布局管理器是FlowLayout类型。

(十)监听器和适配器的作用是什么?为什么要引入适配器?

①监听器的作用:监听客户端的请求、服务端的 *** 作等;
②适配器的作用:实现了某种接口,提供了方法体,等再用到这个接口时就可以直接继承适配器
③为什么要引入适配器:简化编程。

(十一)什么是低级(low-level)事件和语义(semantic)事件?

低级事件是指基于组件、容器等的事件,例如按下鼠标、移动鼠标、抬起鼠标、转动鼠标滚轮、窗口状态变化等;
语言事件是指表达用户在某种动作意图的事件,例如单击某个按钮,调节滚动条滑块、选择某个菜单项或列表项、在文本框中按下回车键等。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/871624.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存