GUI编程学习
一,什么是GUI
图形用户界面(Graphical User Interface,简称 GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界面。
图形用户界面是一种人与计算机通信的界面显示格式,允许用户使用鼠标等输入设备操纵屏幕上的图标或菜单选项,以选择命令、调用文件、启动程序或执行其它一些日常任务。与通过键盘输入文本或字符命令来完成例行任务的字符界面相比,图形用户界面有许多优点。图形用户界面由窗口、下拉菜单、对话框及其相应的控制机制构成,在各种新式应用程序中都是标准化的,即相同的操作总是以同样的方式来完成,在图形用户界面,用户看到和操作的都是图形对象,应用的是计算机图形学的技术。
二,AWT
1.组件
1.窗口
创建一个Frame窗口
Frame frame = new Frame("窗口名");
窗口属性
//创建一个窗口,窗口类型为"我的窗口"
Frame frame = new Frame("我的窗口");
//设置窗口名称(可选)
frame.setName("haha");
//设置窗口的是否可见(默认不可见)
frame.setVisible(true);
//设置窗口大小
frame.setSize(200,200);
//设置窗口的初始位置(可选)//相对于屏幕
frame.setLocation(500,500);
//frame.setBounds(100,100,100,100);
//上面两行代码可以用frame.setBounds()代替;
//设置窗口的背景颜色(可选)
frame.setBackground(Color.BLUE);
//设置窗口大小是否固定(可选)默认不可以动
frame.setResizable(false);
//设置布局(设置为null则为绝对布局)
frame.setLayout(null);
2.面板
//创建一个面板
Panel panel = new Panel();
panel.setBackground(Color.GREEN);
//panel的位置是相对于frame的
panel.setBounds(100,100,100,100);
//将面板添加到窗口中
frame.add(panel);
//添加窗口关闭监听器,是窗口能够关不,注意是在windowClosing()方法中设置关闭
frame.addWindowListener(new WindowAdapter() {
//窗口打开事件
public void windowOpened(WindowEvent e) {
System.out.println(e.getWindow().getName()+"窗口打开");
}
public void windowClosing(WindowEvent e) {
//窗口关闭事件
//e.getWindow().add()
System.out.println(e.getWindow().getName()+"窗口关闭了");
System.exit(0);
}
});
3.按钮
//创建按钮
Button button1 = new Button("button1");//注意,使用中文可能会乱码,
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//将按钮添加到窗口容器中
frame.add(button1);
frame.add(button2);
frame.add(button3);
按钮可以添加事件监听,设置按钮上面的标签等
4.标签
//创建标签
Label label = new Label();
//设置标签文字
label.setText("你好!");
5.文本框和文本域
Frame frame = new Frame();
frame.setVisible(true);
frame.setResizable(true);
//frame.pack();//Frame的函数,使窗口的大小自动适应
frame.setBounds(500,500,500,500);
//创建一个50行20列的文本域
//TextArea textArea = new TextArea(50,20);
//创建一个文本框长度为10个字符
TextField textFiled = new TextField(10);
//为文本框设置一个替换编码(可选,主要用于密码输入)
textFiled.setEchoChar('*');
//添加监听器
textFiled.addActionListener(new ActionListener() {
//按下回车键时触发
@Override
public void actionPerformed(ActionEvent e) {
//e.getSource(),谁使用这个监听器,就返回谁的对象
TextField textField =(TextField) e.getSource();
//得到用户输入的文本,并且将它输出
System.out.println(textField.getText());
//重置文本域
textField.setText("");
}
});
frame.add(textFiled);
2.布局
1. Border Layout
BorderLayout:边界布局
Frame frame = new Frame();
frame.setVisible(true);
frame.setResizable(true);
frame.setBounds(500,500,500,500);
//BorderLayout borderLayout = new BorderLayout();
//可以用borderLayout对象设置好组件位置再添加到容器中
/*BorderLayout常用的五个位置,东西南北中
* BorderLayout.EAST
* BorderLayout.WEST
* BorderLayout.SOUTH
* BorderLayout.NORTH
* BorderLayout.CENTER
* */
//设置按钮的位置,相对位置
frame.add(new Button("button1"),BorderLayout.EAST);
frame.add(new Button("button2"),BorderLayout.WEST);
frame.add(new Button("button3"),BorderLayout.SOUTH);
frame.add(new Button("button4"),BorderLayout.NORTH);
frame.add(new Button("button5"),BorderLayout.CENTER);
}
效果图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vBiTLbTw-1630343441154)(C:\Users\TR\AppData\Roaming\Typora\typora-user-images\image-20210827200046570.png)]
2. Flow Layout
流式布局
Frame frame = new Frame();
frame.setVisible(true);
//设置布局为流式布局,居中
/*
流式布局的五个可选项常量
public static final int LEFT = 0;//居左
public static final int CENTER = 1;//居中
public static final int RIGHT = 2;//居右
public static final int LEADING = 3;//在头
public static final int TRAILING = 4;//在尾
*/
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setSize(500,500);
frame.setResizable(true);
for (int i = 0; i < 6; i++) {
frame.add(new Button("button"+i));
}
效果图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ao9PZvJy-1630343441156)(C:\Users\TR\AppData\Roaming\Typora\typora-user-images\image-20210827201214488.png)]
3. Grid Layout
Grid Layout:网格布局
Frame frame = new Frame();
frame.setVisible(true);
frame.setResizable(true);
frame.setBounds(500,500,500,500);
//frame.setLayout(new GridLayout(3,2));//三行两列
frame.setLayout(new GridLayout(2,3));//两行三列
for (int i = 0; i <6 ; i++) {
frame.add(new Button("button"+i));
}
效果图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eJDvP42T-1630343441157)(C:\Users\TR\AppData\Roaming\Typora\typora-user-images\image-20210827201404918.png)]
3.监听器
1. 事件监听器
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionListenerTest {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
frame.setResizable(true);
frame.setBounds(500,500,500,500);
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
Panel panel = new Panel();
panel.setVisible(true);
panel.setBounds(100,100,100,100);
//给按钮设置按压命令
button1.setActionCommand("我使用了Lambda表达式");
//给该按钮添加ActionListener
//方式一,使用Lambda表达式
button1.addActionListener((ActionEvent e)->{
//得到按压命令并输出按压命令
System.out.println(e.getActionCommand());
});
//方式二:使用ActionListener实现类
MyAction myAction = new MyAction();
button2.addActionListener(myAction);
button2.setActionCommand("我使用了ActionListener实现类");
//方式三:使用匿名内部类
button3.setActionCommand("我使用匿名内部类");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
});
panel.add(button1,BorderLayout.NORTH);
panel.add(button2,BorderLayout.CENTER);
panel.add(button3,BorderLayout.SOUTH);
frame.add(panel);
}
}
class MyAction implements ActionListener{
//通过实现事件监听器接口的方式创建
static int count = 0;
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand()+"->按压第"+(++count)+"次了");
}
}
效果图:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZkifNz98-1630343441159)(C:\Users\TR\AppData\Roaming\Typora\typora-user-images\image-20210827202346500.png)]
2.窗口监听
package study4.Listener;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WindowListenerTest extends Frame {
public WindowListenerTest() {
setSize(500,500);
setVisible(true);
setResizable(true);
setBackground(Color.CYAN);
//使用适配器,只需重写自己想重写的方法
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
WindowListenerTest windowListenerTest = (WindowListenerTest)e.getSource();
//setVisible(false);//点击关闭时隐藏在原来的位置
System.out.println("窗口关闭了");
System.exit(0);//状态码 0,表示安全退出
}
@Override
public void windowActivated(WindowEvent e) {
//当窗口被打开,或者说再次获得焦点时,触发
System.out.println("窗口被激活了");
}
});
}
public static void main(String[] args) {
new WindowListenerTest();
}
}
3.键盘监听
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyListenerTest extends Frame {
public KeyListenerTest(){
this.setSize(500,500);
this.setVisible(true);
this.setResizable(true);
this.setBackground(Color.BLUE);
Panel panel = new Panel();
panel.setSize(200,200);
panel.setBackground(Color.black);
panel.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获取当前键盘按下的码
int keyCode = e.getKeyCode();
System.out.println(keyCode);
if (keyCode == KeyEvent.VK_Q){
//如果按下了Q键,那么输出一句话
System.out.println("你按下了Q键");
}
}
});
this.add(panel);
}
public static void main(String[] args) {
new KeyListenerTest();
}
}
4.鼠标监听
package study4.Listener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
public class TestMouseListener {
public static void main(String[] args) {
Frame frame = new Frame("");
frame.setVisible(true);
frame.setBounds(500,500,500,500);
frame.setFocusable(true);获取焦点事件,注意该代码应该写到setVisible()方法后面,否则键盘监听器可能会失效
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("鼠标点击");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("鼠标按压");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("鼠标释放");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("鼠标进入");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("鼠标退出");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
System.out.println("鼠标滚轮移动");
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("鼠标拖拽");
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("鼠标移动");
}
});
}
}
**注意:**鼠标点击 = 鼠标按压+鼠标释放
三,Swing
1.什么是Swing
Swing是一个为Java设计的GUI工具包,属于Java基础类的一部分。Swing包括了图形用户界面(GUI)功能,其组件包含:文本框、文本域、按钮、表格、列表……等等。
Swing提供许多比AWT更好的屏幕显示元素。它们用纯Java写成,所以同Java本身一样可以跨平台运行,这一点不像AWT(是以AWT的升级)。它们是JFC的一部分。它们支持可更换的面板和主题(各种操作系统默认的特有主题),然而不是真的使用原生平台提供的设备,而是仅仅在表面上模仿它们。这意味着你可以在任意平台上使用Java支持的任意面板。轻量级组件的缺点则是执行速度较慢,优点就是可以在所有平台上采用统一的行为。
1.组件
1.窗口
package study06;
import javax.swing.*;
import java.awt.*;
public class JFrameTest {
public JFrameTest(){
//使用构造器创建,比较偷懒
//创建一个JFrame窗口
JFrame jFrame = new JFrame("我的窗口");
//设置窗口可见
jFrame.setVisible(true);
//设置窗口的大小
jFrame.setSize(500,500);
//设置窗口的大小可以修改
jFrame.setResizable(true);
//设置布局
jFrame.setLayout(new FlowLayout());
//设置窗口关闭,JFrame自带,也可以自己用监听器关
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame实现了WindowConstants接口,所以也可以以使用JFrame.EXIT_ON_CLOSE的方式
//WindowConstants的四个常量
/*
* DO_NOTHING_ON_CLOSE 什么都不做关上 就是点击关闭,窗口不能关掉
* HIDE_ON_CLOSE 隐藏在关闭位置
* DISPOSE_ON_CLOSE 在关闭时处理
* EXIT_ON_CLOSE 在关闭时退出
* */
//JFrame窗口添加组件和设置背景颜色,需要使用窗口容器进行添加,否则会出现莫名其妙的问题
Container container = jFrame.getContentPane();
container.setBackground(Color.BLUE);
}
public static void main(String[] args) {
new JFrameTest();
}
}
2.面板
JPanel panel = new JPanel();//使用方式和AWT基本一致,就不多说了
3.标签
标签和按钮的功能和使用方式和AWT基本一致
JLabel jLabel1 = new JLabel("标签");
4.普通按钮
普通按钮和AWT的功能和使用方式和AWT基本一致
JButton jButton1 = new JButton("按钮");//按钮上放文本
jButton1.setToolTipText("点我");//设置按钮的提示信息
5.多选和单选按钮
1.单选按钮 Radio Button
package study06;
import javax.swing.*;
import java.awt.*;
public class RadioButtonTest extends JFrame {
public OtherButton(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//得到顶级容器
Container container = this.getContentPane();
//创建一个单选按钮
JRadioButton rb1 = new JRadioButton("rb1");
JRadioButton rb2 = new JRadioButton("rb2");
JRadioButton rb3 = new JRadioButton("rb3");
//由于单选按钮只能选择一个,所以需要将他们添加到一个分组里,否则全部都可以选择
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
bg.add(rb3);
container.add(rb1,BorderLayout.NORTH);
container.add(rb2,BorderLayout.CENTER);
container.add(rb3,BorderLayout.SOUTH);
}
public static void main(String[] args) {
new RadioButtonTest();
}
}
2.多选按钮
package study06;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import java.awt.*;
public class OtherButton02 extends JFrame{
public OtherButton02(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
//创建多选按钮
JCheckBox jCheckBox1 = new JCheckBox("打篮球");
JCheckBox jCheckBox2 = new JCheckBox("打羽毛球");
JCheckBox jCheckBox3 = new JCheckBox("踢足球");
container.add(jCheckBox1,BorderLayout.NORTH);
container.add(jCheckBox2,BorderLayout.CENTER);
container.add(jCheckBox3,BorderLayout.SOUTH);
}
public static void main(String[] args) {
new OtherButton02();
}
}
6.图标
Swing中的按钮和标签均能添加图标属性
1.自画图标
package study06;
import javax.swing.*;
import java.awt.*;
//图标标签
public class IconTest extends JFrame {
public IconTest(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
//图标按钮
//通过图标创建按钮
JButton jButton = new JButton(new MyIcon(50,50));
jButton.setBounds(100,100,100,100);
// jButton.setIcon(new MyIcon(50,50));
//图标标签
//三个参数:标签名称,图标,位置
JLabel jLabel = new JLabel("带有图标的标签",new MyIcon(50,50),SwingConstants.CENTER);
//或者两个参数JLabel jLabel = new JLabel(new MyIcon(50,50),SwingConstants.CENTER);
container.add(jButton);
container.add(jLabel);
}
public static void main(String[] args) {
new IconTest();
}
}
class MyIcon implements Icon {
private int iconWidth;
private int iconHeight;
public MyIcon(int iconWidth,int iconHeight){
this.iconWidth = iconWidth;
this.iconHeight = iconHeight;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
//设置按钮的颜色
g.setColor(Color.BLUE);
//画一个椭圆
g.fillOval(x,y,iconWidth,iconHeight);
//画字符串
//new Font(字体,加粗等,字体大小)
g.setFont(new Font("微软雅黑",Font.BOLD,18));
g.setColor(Color.PINK);
g.drawString("图标按钮",x,y);
}
@Override
public int getIconWidth() {
return this.iconWidth;
}
@Override
public int getIconHeight() {
return this.iconHeight;
}
}
2.通过图片创建图标
package study06;
import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageIconTest extends JFrame{
//带有图片的标签
public ImageIconTest(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
//通过反射获取图片地址(也可以通过创建URL直接写死)
URL url = this.getClass().getResource("img.png");
URL url1 = null;
try {
//通过网络获取资源
url1 = new URL("https://images2017.cnblogs.com/blog/894443/201709/894443-20170920105433618-867225449.png");//获取网路图片
} catch (MalformedURLException e) {
System.out.println("无法获取网络图片");
url1 = url;//找不到就用本机的
e.printStackTrace();
}
//可以通过URL创建,也可以通过本机文件路径创建
//ImageIcon imageIcon = new ImageIcon("src/study06/img.png");
//图片图标类ImageIcon可以使用paintIcon()方法画到指定容器中
ImageIcon imageIcon = new ImageIcon(url1);
JButton jButton = new JButton("图标按钮");
//给按钮添加图标
jButton.setIcon(imageIcon);
//设置水平对齐(图标在面板中的位置)
jButton.setHorizontalAlignment(SwingConstants.CENTER);
//设置按钮中文本的位置
//jButton.setHorizontalTextPosition(SwingConstants.TRAILING);
//设置按钮提示文字
jButton.setToolTipText("点击按钮");
JLabel jLabel = new JLabel("带有图片的标签");
jLabel.setIcon(imageIcon);
//设置水平文本(按钮中文本的位置)
jLabel.setHorizontalTextPosition(SwingConstants.CENTER);
//设置水平对齐(标签在面板中的位置)
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
//添加到容器中
container.setLayout(new GridLayout(2,1));
container.add(jLabel);
container.add(jButton);
}
public static void main(String[] args) {
new ImageIconTest();
}
}
6.文本框和文本域
1.文本框
//创建文本框只有一行,不能换行
JTextField jTextField = new JFormattedTextField();
2.文本域
//创建文本域 20行,50列,可以用回车键换行
JTextArea field = new JTextArea(20,20);
3.密码框
//创建密码框 只有一行,不能换行
JPasswordField jPasswordField = new JPasswordField();
//设置输入的文字用什么字符替换
jPasswordField.setEchoChar('*');
7.滑动面板
滑动面板 :JScrollPane
//创建一个ScrollPane面板//带有滚动条的面板,当里面的组件,或者文字超出他的大小时,会出现滚动条
//常与文本域搭配
JScrollPane jScrollPane = new JScrollPane();
//jScrollPane.add(field);
8.弹窗
package study06;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//Dialog弹窗
public class JDialogTest extends JFrame {
Container container;
//Timer timer = new Timer(500,actionListener);//开启后定时弹出弹窗
public JDialogTest(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setResizable(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
container = this.getContentPane();
//设置布局为绝对布局
container.setLayout(null);
//创建一个按钮
JButton button = new JButton("点击此处弹出一个对话框");
//设置按钮提示文字
button.setToolTipText("点击按钮弹出弹窗");
//此时设置按钮的位置就是相对于窗口位置定位
button.setBounds(50,50,200,100);
//ActionListener可以用Lambda表达式,ActionListener只有一个方法
button.addActionListener(e->{
new MyDialog();//点击按钮弹出弹窗
//timer.start();
});
container.add(button);
}
public static void main(String[] args) {
new JDialogTest();
}
}
class MyDialog extends JDialog{
public MyDialog(){
//设置弹窗可见
this.setVisible(true);//弹窗默认不可见
this.setBounds(600,500,500,500);
Container container = this.getContentPane();
JButton jButton = new JButton("无线循环");
jButton.addActionListener(new ActionListener() {
//事件监听,点击按钮弹出弹窗
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
container.add(jButton);
}
}
9.下拉框和列表
1.下拉框
package study07;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class ComboboxTest extends JFrame {
public ComboboxTest(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
//创建下拉框
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem(null);
comboBox.addItem("第一个");
comboBox.addItem("第二个");
comboBox.addItem("第三个");
//添加复选框监听事件
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
//输出选中项目
System.out.println(e.getItem());
}
});
container.add(comboBox);
}
//启动
public static void main(String[] args) {
new ComboboxTest();
}
}
2.列表
package study07;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Vector;
public class ComboboxTest02 extends JFrame{
public ComboboxTest02(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
//创建列表
//String[] str = {"1","2","3"};//静态数组
//动态数组,动态数组可以用于游戏数据的储存,聊天记录的储存等
Vector<String> str = new Vector<String>();
JList<String> jList = new JList<String>(str);
str.add("你");
str.add("我");
str.add("他");
container.add(jList);
}
//启动
public static void main(String[] args) {
new ComboboxTest02();
}
}
四,项目实战
1.简单的计算器实现
仅支持一级运算:如5*5,9/5等,
package myDamo;
import java.awt.*;
import java.awt.event.*;
import java.nio.charset.StandardCharsets;
public class SimpleCalculator {
public static void main(String[] args) {
new CalculatorSubject().load();
}
}
class CalculatorSubject {
TextField textField;//计算框
TextField textField2;//结果框
String f;//储存符号
public void load(){
//监听器1 --添加字符
Append append = new Append();//添加字符的监听器
Remove remove = new Remove();//删除字符的监听器
RemoveAll removeAll = new RemoveAll();//删除所有字符的监听器
Result result = new Result();//计算结果的监听器
Function function = new Function();//各个运算符的监听器
Frame frame = new Frame();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(600,500);
//五个面板
Panel panel1 = new Panel();
Panel panel2 = new Panel();
Panel panel3 = new Panel();
Panel panel4 = new Panel();
Panel panel5 = new Panel();
//一个标签
Label r = new Label("result:");
//r.setAlignment(Label.CENTER);//设置对其
//两个文本域
textField = new TextField(40);
textField2 = new TextField(40);
//面板的布局
//设置尺寸
panel1.setSize(600,150);
panel1.setLayout(new GridLayout(3,1));
panel2.setSize(600,350);
panel2.setLayout(new GridLayout(1,2,25,20));
panel3.setSize(300,300);
panel3.setLayout(new GridLayout(3,3));
panel4.setSize(200,300);
panel4.setLayout(new GridLayout(2,3));
panel5.setSize(100,100);
panel5.setLayout(new GridLayout(3,1));
//17个按钮
//10个数字按钮
for (int i = 1; i <10 ; i++) {
Button button = new Button(i+"");
button.addActionListener(append);
panel3.add(button);
}
Button button0 = new Button("0");
button0.addActionListener(append);//0
//7个功能按钮
Button button1 = new Button("+");
Button button2 = new Button("-");
Button button3 = new Button("*");
Button button4 = new Button("/");
Button button5 = new Button("remove");//
Button button6 = new Button("=");//
Button button7 = new Button("removeAll");//清除全部
button1.addActionListener(function);
button2.addActionListener(function);
button3.addActionListener(function);
button4.addActionListener(function);
button5.addActionListener(remove);
button6.addActionListener(result);
button7.addActionListener(removeAll);
//添加
panel5.add(button7);
panel5.add(button5);
panel5.add(button6);
panel4.add(button1);
panel4.add(button2);
panel4.add(button3);
panel4.add(button4);
panel4.add(button0);
panel4.add(panel5);
panel2.add(panel3);
panel2.add(panel4);
panel1.add(textField);
panel1.add(r);
panel1.add(textField2);
frame.add(panel1);
frame.add(panel2);
frame.setLayout(new GridLayout(2,1));
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("窗口关闭");
System.exit(0);
}
});
}
//输入框输入
class Append implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Button button = (Button)e.getSource();
textField.setText(textField.getText()+button.getLabel());
}
}
//删除输入的字符
class Remove implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
String string = new String(text.getBytes(StandardCharsets.UTF_8),0,text.length()-1);
textField.setText(string);
}
}
//删除所有输入的字符
class RemoveAll implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
}
//计算结果
class Result implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
Button button =(Button) e.getSource();
int index= text.indexOf(f);
System.out.println(f);
double num1 = Double.parseDouble(text.substring(0,index));
double num2 = Double.parseDouble(text.substring(index+1));
double result = 0;
//System.out.println(num1+f+num2);
textField2.setText("");//重置结果框
//获得运算法,并计算结果
switch (f){
case "-":{
result = num1-num2;
textField2.setText(result+"");//将结果输出到结果框
break;
}
case "+":{
result = num1+num2;
textField2.setText(result+"");//将结果输出到结果框
break;
}
case "/":{
result = num1/num2;
textField2.setText(result+"");//将结果输出到结果框
break;
}
case "*":{
result = num1*num2;
textField2.setText(result+"");//将结果输出到结果框
break;
}
default:{
System.out.println("输入有误");
}
}
}
}
//符号
class Function implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Button button =(Button) e.getSource();
f = button.getLabel();//将输入框的的命令设置为按钮的标签
textField.setText(textField.getText()+button.getLabel());
}
}
}
效果图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PPH9FiXo-1630343599305)(C:\Users\TR\AppData\Roaming\Typora\typora-user-images\image-20210829171634245.png)]
2.交互式画画板的实现
package myDamo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFreePaint {
//启动程序
public static void main(String[] args) {
new MyPaintWindow("我的自由画画板");
}
}
class MyPaintWindow extends JFrame {
private int x1,x2,y1,y2;
private final MyPaintPanel myPaintPanel;
private Color color;//笔的颜色
private int state;//笔的状态,1为画笔,0为橡皮擦
public MyPaintWindow(String name){
super(name);
//设置窗口参数
setVisible(true);
setSize(1000,800);
setResizable(false);
setBackground(Color.WHITE);
//初始化画画板
myPaintPanel = new MyPaintPanel();
//初始化画板参数
color = Color.black;
state = 1;
//添加窗口关闭功能
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("窗口关闭");
System.exit(0);
}
});
//添加组件
Container container = this.getContentPane();
//添加清除按钮
// container.add(button,BorderLayout.SOUTH);
container.add(myPaintPanel,BorderLayout.CENTER);
container.add(new MyPowerPanel(),BorderLayout.NORTH);
}
//功能面板
private class MyPowerPanel extends JPanel{
public MyPowerPanel(){
this.setVisible(true);
this.setSize(1000,100);
//清除按钮按钮
JButton button = new JButton("clear");
//按钮添加监听事件
button.addActionListener(e -> {
//添加按钮监听器,清空画画板
myPaintPanel.paintComponent(myPaintPanel.getGraphics());
});
//创建下拉框
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("请选择画笔颜色");
comboBox.addItem("红色");
comboBox.addItem("蓝色");
comboBox.addItem("绿色");
comboBox.addItem("黑色");
comboBox.addItem("黄色");
comboBox.addItem("橡皮擦");
//添加复选框监听事件
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
//得到复选框选项
String colors = (String) e.getItem();
//判断复选框内容
switch (colors){
case "红色":{
color = Color.red;
state = 1;
break;
}
case "蓝色":{
color = Color.BLUE;
state = 1;
break;
}
case "绿色":{
color = Color.green;
state = 1;
break;
}
case "黑色":{
color = Color.black;
state = 1;
break;
}
case "黄色":{
color = Color.yellow;
state = 1;
break;
}
case "橡皮擦":{
color = Color.white;
state = 0;
break;
}
default:{
}
}
}
});
this.add(button);
this.add(comboBox);
}
}
//画画板
private class MyPaintPanel extends JPanel {
public MyPaintPanel(){
this.setSize(1000,600);
this.setBackground(Color.white);
//添加鼠标监听事件
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
//鼠标按压时的坐标
x1 = e.getX();
y1 = e.getY();
}
});
//添加鼠标移动事件
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
//获取拖拽后的鼠标坐标
x2 = e.getX();
y2 = e.getY();
Graphics myG = myPaintPanel.getGraphics();
//设置笔的颜色
myG.setColor(color);
//判断是笔还是橡皮差
if (state == 0){
myG.fillRect(x1,y1,20,20);
}else {
myG.drawLine(x1, y1, x2, y2);
}
//画完后重新定义起点
x1 = x2;
y1 = y2;
}
});
}
//重写父类的方法用于清空面板
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
}
3.单人贪吃蛇的实现
码云下载链接:请勿白嫖,谢谢
贪吃蛇游戏下载