onlyxue

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java基础

GUI编程

核心技术:Swing、AWT

现在GUI并不流行 因为其界面不美观、需要依赖jre环境

Swing

public class Demo1 {

    //init();初始化
    public void init() {
        //最大窗口
        JFrame jf = new JFrame("jframe窗口");
        jf.setVisible(true);
        jf.setSize(500,600);

        //设置文字jlable
        JLabel jLabel = new JLabel("欢迎来到java世界");
        jf.add(jLabel);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        //获取一个容器
        Container contentPane = jf.getContentPane();
        contentPane.setBackground(Color.cyan);


        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
         new Demo1().init();
    }
}

弹窗

public class Demo2 {

    public void init(){
        JFrame jf = new JFrame();
        jf.setVisible(true);
        jf.setSize(600,800);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container cp = jf.getContentPane();

        cp.setLayout(null);//绝对布局

        JButton jBut = new JButton("点我");
        jBut.setBounds(20,20,200,100);
        jBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();
            }
        });

        cp.add(jBut);//将按钮放进容器中


    }

    public static void main(String[] args) {
        new Demo2().init();
    }
}

//弹窗窗口
class MyDialog extends JDialog{
    public MyDialog() {
        setVisible(true);
        setBounds(100,100,200,200);

        Container contentPane = getContentPane();
        contentPane.setLayout(null);
        JLabel label = new JLabel("我来带你飞");
        label.setBounds(50,50,100,100);
        contentPane.add(label);
    }
}

Icon 图标

public class Demo3 extends JFrame implements Icon {
    private int width;
    private int height;

    public Demo3()  {
    }

    public Demo3(int width, int height)  {
        this.width = width;
        this.height = height;
    }
    
    public void init() {
        Demo3 d = new Demo3(15,15);
        JLabel icon = new JLabel("icon", d, SwingConstants.CENTER);
        Container contentPane = getContentPane();
        contentPane.add(icon);
        setVisible(true);
        setSize(200,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public void setIcon() {
        JLabel icon2 = new JLabel("image",SwingConstants.CENTER);
        URL url = this.getClass().getResource("ico.png");
        ImageIcon imageIcon = new ImageIcon(url);
        icon2.setIcon(imageIcon);
        Container contentPane = getContentPane();
        contentPane.add(icon2);
        setVisible(true);
        setSize(200,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


    public static void main(String[] args) {
//        new Demo3().init();
        new Demo3().setIcon();
    }

    @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;
    }
}

面板

public class Demo4 extends JFrame {
    public Demo4() {
        Container contentPane = getContentPane();
        contentPane.setLayout(new GridLayout(2,1,10,10));

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1,3));
        contentPane.add(panel);

        panel.add(new JButton("1"));
        panel.add(new JButton("2"));
        panel.add(new JButton("3"));

        contentPane.add(panel);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(300,400);
    }

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

}
public class Demo5 extends JFrame {
    public Demo5(){
        Container contentPane = getContentPane();

        JTextArea jTextArea = new JTextArea(20, 50);
        Scanner scanner = new Scanner(System.in);
        String str= scanner.toString();
        jTextArea.setText(str);

        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        contentPane.add(jScrollPane);


        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500,400);

    }

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

}

单选、多选

public class Demo6 extends JFrame {
    public Demo6(){
//        Container container = getContentPane();
//
//        URL url = Demo6.class.getResource("ico.png");
//        ImageIcon icon = new ImageIcon(url);
//
//        JButton jButton = new JButton();
//        jButton.setSize(55,55);
//        jButton.setIcon(icon);
//        jButton.setToolTipText("我是提示");
//
//        container.add(jButton);
//
//        setVisible(true);
//        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//        setSize(400,500);
    }


    public void init(){
        Container container = getContentPane();

        URL url = Demo6.class.getResource("ico.png");
        ImageIcon icon = new ImageIcon(url);

        //单选框
        JRadioButton jRadioButton1 = new JRadioButton("jRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("jRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("jRadioButton3");

        //分组 将按钮放入组内 一个组只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(jRadioButton1);
        group.add(jRadioButton2);
        group.add(jRadioButton3);


        container.add(jRadioButton1,BorderLayout.SOUTH);
        container.add(jRadioButton2,BorderLayout.CENTER);
        container.add(jRadioButton3,BorderLayout.NORTH);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400,500);
    }

    public void init2(){
        Container container = getContentPane();

        URL url = Demo6.class.getResource("ico.png");
        ImageIcon icon = new ImageIcon(url);

        //多选
        JCheckBox checkBox1 = new JCheckBox("checkBox1");
        JCheckBox checkBox2 = new JCheckBox("checkBox1");
        JCheckBox checkBox3 = new JCheckBox("checkBox1");

        container.add(checkBox1,BorderLayout.NORTH);
        container.add(checkBox2,BorderLayout.CENTER);
        container.add(checkBox3,BorderLayout.SOUTH);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400,500);
    }

    public static void main(String[] args) {
        new Demo6().init2();
    }
}

下拉、列表

public class Demo7 extends JFrame {
     public Demo7() {

     }

     public void init() {
         Container container = getContentPane();

         //下拉框
         JComboBox<Object> box = new JComboBox<>();
         box.addItem("黑");
         box.addItem("白");
         box.addItem("黄");
         box.addItem("红");

         container.add(box);

         setVisible(true);
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         setSize(400,500);
     }

    public void init2() {
        Container container = getContentPane();
        String[] strings = {"1","2","3","4"}; //固定添加

        //列表框
        Vector objs = new Vector();
        objs.add(1);
        objs.add("2");
        objs.add("DNF");
        objs.add(234);

        JList jList = new JList(objs);



        container.add(jList);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400,500);
    }

    public static void main(String[] args) {
        new Demo7().init2();
    }
}

文本框

public class Demo8 extends JFrame {
    public void init1(){
        Container container = getContentPane();

        //文本框
        JTextField textField1 = new JTextField("nihao");
        TextField tf = new TextField();
        JTextField textField2 = new JTextField("java");
        tf.setEchoChar('*');//伪密码框效果


        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');//密码显示样式更改

        container.add(textField1,BorderLayout.SOUTH);
        container.add(textField2,BorderLayout.NORTH);
        container.add(passwordField,BorderLayout.CENTER);
        container.add(tf,BorderLayout.WEST);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400,500);
    }

    public static void main(String[] args) {
        new Demo8().init1();
    }
}

贪吃蛇小游戏

/**
 * 游戏面板
 */
public  class GamePanel extends JPanel implements KeyListener, ActionListener {

    //定义🐍的数据结构
    int length;
    int[] snakeX = new int[600];//x坐标
    int[] snakeY = new int[500];//y坐标
    String drec;//初始方向

    //食物的坐标
    int foodX;
    int foodY;
    Random random = new Random();
    int score;//成绩

    boolean isStart = false;//游戏开始状态
    boolean isFail = false;//游戏失败状态

    Timer timer = new Timer(100,this);//100毫秒执行一次

    public GamePanel(){
        init();
        setFocusable(true);//获取焦点和键盘事件
        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;
        drec = "right";
        score=0;

        //食物初始随机位置
        foodX = 25+25*random.nextInt(34);
        foodY = 75+25*random.nextInt(24);

    }

    //绘制游戏面板
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏幕
        this.setBackground(Color.BLACK);
        Date.header.paintIcon(this,g,25,11);//头部广告栏
        g.fillRect(25,75,850,600);//默认游戏界面

        //画小蛇
        if (drec.equals("right")) {
            Date.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        } else if (drec.equals("left")){
            Date.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        } else if (drec.equals("up")) {
            Date.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        } else if (drec.equals("down")) {
            Date.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }

        //游戏开始状态
        if (isStart==false) {
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体
            g.drawString("按下空格开始游戏",300,300);//添加文字
        }

        //游戏失败状态
        if (isFail==true){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体
            g.drawString("游戏失败,按下空格重新开始",300,300);//添加文字
        }

        //画上身体
        for (int i = 1;i<length;i++) {
            Date.body.paintIcon(this,g,snakeX[i],snakeY[i]);//身体
        }

        //画上食物
        Date.food.paintIcon(this,g,foodX,foodY);
        //画上积分
        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,20));//设置字体
        g.drawString("分数 "+score,750,30);//添加文字
        g.drawString("长度 "+length,750,50);//添加文字


    }


    @Override
    public void keyTyped(KeyEvent e) {

    }

    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_SPACE){
            if (isFail){
                isFail = false;
                init();
            } else {
                isStart  = !isStart;//取反
            }
            repaint();
        }


        if (keyCode == KeyEvent.VK_UP){
            drec = "up";

        } else if (keyCode == KeyEvent.VK_DOWN) {
            drec = "down";
            
        } else if (keyCode == KeyEvent.VK_LEFT) {
            drec = "left";

        } else if (keyCode == KeyEvent.VK_RIGHT) {
            drec = "right";

        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }


    //事件监听--通过固定事件来刷新
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isFail == false){
            //移动
            for (int i = length-1;i>0;i--){
                snakeX[i] = snakeX[i-1]; //向前移动一节
                snakeY[i] = snakeY[i-1];
            }
            if (drec.equals("right")){
                snakeX[0] = snakeX[0]+25;
                if (snakeX[0]>850){ //撞到边界就回来
                    snakeX[0]=25;
                }


            } else if (drec.equals("left")) {
                snakeX[0] = snakeX[0]-25;
                if (snakeX[0]<25){ //撞到边界就回来
                    snakeX[0]=850;
                }

            } else if (drec.equals("up")) {
                snakeY[0] -=25;
                if (snakeY[0]<75){ //撞到边界就回来
                    snakeY[0]=650;
                }
            } else if (drec.equals("down")) {
                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;
                }
            }

            //吃食物
            if (snakeX[0]==foodX && snakeY[0]==foodY){
                length++;//长度+1
                score++; //分数+1
                //再次随机生成食物
                foodX = 25+25*random.nextInt(34);
                foodY = 75+25*random.nextInt(24);
            }

            repaint();//重画

        }

        timer.start();
    }
}


/**
 * 数据层
 */
public class Data {
    public static URL headerUrl = Data.class.getResource("images/header.png");
    public static ImageIcon header = new ImageIcon(headerUrl);

    public static URL upUrl = Data.class.getResource("images/up.png");
    public static ImageIcon up = new ImageIcon(upUrl);

    public static URL downUrl = Data.class.getResource("images/down.png");
    public static ImageIcon down = new ImageIcon(downUrl);

    public static URL leftUrl = Data.class.getResource("images/left.png");
    public static ImageIcon left = new ImageIcon(leftUrl);

    public static URL rightUrl = Data.class.getResource("images/right.png");
    public static ImageIcon right = new ImageIcon(rightUrl);

    public static URL bodyUrl = Data.class.getResource("images/body.png");
    public static ImageIcon body = new ImageIcon(bodyUrl);

    public static URL foodUrl = Data.class.getResource("images/food.png");
    public static ImageIcon food = new ImageIcon(foodUrl);



}


//main方法
public class StartGame {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame();

        jFrame.add(new GamePanel(),BorderLayout.CENTER);

        jFrame.setBounds(10,10,900,720);
        jFrame.setResizable(false);//窗口大小不可变
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

图片素材链接:https://pan.baidu.com/s/1b8vL6AJqlmROFe_kB7oohw
提取码:f7yt

posted on 2022-11-01 16:23  守望在路上  阅读(22)  评论(0)    收藏  举报