GUI编程
目录
GUI概述
GUI(Graphics User Interface),中文名称为图形用户界面,是指采用图形方式显示的计算机操作用户界面,是计算机与其使用者之间的对话接口,是计算机系统的重要组成部分。
组件
- 窗口
- 弹出
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标事件
- 键盘事件
核心技术
- Swing
- AWT
AWT
AWT概述
-
包含了很多类和接口!
-
元素:窗口,按钮,文本框
-
java.awt
组件和容器
Frame
演示1:frame
package gui;
import java.awt.*;
//GUI的第一个界面
public class TestFrame {
public static void main(String[] args) {
//Frame
Frame frame = new Frame("图形界面");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色
frame.setBackground(new Color(255, 255, 255));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
演示2:展示多个窗口
package gui;
import java.awt.*;
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
Myframe myframe1 = new Myframe(100, 100, 200, 200, Color.white);
Myframe myframe2 = new Myframe(300, 100, 200, 200, Color.black);
Myframe myframe3 = new Myframe(100, 300, 200, 200, Color.yellow);
Myframe myframe4 = new Myframe(300, 300, 200, 200, Color.pink);
}
}
class Myframe extends Frame {
static int id = 0; //可能存在多个窗口,我们需要一个计数器
public Myframe(int x,int y,int w,int h,Color color){
super("Myframe"+(++id));
setVisible(true);
setBounds(x, y, w, h);
setBackground(color);
}
}
面板Panel
面板
package gui;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Panel 可以看成是一个空间,但是不能单独存在
public class TestPanel {
public static void main(String[] args) {
//Frame
Frame frame = new Frame();
//布局的概念
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标 颜色
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(255,255,255));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(191, 160, 238));
//把panel放入frame中。故,frame中添加一个panel
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭事件 System.exit(0)
//适配器模式
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭的时候需要做的事情
@Override
public void windowClosing(WindowEvent e) {
super.windowOpened(e);
//结束程序
System.exit(0);
}
});
}
}
布局管理器
- 流式布局
- 东南西北中
- 表格布局
演示:流式布局
package gui;
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
//组件-按钮
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//设置为流式布局
frame.setLayout(new FlowLayout(FlowLayout.LEADING));
frame.setSize(200,200);
//把按钮添加上去
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
演示:东南西北中
package gui;
import java.awt.*;
public class TestFlowLayout1 {
public static void main(String[] args) {
Frame frame = new Frame("新的窗口");
Button east = new Button("East");
Button west = new Button("West");
Button south = new Button("South");
Button north = new Button("North");
Button center = new Button("Center");
frame.add(east,BorderLayout.EAST);
frame.add(west,BorderLayout.WEST);
frame.add(south,BorderLayout.SOUTH);
frame.add(north,BorderLayout.NORTH);
frame.add(center,BorderLayout.CENTER);
frame.setSize(200,200);
frame.setVisible(true);
}
}
演示:网格布局
package gui;
import java.awt.*;
public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("新的窗口");
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
Button button4 = new Button("button4");
Button button5 = new Button("button5");
frame.setLayout(new GridLayout(3,2));
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.pack();//Java函数,自动布局!
frame.setVisible(true);
}
}
练习
演示
package gui;
import java.awt.*;
public class TestDemo {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setSize(400,300);
frame.setLocation(400,300);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//四个面板
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2,2));
//上面
p1.add(new Button("East-1"),BorderLayout.EAST);
p1.add(new Button("West-1"),BorderLayout.WEST);
p2.add(new Button("p2-btn-1"));
p2.add(new Button("p2-btn-2"));
p1.add(p2,BorderLayout.CENTER);
//下面
p3.add(new Button("East-2"),BorderLayout.EAST);
p3.add(new Button("West-2"),BorderLayout.WEST);
/*p4.add(new Button("p4-btn-1"));
p4.add(new Button("p4-btn-2"));
p4.add(new Button("p4-btn-3"));
p4.add(new Button("p4-btn-4"));*/
for (int i = 0; i < 4; i++) {
p4.add(new Button("for-"+i));
}
p3.add(p4,BorderLayout.CENTER);
frame.add(p1);
frame.add(p3);
}
}
小结
- Frame是一个顶级窗口
- Panel无法单独显示,必须添加到某个容器中
- 布局管理器
- 流式布局
- 东西南北中布局
- 网格
- 大小,定位,背景颜色,可见性
事件监听
-
什么叫事件监听?你在电脑上设置个按钮,通过点击按钮来反馈里面所显示出来的信息。这就叫事件监听。
-
事件监听概念:通过某一事物源对象(当某种事件发生时),然后向监听器传送某种事件对象,监听器里面封装了某种事件信息,接到事件对象后进行某种处理,这就是事件监听。
演示:事件监听1
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestAction {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame = new Frame("我的窗口");
frame.setLocation(500,500);
Button button = new Button("button");
//因为,addActionListener需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack();
windowClose(frame);//关闭窗口
frame.setVisible(true);
}
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件监听
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
演示:事件监听2
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestAction2 {
public static void main(String[] args) {
//两个按钮,实现同一个监听
//开始 停止
Frame frame = new Frame("开始-停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值!
//可以多个按钮只写一个监听类
button2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//获得按钮的信息
System.out.println("按钮被点击了"+e.getActionCommand());
}
}
输入框事件监听
演示:textFiled
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestText {
public static void main(String[] args) {
//启动!
new MyFrame1();
}
}
class MyFrame1 extends Frame{
//构造方法
public MyFrame1(){
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyMonitor1 myMonitor1 = new MyMonitor1();
//按下enter 就会触发这个输入框的事件
textField.addActionListener(myMonitor1);
//设置替换编码
//textField.setColumns('*');
setVisible(true);
pack();
}
}
class MyMonitor1 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//获得按钮的信息
TextField field = (TextField) e.getSource();//获得资源,返回的一个对象
System.out.println(field.getText());//获得输入框的文本
field.setText("");//null
}
}
简易计算器
演示1:计算器
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
public Calculator() {
//3个文本框
TextField num1 = new TextField(10);//字符数
TextField num2 = new TextField(10);//字符数
TextField num3= new TextField(20);//字符数
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(num1 ,num2,num3 ));//监听
//1个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取三个变量
private TextField num1,num2,num3;//需要在这也写这个
public MyCalculatorListener( TextField num1, TextField num2, TextField num3){
this.num1=num1;
public void actionPerformed(ActionEvent e) {
//1.获得加数和被加数
int n1= Integer.parseInt(num1.getText());//将字符串类型转换为int类型
int n2= Integer.parseInt(num2.getText());
//2.将这个值加法运算后放入第三个框中
num3.setText(""+(n1+n2));
//3.清除前两个框的内容
num1.setText("");
num2.setText("");
}
}
演示2:计算器,面向对象
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame {
//属性
TextField num1, num2, num3;
//方法
public void loadFrame() {
//3个文本框
num1 = new TextField(10);//字符数
num2 = new TextField(10);//字符数
num3 = new TextField(20);//字符数
//1个按钮,添加监听事件
//1个标签
//布局
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(this));
Label label = new Label("+");
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取计算器这个变量,在一个类中组合另外一个类
Calculator calculator = null;
public MyCalculatorListener(Calculator calculator) {
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获得加数和被加数
//2.将这个值加法运算后,放到第三个运算框
//3.清除前两个框
int n1 = Integer.parseInt(calculator.num1.getText());
int n2 = Integer.parseInt(calculator.num2.getText());
calculator.num3.setText(""+(n1+n2));
calculator.num1.setText("");
calculator.num2.setText("");
}
}
演示3:计算器,内部类
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame {
//属性
TextField num1, num2, num3;
//方法
public void loadFrame() {
//3个文本框
num1 = new TextField(10);//字符数
num2 = new TextField(10);//字符数
num3 = new TextField(20);//字符数
//1个按钮,添加监听事件
//1个标签
//布局
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener());
Label label = new Label("+");
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
//监听器类
private class MyCalculatorListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//1.获得加数和被加数
//2.将这个值加法运算后,放到第三个运算框
//3.清除前两个框
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText(""+(n1+n2));
num1.setText("");
num2.setText("");
}
}
}
画笔
演示:画笔
package gui;
import java.awt.*;
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame {
public void loadFrame(){
setBounds(600,300,600,500);
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画笔,需要颜色,画笔可以画画
g.setColor(Color.BLACK);
g.drawOval(100,100,100,100);
g.fillOval(350,350,100,100);
g.setColor(Color.BLUE);
g.fillRect(200,200,100,200);
//画笔用完,还原到最初的颜色
}
}
鼠标监听
演示:鼠标画画
package gui;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
//鼠标监听事件
public class TestMouseListener {
public static void main(String[] args) {
new MyFrame("画图");
}
}
class MyFrame extends Frame {
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储画出来的东西
ArrayList points;
public MyFrame(String title) {
super(title);
setBounds(600, 300, 600, 500);
//存储鼠标点击的点
points = new ArrayList<>();
setVisible(true);
//鼠标监听器,针对窗口
this.addMouseListener(new MyMouseListener());
}
//画画需要重写画笔
@Override
public void paint(Graphics g) {
//画画、需要监听鼠标事件
Iterator iterator = points.iterator();
while (iterator.hasNext()) {
Point point = (Point) iterator.next();
g.setColor(Color.red);
g.fillOval(point.x, point.y, 10, 10);
}
}
//添加点到界面上
public void addPaint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标按下 弹起 按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();
//这里我们点击的时候,就会在界面上产生一个点-->画
frame.addPaint(new Point(e.getX(), e.getY()));
//这个点就是鼠标的点
//每次点击鼠标 都需要重写画一遍
frame.repaint();//刷新
}
}
}
窗口监听
演示:窗口监听
package gui;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBackground(Color.BLACK);
setBounds(600,300,600,500);
setVisible(true);
//addWindowListener(new MyWindowListener());
this.addWindowListener(new WindowAdapter() {
//匿名内部类
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
}
});
}
}
键盘监听
演示:键盘监听
package gui;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setBounds(600,300,600,500);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//键盘按下的键是哪一个,当前键盘的码
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP){
System.out.println("你按下了上键");
}
}
});
}
}
Swing
JFrame窗体
package gui;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame{
//初始化
public void init(){
//顶级窗口
JFrame jframe = new JFrame("这是一个JFrame窗口");
jframe.setVisible(true);
jframe.setBounds(600,300,600,500);
jframe.setBackground(Color.BLUE);
//设置文字
JLabel jLabel = new JLabel("欢迎来到Java世界!",SwingConstants.CENTER);
jframe.add(jLabel);
//容器实例化
Container container = this.getContentPane();
container.setBackground(Color.BLUE);
//关闭事件
jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo().init();
}
}
JDialog弹窗
演示:弹窗
package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogDemo extends JFrame {
public DialogDemo(){
this.setVisible(true);
this.setBounds(600,300,600,500);
//JFrame 放东西,需要容器
Container contentPane = this.getContentPane();
//绝对布局
contentPane.setLayout(null);
//按钮
JButton jButton = new JButton("点击弹出一个对话框");
jButton.setBounds(180,150,200,50);
//点击这个按钮的时候,弹出一个弹窗
jButton.addActionListener(new ActionListener() {//监听器
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialogDemo();
}
});
contentPane.add(jButton);
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo(){
this.setVisible(true);
this.setBounds(600,300,100,70);
Container contentPane = this.getContentPane();
Component java = contentPane.add(new Label("java"));
}
}
Icon标签
Icon标签
package gui;
import javax.swing.*;
import java.awt.*;
//图标,需要实现类,Frame集成
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public IconDemo(){}//无参构造
public IconDemo(int width,int height){//有参构造
this.width = width;
this.height = height;
}
public void init(){
IconDemo iconDemo = new IconDemo(15, 15);
//图标放在标签上,也可以放在按钮上!
JLabel jLabel = new JLabel("Icon", iconDemo, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(jLabel);
setVisible(true);
}
public static void main(String[] args) {
new IconDemo().init();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return width;
}
@Override
public int getIconHeight() {
return height;
}
}
文本域JScroll面板
演示:JPanel
package gui;
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
public JPanelDemo(){
Container container = getContentPane();
container.setLayout(new GridLayout(2,1,10,10));//后面参数的意思是间距
JPanel jPanel1 = new JPanel(new GridLayout(1,3));
JPanel jPanel2 = new JPanel(new GridLayout(1,2));
JPanel jPanel3 = new JPanel(new GridLayout(2,1));
JPanel jPanel4 = new JPanel(new GridLayout(2,3));
jPanel1.add(new JButton("1"));
jPanel1.add(new JButton("1"));
jPanel1.add(new JButton("1"));
jPanel2.add(new JButton("2"));
jPanel2.add(new JButton("2"));
jPanel3.add(new JButton("3"));
jPanel3.add(new JButton("3"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
container.add(jPanel1);
container.add(jPanel2);
container.add(jPanel3);
container.add(jPanel4);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args) {
new JPanelDemo();
}
}
演示:JScrollPanel
package gui;
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
public JScrollDemo(){
Container container = getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("欢迎来到Java世界");
container.add(textArea);
//面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
setVisible(true);
setBounds(600,300,600,300);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
图片按钮、单选项、多选框
演示:图片按钮
package gui;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo extends JFrame {
public JButtonDemo() {
Container container = getContentPane();
//讲一个图片变为图标
URL url = JButtonDemo.class.getResource("tour.jpg");
ImageIcon icon = new ImageIcon(url);
//把这个图标放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
//add
container.add(button);
setVisible(true);
setBounds(600,300,600,500);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
演示:单选框
package gui;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo extends JFrame {
public JButtonDemo() {
Container container = getContentPane();
//讲一个图片变为图标
URL url = JButtonDemo.class.getResource("tour.jpg");
ImageIcon icon = new ImageIcon(url);
//单选框
JRadioButton radioButton1 = new JRadioButton("JRadioButton01");
JRadioButton radioButton2 = new JRadioButton("JRadioButton02");
JRadioButton radioButton3 = new JRadioButton("JRadioButton03");
//由于单选框只能选择一个,分组,一个组只能选择一个
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
//add
container.add(radioButton1,BorderLayout.CENTER);
container.add(radioButton2,BorderLayout.NORTH);
container.add(radioButton3,BorderLayout.SOUTH);
setVisible(true);
setBounds(600,300,600,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
演示:多选框
package gui;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo extends JFrame {
public JButtonDemo() {
Container container = getContentPane();
//讲一个图片变为图标
URL url = JButtonDemo.class.getResource("tour.jpg");
ImageIcon icon = new ImageIcon(url);
//多选框
JCheckBox jCheckBox1 = new JCheckBox("jCheckBox1");
JCheckBox jCheckBox2 = new JCheckBox("jCheckBox2");
container.add(jCheckBox1,BorderLayout.NORTH);
container.add(jCheckBox2,BorderLayout.SOUTH);
setVisible(true);
setBounds(600,300,600,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
下拉框、列表框
演示:下拉框
package gui;
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo extends JFrame {
public TestComboboxDemo() {
Container container = getContentPane();
JComboBox status = new JComboBox();
status.addItem (null);
status.addItem ("正在热映");
status.addItem ("已下架");
status.addItem ("即将上映");
container.add (status);
setVisible(true);
setBounds(600,300,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
}
}
演示:列表框
package gui;
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo extends JFrame {
public TestComboboxDemo() {
Container container = getContentPane();
//生成列表的内容
String[] contents = {"1","2","3"};
//列表中需要放入内容
JList jList = new JList(contents);
container.add(jList);
setVisible(true);
setBounds(600,300,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo ();
}
}
文本框、密码框、文本域
演示:文本框
package gui;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo extends JFrame {
public TestTextDemo() {
Container container = getContentPane();
JTextField jTextField1 = new JTextField ("hello");
JTextField jTextField2 = new JTextField ("world",20);
container.add (jTextField1,BorderLayout.NORTH);
container.add (jTextField2,BorderLayout.CENTER);
setVisible(true);
setBounds(600,300,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo();
}
}
演示:密码框
package gui;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo extends JFrame {
public TestTextDemo() {
Container container = getContentPane();
JPasswordField jPasswordField = new JPasswordField ();//默认为****
jPasswordField.setEchoChar('*');
container.add (jPasswordField);
setVisible(true);
setBounds(600,300,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo();
}
}
演示:文本域
package gui;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo extends JFrame {
public TestTextDemo() {
Container container = getContentPane();
JTextArea textArea = new JTextArea (20, 50);
textArea.setText ("欢迎来到Java世界!");
//Scroll
JScrollPane scrollPane = new JScrollPane(textArea);
container.add (scrollPane);
setVisible(true);
setBounds(600,300,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo();
}
}
实战演练:贪吃蛇
StartGame.java
package snake;
import javax.swing.*;
//游戏的主启动类
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new GamePanel());
frame.setBounds(10,10,900,720);
frame.setResizable(false);//窗口大小不可变
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//正常游戏界面应该在面板上!
frame.setVisible(true);
}
}
Data.java
package snake;
import javax.swing.*;
import java.net.URL;
public class Data {
//绝对路径
//头
public static URL headerURL = Data.class.getResource("statics/header5.png");
public static ImageIcon header = new ImageIcon(headerURL);
//上下左右
public static URL leftURL = Data.class.getResource("statics/left.png");
public static URL rightURL = Data.class.getResource("statics/right.png");
public static URL upURL = Data.class.getResource("statics/up.png");
public static URL downURL = Data.class.getResource("statics/down.png");
public static ImageIcon left = new ImageIcon(leftURL);
public static ImageIcon right = new ImageIcon(rightURL);
public static ImageIcon up = new ImageIcon(upURL);
public static ImageIcon down = new ImageIcon(downURL);
//身体
public static URL bodyURL = Data.class.getResource("statics/body.png");
public static ImageIcon body = new ImageIcon(bodyURL);
//食物
public static URL foodURL = Data.class.getResource("statics/food.png");
public static ImageIcon food = new ImageIcon(foodURL);
}
GamePanel.java
package snake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length;//蛇的长度
int[] snakeX = new int[600];//蛇的X坐标 25*25
int[] snakeY = new int[500];//蛇的Y坐标 25*25
String direction;
//食物的坐标
int foodx;
int foody;
Random random = new Random();
int score;//游戏成绩
//游戏当前的状态:开始 停止
boolean isStart = false;//默认是没开始的
//游戏失败的机制
boolean isFail = false;//游戏失败,默认是不失败的
//定时器 以毫秒为单位 1000ms=1s
Timer timer = new Timer(100,this);//100毫秒执行一次
//构造器
public GamePanel() {
init();
//获得焦点和键盘事件
this.setFocusable(true);//获得焦点事件
this.addKeyListener(this);//获得键盘监听事件
timer.start();//游戏一开始,定时器就启动
}
//初始化方法
public void init(){
length= 3;
snakeX[0] = 100;snakeY[0] = 100;//脑袋的坐标
snakeX[1] = 75;snakeY[1] = 100;//第一个身体的坐标
snakeX[2] = 50;snakeY[2] = 100;//第二个身体的坐标
direction ="R";//初始方向为右
//把食物随机分布在界面上
foodx = 25 + 25*random.nextInt(34);
foody = 75 + 25*random.nextInt(24);
score = 0;
}
//绘制面板,游戏中的所有的东西,都使用这个来绘制!
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏
//绘制静态的面板
setBackground(Color.white);
Data.header.paintIcon(this,g,25,11);//头部广告栏
g.fillRect(25,75,850,600);//默认的游戏界面
//画积分
g.setColor(Color.GREEN);
g.setFont(new Font("微软雅黑",Font.BOLD,18));
g.drawString("长度"+length,750,35);
g.drawString("分数"+score,750,55);
//画食物
Data.food.paintIcon(this,g,foodx,foody);
//把小蛇画上去
if (direction.equals("R")){
Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
}else if (direction.equals("L")) {
Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头方向为左
}else if (direction.equals("U")) {
Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头方向为上
}else if (direction.equals("D")) {
Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头方向为下
}
for (int i = 1; i < length; i++) {
Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//身体
}
//游戏状态
if (isStart==false){
g.setColor(Color.white);
//设置字体
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("按下回车开始游戏",300,300);
}
if (isFail){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("失败!按下回车重新开始",300,300);
}
}
//键盘监听事件
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();//获得键盘按键是哪个
if (keyCode == KeyEvent.VK_ENTER){//如果按下的是回车键
if (isFail){
//重新开始
isFail = false;
init();
}else {
isStart = !isStart;//取反
}
}
//小蛇移动
if (keyCode==KeyEvent.VK_UP && direction!="D"){
direction = "U";
}else if (keyCode==KeyEvent.VK_LEFT && direction!="R"){
direction = "L";
}else if (keyCode==KeyEvent.VK_RIGHT && direction!="L"){
direction = "R";
}else if (keyCode==KeyEvent.VK_DOWN && direction!="U"){
direction = "D";
}
}
//事件监听---需要通过固定事件来刷新,一秒十次
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && isFail == false){//如果游戏是开始状态,那么让小蛇运动起来
//吃食物
if (snakeX[0] == foodx && snakeY[0] == foody){
//长度+1,分数+10
length++;
score = score+10;
//再次随机随机生成食物
foodx = 25 + 25*random.nextInt(34);
foody = 75 + 25*random.nextInt(24);
}
//移动
for (int i = length-1; i > 0; i--) {//后一节移到前一节的位置 snakeX[1] = snakeX[0];
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
//走向
if (direction.equals("R")){
snakeX[0] = snakeX[0]+25;
if (snakeX[0]>850){snakeX[0] = 25;}//边界判断
}else if (direction.equals("L")){
snakeX[0] = snakeX[0]-25;
if (snakeX[0]<25){snakeX[0] = 850;}//边界判断
}else if (direction.equals("U")){
snakeY[0] = snakeY[0]-25;
if (snakeY[0]<75){snakeY[0] = 650;}//边界判断
}else if (direction.equals("D")){
snakeY[0] = snakeY[0]+25;
if (snakeY[0]>650){snakeY[0] = 75;}//边界判断
}
//失败判定,撞到自己就算失败
for (int i = 1; i < length; i++) {
if (snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){
isFail = true;
}
}
repaint();
}
timer.start();//定时器开启
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}