Java期末复习题之GUI

2023-12-23 06:06:16

点击返回标题->23年Java期末复习-CSDN博客

第1题.

一、利用Swing包创建一个窗口,窗口位置为(220,160)、大小为320×240,并在窗口(20,80)、(120,80)、(220,80)处各设置一个按钮,按钮大小为80 X 40。

点击左按钮将窗口背景的红色分量增加10,点击中间按钮将窗口背景的绿色分量增加10,点击右按钮将窗口背景的蓝色分量增加10,上述三种分量大于255时变成0,下面面板的颜色同步改变,点击窗口关闭按钮时退出程序运行。

①分析布局

题目要求按钮的位置和大小,说明需要使用的布局是空布局,但JFrame窗口的内容面板默认布局是边界布局(BorderLayout),所以需要设置一下,注意是设置Jpanel类对象(容器)的布局,而不是窗口的布局。

pane.setLayout(null);

②关于颜色,

Color类提供一个有参构造,传入rgb三原色的参数,返回对应的颜色。在代码中我采取匿名对象的形式去实例化这个颜色对象。而r,g,b是我定义在主类中的成员变量,通过监听按下的按钮,对r,g,b三个变量的值进行修改,然后更新(setBackground)背景颜色。

pane.setBackground(new Color(r, g, b));

③事件处理,

点击按钮,会触发ActionEvent事件,这个事件会被ActionListener接收器接收到, 只需要重写ActionListener里的actionPerformed 方法,即可实现点击按钮后,做某件事。

拿"红色"按钮举例,添加监听事件的对象采取匿名内部类的方式(如果忘了见本篇Java内部类-CSDN博客的标题二的子标题④学习),实现其中的actionPerformed方法,其它细节在注释中已经详细阐述了。剩余两个按钮同理。

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        r += 10;//让颜色分量r加10
        r = r > 255 ? 0 : r;//如果r超过10就赋值为0,否则就不变
        pane.setBackground(new Color(r, g, b));//重新设置背景颜色
    }
});

完整代码如下:

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


public class Main {

    int r = 90, g = 20, b = 180;

    public static void main(String[] args) {
        Main test = new Main();
        test.createGUI();
    }

    public void createGUI() {
        JFrame fr = new JFrame("这是主窗口");//通常直接在有参构造的时候命名,省得后续用setTitle()方法命名了。
        fr.setBounds(220, 160, 320, 240);
        fr.setVisible(true);//设置窗体可见,基本必写吧?
        fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置窗体关闭按钮响应事件为关闭此窗口。

        //创建容器和按钮组件,对按钮添加监听类对象,最后把按钮塞到容器中。
        JPanel pane = new JPanel();
        JButton button1 = new JButton("红色");
        JButton button2 = new JButton("绿色");
        JButton button3 = new JButton("蓝色");
        
        //给按钮组件设置位置、大小等参数,采用匿名内部类的方式实例化监听类对象并添加给按钮
        button1.setLocation(20, 80);
        button1.setSize(80, 40);
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                r += 10;//让颜色分量r加10
                r = r > 255 ? 0 : r;//如果r超过10就赋值为0,否则就不变
                pane.setBackground(new Color(r, g, b));//重新设置背景颜色
            }
        });

        button2.setLocation(120, 80);
        button2.setSize(80, 40);
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                g += 10;
                g = g > 255 ? 0 : g;
                pane.setBackground(new Color(r, g, b));
            }
        });

        button3.setLocation(220, 80);
        button3.setSize(80, 40);
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                b += 10;
                b = b > 255 ? 0 : b;
                pane.setBackground(new Color(r, g, b));
            }
        });
        //把按钮添加到容器中
        pane.setLayout(null);//题目明确的指出了按钮的位置和大小 ,那么说明需要使用的布局是空布局(绝对布局)
        pane.add(button1);
        pane.add(button2);
        pane.add(button3);
        //把容器放在窗口中
        fr.add(pane);
    }
}

博客中不方便展示效果图,请自行复制到IDE中进行验证。


第2题.(建议略过)

二、用swing包和布局管理器设计如下图所示调色板界面。点击加减按钮能改变颜色值中各色值的分量,下面面板的颜色同步改变

?说实话这题难度有点大了,蒟蒻博主实在是花了很长很长的时间硬磕(与应付期末考的初心背道而驰🤦?),没办法最后参考了大佬的写法,最终才潦草写出来(还有一堆bug不会改),这种情况下要我教学很难了(如果你也跟我一样是为了应对期末考,实在不建议多花一分钟在这题上,晦气(╯▔皿▔)╯),我只好贴个代码和原链接->Java图形用户界面设计_用swing包和布局管理器设计如下图所示调色板界面。点击加减按钮能改变颜色值中各-CSDN博客

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

public class Main extends JFrame {
    //三个标签
    Label l1, l2, l3;
    //六个按钮(三个?,三个?)
    Button add1, add2, add3, sub1, sub2, sub3;
    //三个文本框
    TextField tf1, tf2, tf3;
    int count1, count2, count3;
    Color c;
    //两个面板
    Panel p = new Panel();
    Panel p1 = new Panel();
    //设置布局
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();

    //构造器
    public Main() {

        setSize(500, 400);
        p.setLayout(gbl);
        gbc.fill = GridBagConstraints.BOTH;
        this.setLabel();
        this.setButton_add();
        this.setTxetField();
        this.setButton_sub();
        this.setPanel();
        add(p);
        setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new Main();
    }

    private void setPanel() {
        gbc.weightx = 10;
        gbc.weighty = 10;
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 4;
        gbc.insets = new Insets(10, 10, 10, 10);
        p1.setBackground(new Color(220, 220, 220));
        gbl.setConstraints(p1, gbc);
        p.add(p1);

    }

    private void setButton_sub() {
        sub1 = new Button("-");
        sub2 = new Button("-");
        sub3 = new Button("-");
        sub1.setFont(new Font("宋体", Font.PLAIN, 20));
        sub2.setFont(new Font("宋体", Font.PLAIN, 20));
        sub3.setFont(new Font("宋体", Font.PLAIN, 20));
        gbc.gridx = 3;
        gbc.gridy = 0;
        gbl.setConstraints(sub1, gbc);
        gbc.gridy = 1;
        gbl.setConstraints(sub2, gbc);
        gbc.gridy = 2;
        gbl.setConstraints(sub3, gbc);
        p.add(sub1);
        p.add(sub2);
        p.add(sub3);
        sub1.addActionListener(new changeText());
        sub2.addActionListener(new changeText());
        sub3.addActionListener(new changeText());

    }

    private void setTxetField() {
        tf1 = new TextField(5);
        tf2 = new TextField(5);
        tf3 = new TextField(5);

        tf1.setText("220");
        tf2.setText("220");
        tf3.setText("220");

        count1 = Integer.parseInt(tf1.getText());
        count2 = Integer.parseInt(tf1.getText());
        count3 = Integer.parseInt(tf1.getText());

        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbl.setConstraints(tf1, gbc);
        gbc.gridy = 1;
        gbl.setConstraints(tf2, gbc);
        gbc.gridy = 2;
        gbl.setConstraints(tf3, gbc);

        p.add(tf1);
        p.add(tf2);
        p.add(tf3);

        tf1.addTextListener(new changeText());
        tf2.addTextListener(new changeText());
        tf3.addTextListener(new changeText());

        this.setKeyPress(tf1);
        this.setKeyPress(tf2);
        this.setKeyPress(tf3);
    }

    private void setKeyPress(TextField tf) {
        //具体看addKeyListener的使用方法和说明
        tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                char ch = e.getKeyChar();
                if (!(ch >= '0' && ch <= '9')) {
                    e.consume();
                }
            }
        });
    }

    private void setButton_add() {
        add1 = new Button("+");
        add2 = new Button("+");
        add3 = new Button("+");
        add1.setFont(new Font("宋体", Font.PLAIN, 20));
        add2.setFont(new Font("宋体", Font.PLAIN, 20));
        add3.setFont(new Font("宋体", Font.PLAIN, 20));
        gbc.insets = new Insets(10, 80, 10, 10);//组件间间距
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbl.setConstraints(add1, gbc);
        gbc.gridy = 1;
        gbl.setConstraints(add2, gbc);
        gbc.gridy = 2;
        gbl.setConstraints(add3, gbc);
        p.add(add1);
        p.add(add2);
        p.add(add3);
        add1.addActionListener(new changeText());
        add2.addActionListener(new changeText());
        add3.addActionListener(new changeText());
    }

    private void setLabel() {//设置3个标签
        l1 = new Label("红色", Label.CENTER);
        l2 = new Label("绿色", Label.CENTER);
        l3 = new Label("蓝色", Label.CENTER);
        //设置标签背景色
        l1.setBackground(Color.RED);
        l2.setBackground(Color.GREEN);
        l3.setBackground(Color.BLUE);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.insets = new Insets(10, 10, 10, 10);
        gbl.setConstraints(l1, gbc);
        gbc.gridy = 1;
        gbl.setConstraints(l2, gbc);
        gbc.gridy = 2;
        gbl.setConstraints(l3, gbc);
        p.add(l1);
        p.add(l2);
        p.add(l3);
    }

    //实现接口中的方法actionPerformed和textValueChanged
    private class changeText implements ActionListener, TextListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == add1) {
                count1++;
                count1 = count1 > 255 ? 0 : count1;//边界判断防止参数越界
                tf1.setText((count1) + "");
            }
            if (e.getSource() == add2) {
                count2++;
                count2 = count2 > 255 ? 0 : count2;//边界判断防止参数越界
                tf2.setText((count2) + "");
            }
            if (e.getSource() == add3) {
                count3++;
                count3 = count2 > 255 ? 0 : count3;//边界判断防止参数越界
                tf3.setText((count3) + "");
            }

            if (e.getSource() == sub1) {
                count1--;
                count1 = count1 < 0 ? 255 : count1;//边界判断防止参数越界
                tf1.setText((count1--) + "");
            }
            if (e.getSource() == sub2) {
                count2--;
                count2 = count2 < 0 ? 255 : count2;//边界判断防止参数越界
                tf2.setText((count2--) + "");
            }
            if (e.getSource() == sub3) {
                count3--;
                count3 = count3 < 0 ? 255 : count3;//边界判断防止参数越界
                tf3.setText((count3--) + "");
            }
            //字符串转整数,方便设置背景颜色参数
            int c1 = Integer.parseInt(tf1.getText());
            int c2 = Integer.parseInt(tf2.getText());
            int c3 = Integer.parseInt(tf3.getText());

            p1.setBackground(new Color(c1, c2, c3));//重新设置面板颜色
        }

        public void textValueChanged(TextEvent e) {
            c = new Color(Integer.parseInt(tf1.getText()), Integer.parseInt(tf2.getText()), Integer.parseInt(tf3.getText()));
            p1.setBackground(c);
        }
    }
}

?


第3题.

三、鼠标事件处理:要求创建一个按钮,鼠标选中按钮不放开,将按钮拖拽到窗口其它他位置后,放开鼠标

?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;


public class Main extends JFrame {

    private JPanel contentPane;

    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(660, 500);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        add(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createLineBorder(Color.orange, 2));
        panel.setLayout(null);

        JButton button = new JButton("拖动我");
        button.setBounds(82, 85, 80, 20);
        panel.add(button);

        MyListener m = new MyListener();
        button.addMouseListener(m);
        button.addMouseMotionListener(m);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 写一个类继承鼠标监听器的适配器,这样就可以免掉不用的方法。  
    class MyListener extends MouseAdapter {
        //这两组x和y为鼠标点下时在屏幕的位置和拖动时所在的位置  
        int newX, newY, oldX, oldY;
        //这两个坐标为组件当前的坐标  
        int startX, startY;

        @Override
        public void mousePressed(MouseEvent e) {
            //此为得到事件源组件  
            Component cp = (Component) e.getSource();
            //当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置  
            startX = cp.getX();
            startY = cp.getY();
            oldX = e.getXOnScreen();
            oldY = e.getYOnScreen();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            Component cp = (Component) e.getSource();
            //拖动的时候记录新坐标  
            newX = e.getXOnScreen();
            newY = e.getYOnScreen();
            //设置bounds,将点下时记录的组件开始坐标与鼠标拖动的距离相加  
            cp.setBounds(startX + (newX - oldX), startY + (newY - oldY), cp.getWidth(), cp.getHeight());
        }

    }
}  

文章来源:https://blog.csdn.net/liKeQing1027520/article/details/135142985
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。