# java swing,awt图形化界面代码案例合集

文章目录

  • java awt,swing图形化界面代码案例合集

java awt,swing图形化界面代码案例合集

package Demo1;
import java.awt.*;
public class Demo1 {
    public static void main(String[] args) {
        //创建一个窗口对象
        Frame frame = new Frame("这里测试windows窗口");
        //指定窗口位置,大小
        frame.setLocation(100,100);
        frame.setSize(500,300);
        //色值窗口可见
        frame.setVisible(true);
    }
}
package Demo1;

import java.awt.*;

public class Demo2 {
    public static void main(String[] args) {
   Frame frame = new Frame("计算器");
   //1.创建一个panel对象,里面存放一个textFiled组件
  Panel p = new Panel();
  p.add(new TextField(30));
  //2.把当前panel添加到frame的北边区域
        frame.add(p,BorderLayout.NORTH);
        //3.创建一个panel对象,并且设置他的布局管理为Gridlayout
        Panel p2 = new Panel();
        p2.setLayout(new GridLayout(3,3,4,4));
        for (int i = 0; i < 10; i++) {
            p2.add(new Button(i+""));
        }
        p2.add(new Button("+"));
        p2.add(new Button("-"));
        p2.add(new Button("*"));
        p2.add(new Button("/"));
        //5.把当前panel添加到frame中
        frame.add(p2);
    frame.pack();
    frame.setVisible(true);
    }
}
package Demo1;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.charset.UnmappableCharacterException;

public class Demo3 {
    public static void main(String[] args) {


        Frame frame = new Frame("这里测试cardlayout");
        //1.创建一个panel,用来存储多个卡片
        Panel p1 = new Panel();
        //2.创建Cardlayout对象,并且把该对象设置给之前创建的容器
        CardLayout cardLayout = new CardLayout();
        p1.setLayout(cardLayout);
        //3.往panel中存储多个组件
String[] names ={"A","B","C","D","E"};
        for (int i = 0; i <names.length; i++) {
p1.add(names[i],new Button(names[i]));
        }
        //4.把panel放到frame的中间区域
        frame.add(p1);
        //5. 创建另外一个panel,p2,用来存储多个按钮组件
Panel p2 = new Panel();
        //6.创建5个按钮组件
Button b1 = new Button("privious");
Button b2 = new Button("next");
Button b3 = new Button("first");
Button b4 = new Button("last");
Button b5 = new Button("third");
        //7.创建一个事件监听器,监听按钮的点击动作
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String actionCommand = e.getActionCommand();//这个字符就是按钮上的文字
            switch (actionCommand){
                case"privious":
                    cardLayout.previous(p1);
                 break;
                case"next":
                    cardLayout.next(p1);
                   break;
                 case"first":
                     cardLayout.first(p1);
                    break;
                case"last":
                    cardLayout.last(p1);
                    break;
                case "third":
                    cardLayout.show(p1,"C");
                    break;
            }
            }
        };
        //8.把当前这个事件监听器和多个按钮绑定到一起
b1.addActionListener(listener);
b2.addActionListener(listener);
b3.addActionListener(listener);
b4.addActionListener(listener);
b5.addActionListener(listener);
        //9.把按钮添加到容器p2中
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
        //10。把p2放在frame的南边区域
        frame.add(p2,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }
}
package Demo1;

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

public class Demo4 {
    public static void main(String[] args){
        Frame frame = new Frame();
        //1.基于frame,创建一个boxlayout对象,并且垂直放置
        BoxLayout boxlayout = new BoxLayout(frame,BoxLayout.X_AXIS);
        //2.把Boxlayout设置给Frame
        frame.setLayout(boxlayout);
        //3.往frame中添加两个组件
        frame.add(new Button("button1"));
        frame.add(new Button("button2"));
        frame.pack();
        frame.setVisible(true);
    }
}
package Demo1;

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

public class Demo5 {
    public static void main(String[] args) {
        Frame frame = new Frame("test");
        //1.创建一个水平排列的box容器
      Box b1 = Box.createHorizontalBox();
        //2.往容器里面添加两个按钮
  b1.add(new Button("button1"));
  b1.add(new Button("button2"));
  //3.创建一个垂直排列的容器
       Box b2 = Box.createVerticalBox();
        //4.往容器里面添加两个按钮
        b2.add(new Button("buttonA"));
        b2.add(new Button("buttonB"));
        //5.吧Box放入frame中
        frame.add(b1,BorderLayout.SOUTH);
        frame.add(b2,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
    }
}
package Demo1;
import javax.swing.*;
import java.awt.*;
public class Demo6 {
    Frame frame = new Frame("这里测试基本组件");

    //定义一个按钮
    Button ok = new Button("确认");

    //定义一个复选框组
    CheckboxGroup cbg = new CheckboxGroup();
    //定义一个单选框,初始处于被选中状态,并添加到cbg组中
    Checkbox male = new Checkbox("男", cbg, true);

    //定义一个单选框,初始处于未被选中状态,并添加到cbg组中
    Checkbox female = new Checkbox("女", cbg, false);

    //定义一个复选框,初始处于未被选中状态
    Checkbox married = new Checkbox("是否已婚?", false);

    //定义一个下拉选择框
    Choice colorChooser = new Choice();

    //定义一个列表选择框
    List colorList = new List(6, true);

    //定义一个5行,20列的多行文本域
    TextArea ta = new TextArea(5, 20);

    //定义一个50列的单行文本域
    TextField tf = new TextField(50);

    public void init() {
        //往下拉选择框中添加内容
        colorChooser.add("红色");
        colorChooser.add("绿色");
        colorChooser.add("蓝色");

        //往列表选择框中添加内容
        colorList.add("红色");
        colorList.add("绿色");
        colorList.add("蓝色");

        //创建一个装载按钮和文本框的Panel容器
        Panel bottom = new Panel();
        bottom.add(tf);
        bottom.add(ok);

        //把bottom添加到Frame的底部
        frame.add(bottom,BorderLayout.SOUTH);

        //创建一个Panel容器,装载下拉选择框,单选框和复选框
        Panel checkPanel = new Panel();
        checkPanel.add(colorChooser);
        checkPanel.add(male);
        checkPanel.add(female);
        checkPanel.add(married);

        //创建一个垂直排列的Box容器,装载 多行文本域和checkPanel
        Box topLeft = Box.createVerticalBox();
        topLeft.add(ta);
        topLeft.add(checkPanel);

        //创建一个水平排列的Box容器,装载topLeft和列表选择框
        Box top = Box.createHorizontalBox();
        top.add(topLeft);
        top.add(colorList);

        //将top添加到frame的中间区域
        frame.add(top);


        //设置frame最佳大小并可见
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        new Demo6().init();

    }
}
package Demo1;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo7 {
    Frame frame =new Frame("test");
    TextField tf = new TextField("30");
    Button ok = new Button("ok");
    public void init(){
        //组装视图
        //监听视图
//        MyLister myLister = new MyLister();
        //注册监听
        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tf.setText("hello pofen");
            }
        });
        //把tf和ok放入frame
        frame.add(tf,BorderLayout.NORTH);
        frame.add(ok,BorderLayout.SOUTH);
        frame.pack();
frame.setVisible(true);
    }
//    private class MyLister implements  ActionListener{
//
//        @Override
//        public void actionPerformed(ActionEvent e) {
//            tf.setText("hello pofen");
//        }
//    }

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

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Demo8 {
    private Frame frame = new Frame("test pofen");

//创建菜单条
        MenuBar menuBar = new MenuBar();
        //创建菜单组件
        Menu filemenu = new Menu("文件");
        Menu editMenu = new Menu("编辑");
        Menu formatMenu = new Menu("格式");
        //菜单项组件
        MenuItem auto = new MenuItem("自动换行");
        MenuItem copy =new MenuItem("复制");
        MenuItem paste =new MenuItem("粘贴");
        MenuItem comment =new MenuItem("注释 ctrl+shift+q",new MenuShortcut(KeyEvent.VK_Q,
                true));//关联款快捷键
        MenuItem canceComment = new MenuItem("取消注释");
TextArea textArea = new TextArea(6,40);
    public void init(){
//组装视图
comment.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.print("ok : ");
        textArea.append("你点了菜单项  "+ e.getActionCommand());
    }
});
formatMenu.add(comment);
formatMenu.add(canceComment);
editMenu.add(auto);
editMenu.add(copy);
editMenu.add(paste);
editMenu.add(formatMenu);
//组装菜单条
        menuBar.add(filemenu);
        menuBar.add(editMenu);
//把菜单条放入到framen中
        menuBar.add(filemenu);
        frame.setMenuBar(menuBar);
        //设置frame最佳大小并且可见
        frame.pack();
        frame.setVisible(true);
    }

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

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Demo9 {
    private Frame frame = new Frame("test pofen");

    //创建菜单条
    MenuBar menuBar = new MenuBar();
    //创建菜单组件
    Menu filemenu = new Menu("文件");
    Menu editMenu = new Menu("编辑");
    Menu formatMenu = new Menu("格式");
    //菜单项组件
    MenuItem auto = new MenuItem("自动换行");
    MenuItem copy =new MenuItem("复制");
    MenuItem paste =new MenuItem("粘贴");
    MenuItem comment =new MenuItem("注释 ",new MenuShortcut(KeyEvent.VK_Q,
            true));//关联款快捷键
    MenuItem canceComment = new MenuItem("取消注释");
    TextArea textArea = new TextArea(6,40);
    public void init(){
//组装视图
        comment.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.print("ok : ");
                textArea.append("你点了菜单项  "+ e.getActionCommand()+"\n");
            }
        });
        formatMenu.add(comment);
        formatMenu.add(canceComment);
        editMenu.add(auto);
        editMenu.add(copy);
        editMenu.add(paste);
        editMenu.add(formatMenu);
//组装菜单条
        menuBar.add(filemenu);
        menuBar.add(editMenu);
//把菜单条放入到framen中
        frame.setMenuBar(menuBar);
        frame.add(textArea);
        //设置frame最佳大小并且可见
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Demo9().init();
    }
}
package Demo1;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo10 {
    Frame frame =new Frame("这里测试绘图");
private  final String RECT_SHAPE="rect";
private  final String OVAL_SHAPE="oval";
Button buttonReact = new Button("绘制矩形");
Button buttonOval = new Button("绘制椭圆");
//定义一个变量,记录当前绘制椭圆还是矩形
    private String shape = "";
//自定义类,继承canvas类,重写paint(Grapics g)方法完成画图·
    private  class MyCanvas extends Canvas{
        @Override
    public void paint(Graphics g){
            //绘制不同的图形
            if(shape.equals(RECT_SHAPE)){
                g.setColor(Color.black);//设置画笔的颜色为黑色
                g.drawRect(100,100,150,100);
                //绘制矩形
            }else if(shape.equals(OVAL_SHAPE)){
                g.setColor(Color.RED);
                g.drawOval(100,100,150,100);
                //绘制椭圆
            }
        }
}
//创建自定义的画布对象
    MyCanvas drawArea = new MyCanvas();
public void init(){
    //组装视图
    buttonReact.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //修改标记的值为rect

            shape = RECT_SHAPE;
            drawArea.repaint();
        }
    });
    buttonOval.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            shape = OVAL_SHAPE;
            drawArea.repaint();
        }
    });
    //panel承载按钮
    Panel p = new Panel();
    p.add(buttonOval);
    p.add(buttonReact);
    frame.add(p,BorderLayout.SOUTH);
    //drawArea的大小需要设置
    drawArea.setPreferredSize(new Dimension(300,300));
    frame.add(drawArea);
    frame.pack();
    frame.setVisible(true);

}

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

import javax.security.auth.kerberos.KerberosKey;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
public class Demo11 {
    int sum = -1;
    //创建窗口对象
    private Frame frame = new Frame("弹球游戏");
    //桌面宽度,高度
    private final int TABLE_WIDTH = 400;
    private final int TABLE_HEIGHT = 400;
    //球拍的高度和宽度
    private final int RACKET_WIDTH = 60;
    private final int RACKET_HEIGHT = 10;
    //小球的大小
    private final int BALL_SIZE = 16;
    //定义变量。记录小球的坐标
    private int ballX = 120;
    private int ballY = 20;
    //定义变量。记录小球在xy方向分别移动的速度
    private int speedY = 10;
    private int speedX = 5;
    //定义变量记录球拍的坐标
    private int racketX = 120;
    private  int racketY = 340;
    //定义一个变量,标识当前游戏是否已经结束
    private boolean isOver = false;
    //声明一个定时器
    private Timer timer;


    //自定义一个类,继承canvas,充当画布
    private class myCanvas extends Canvas {
        @Override
        public void paint(Graphics g) {
            //这里绘制内容
            //游戏结束
            if (isOver) {
                g.setColor(Color.BLUE);
                g.setFont(new Font("Timew", Font.BOLD, 30));
                g.drawString("游戏结束!,你一共成功了"+sum+"次", 50, 200);
            } else {
                //游戏中
                //绘制球
                g.setColor(Color.RED);
                g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
                //绘制球拍
                g.setColor(Color.PINK);
                g.fillRect(racketX, racketY, RACKET_WIDTH, RACKET_HEIGHT);
            }
        }
    }

    //创建绘制区域
    myCanvas drawArea = new myCanvas();

    public void init() {
        //组装视图以及游戏逻辑的控制
        //完成球拍坐标的变化
        KeyListener keyListener = new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_LEFT) {
                    //应该向左移动
                    if (racketX >= 10) {
                        racketX -= 20;
                    }
                }
                if (keyCode == KeyEvent.VK_RIGHT) {
                    //应该向右移动
                    if (racketX < TABLE_WIDTH - RACKET_WIDTH) {
                        racketX += 20;
                    }
                }
                if (keyCode == KeyEvent.VK_UP) {
                    //应该向右移动
                        racketY -= 20;
                    }
                }

        };
        //给Frame和drawarea注册监听器
        frame.addKeyListener(keyListener);
        drawArea.addKeyListener(keyListener);
        //小球坐标的控制
        ActionListener task = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(ballX<=0||ballX>=TABLE_WIDTH+BALL_SIZE){
                    speedX=-speedX;
                }
                if(ballY<=0||(ballY>=racketY-BALL_SIZE&&ballX>racketX&&ballX<racketX+RACKET_WIDTH)){
                    speedY=-speedY;
                    sum = sum+1;
                }
                if(ballY>racketY-BALL_SIZE&&(ballX<racketX || ballX> racketX+RACKET_WIDTH)){
                    //小球超出了球拍范围,结束游戏
                    timer.stop();
                    isOver=true;
                    //重新绘制界面
                    drawArea.repaint();
                    //停止定时器

                }
                //根据边界范围修正速度
                //更新小球的坐标,重新绘制界面
                ballX-=speedX;
                ballY+=speedY;
                drawArea.repaint();

            }
        };
        timer = new Timer(100,task);
        timer.start();
        drawArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
        frame.add((drawArea));
        //设置frame的大小,并且可视
        frame.pack();
        frame.setVisible(true);
        }

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

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

public class Demo12 {
 JFrame f = new JFrame("Swing基本组件的测试");

 //声明菜单相关组件
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenue = new JMenu("文件");
    JMenu editMenue = new JMenu("编辑");
    JMenuItem auto = new JMenuItem("自动换行");
    JMenuItem copy = new JMenuItem("复制");
    JMenuItem paste = new JMenuItem("粘贴");
    JMenu formatMenu = new JMenu("格式");
    JMenuItem comment = new JMenuItem("注释");
    JMenuItem cancelcomment = new JMenuItem("取消注释");
    //声明文本域
    JTextArea ta = new JTextArea(8,20);
    String[] colorsList ={"红色","绿色","蓝色"};
    //声明列表框
    JList<String> colorList = new JList<String>(colorsList);
     //声明选择组件
    JComboBox<String> colorSelect = new JComboBox<String>();
    ButtonGroup bg = new ButtonGroup();
    JRadioButton male = new JRadioButton("男",false);
    JRadioButton female = new JRadioButton("男",true);
    JCheckBox isMarried = new JCheckBox("是否已婚?",true);
    //声明底部
    JTextField tf = new JTextField(40);
    JButton ok = new JButton("确定",new ImageIcon("Code2\\img\\1.jpg"));
    //声明右键菜单
    JPopupMenu jPopupMenu = new JPopupMenu();
    ButtonGroup poupButtonBg = new ButtonGroup();
    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("metal 风格");
    JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("nimbus 风格");
    JRadioButtonMenuItem wiodowsItem = new JRadioButtonMenuItem("wiodows 风格");
    JRadioButtonMenuItem wiodowsClassItem = new JRadioButtonMenuItem("wiodows 经典风格");
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("mmotif 风格");
//初始化界面
 public void init(){
     //组装视图

     //组装底部
     JPanel bottonPanel = new JPanel();
     bottonPanel.add(tf);
     bottonPanel.add(ok);
     f.add(bottonPanel,BorderLayout.SOUTH);
     //组装选择相关的组件
     JPanel selectPanle = new JPanel();
     colorSelect.addItem("红色");
     colorSelect.addItem("绿色");
     colorSelect.addItem("蓝色");
     selectPanle.add(colorSelect);
     bg.add(male);
     bg.add(female);
     selectPanle.add(male);
     selectPanle.add(female);
     selectPanle.add(isMarried);
     //组装文本域和选择相关组件
      Box topleft = Box.createVerticalBox();
      topleft.add(ta);
      topleft.add(selectPanle);
      //组装顶部
     Box top = Box.createHorizontalBox();
     top.add(topleft);
     top.add(colorList);
     f.add(top);
     //组装顶部菜单
     formatMenu.add(comment);
     formatMenu.add(cancelcomment);
     editMenue.add(auto);
     editMenue.addSeparator();
     editMenue.add(formatMenu);
     editMenue.add(copy);
     editMenue.add(paste);
     menuBar.add(fileMenue);
     menuBar.add(editMenue);
     f.setJMenuBar(menuBar);
     //组装右键菜单
     poupButtonBg.add(metalItem);
     poupButtonBg.add(nimbusItem);
     poupButtonBg.add(wiodowsItem);
     poupButtonBg.add(wiodowsClassItem);
     poupButtonBg.add(motifItem);
     poupButtonBg.add(metalItem);
     //不需要在监听鼠标事件了
     ta.setComponentPopupMenu(jPopupMenu);
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     f.pack();
     f.setVisible(true);

 }

    public static void main(String[] args) {
         new Demo12().init();
    }
    //定义一个方法,用于改变界面风格
}
package Demo1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Demo13 {
    JFrame jf = new JFrame("测试工具条");
    JTextArea jta = new JTextArea(6,3);
    //声明工具条相关内容
    JToolBar jToolBar = new JToolBar("播放工具条",SwingConstants.HORIZONTAL);
//创建3个acction、对象
    //传递的参数,name和icon。最终添加到工具条中
    Action pre = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        jta.append("上一曲.\n");
    }
};
    Action pause = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("暂停.\n");
        }
    };
    Action next = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("下一曲.\n");
        }
    };
    public void init(){
        //通过acction创建button
        JButton prebtn = new JButton(pre);
        JButton pausebtn = new JButton(pause);
        JButton nextbtn = new JButton(next);
        //组装视图
//        jToolBar.add(pre);
//        jToolBar.addSeparator();
//        jToolBar.add(pause);
//        jToolBar.addSeparator();
//        jToolBar.add(next);
        jToolBar.add(prebtn);
        jToolBar.addSeparator();
        jToolBar.add(pausebtn);
        jToolBar.addSeparator();
        jToolBar.add(nextbtn);
        jToolBar.setFloatable(true);

        //文本框默认不支持滚动
//        //把一个组件设置到jcrolpane中,那么该组件就支持滚动条了
//        JScrollBar jScrollBar = new JScrollBar(jta);
//        jf.add(jScrollBar);
        jf.add(jToolBar,BorderLayout.NORTH);
        jf.add(jta);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.pack();
    jf.setVisible(true);
}

    public static void main(String[] args) {
    new Demo13().init();
    }
}
package Demo1;
import  java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class Demo14 {
    JFrame jFrame = new JFrame("测试颜色选择器");
    JTextArea jta = new JTextArea("我是pofen",6,30);
    JButton btn = new JButton(new AbstractAction("change text color") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //弹出颜色选择器
            Color result = JColorChooser.showDialog(jFrame,"颜色选择器",Color.white);
            //修改文本框北京
            jta.setBackground(result);
        }
    });
    public void init(){
        jFrame.add(jta);
        jFrame.add(btn,BorderLayout.SOUTH);

        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.pack();
        jFrame.setVisible(true);

    }

    public static void main(String[] args) {
        new Demo14().init();
    }
}
package Demo1;
import javax.imageio.ImageIO;
import  javax.swing.*;
import  java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Demo15 {
    JFrame jf = new JFrame("文件选择器");
    JMenuBar jmb = new JMenuBar();
    JMenu jmenu = new JMenu("file");
    JMenuItem open = new JMenuItem(new AbstractAction("打开") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件显示器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showOpenDialog(jf);
            //获取选择的文件
            File file = fileChooser.getSelectedFile();
            //进行显示
            try {
                image = ImageIO.read(file);
                drawArea.repaint();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    });
    JMenuItem save = new JMenuItem(new AbstractAction("protect") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件显示器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showOpenDialog(jf);
            //获取选择的保存文件路径
            File file = fileChooser.getSelectedFile();
            try {
                ImageIO.write(image,"jpeg",file);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            //进行显示
            try {
                image = ImageIO.read(file);
                drawArea.repaint();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    });
    BufferedImage image;
    private  class MyCanvas extends JPanel{
        //swing提供的组件都使用了图片缓冲技术
        @Override
        public void paint(Graphics g) {
            //把图片绘制到插件上
            g.drawImage(image,0,0,null);
        }
    }
    MyCanvas drawArea = new MyCanvas();
    public void init(){
      jmenu.add(open);
      jmenu.add(save);
      jmb.add(jmenu);
      jf.setJMenuBar(jmb);
      drawArea.setPreferredSize(new Dimension(740,500));
      jf.add(drawArea);
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jf.pack();
      jf.setVisible(true);
    }

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

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

public class Demo16 {
    JFrame jf = new JFrame("测试消息对话框");
    JTextArea jta = new JTextArea(6,30);
    JButton btn = new JButton(new AbstractAction("弹出消息对话框") {
        @Override
        public void actionPerformed(ActionEvent e) {
//弹出一个文本框,显示文本域中输入的内容
String text = " 你输入了   :"+jta.getText();
//JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.INFORMATION_MESSAGE);
//JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.WARNING_MESSAGE);
//JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.PLAIN_MESSAGE);

        }
    });
    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);
        //组装视图

       jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       jf.pack();
       jf.setVisible(true);
    }

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

import com.sun.jdi.PathSearchingVirtualMachine;

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

public class Demo17 {
    JFrame jf = new JFrame("测试确认对话框");
    JTextArea jta = new JTextArea(15,30);
JButton btn = new JButton(new AbstractAction("弹出确认消息对话框") {
    @Override
    public void actionPerformed(ActionEvent e) {
   String text = jta.getText();
  int result = JOptionPane.showConfirmDialog(jf,text,"确认对话框",JOptionPane.YES_NO_CANCEL_OPTION);
jta.append("\n");
  if(result==JOptionPane.YES_OPTION){
        jta.append("用户点击了 是 按钮\n");
    }
        if(result==JOptionPane.NO_OPTION){
            jta.append("用户点击了 否 按钮\n");
        }

//        if(result==JOptionPane.OK_OPTION){
//            jta.append("用户点击了 确认 按钮\n");
//        }
        if(result==JOptionPane.CANCEL_OPTION){
            jta.append("用户点击了 取消 按钮\n");
        }


    }
});
public void init(){
    jf.add(jta);
jf.add(btn, BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}

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

import com.sun.jdi.PathSearchingVirtualMachine;

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

public class Demo18 {
    JFrame jf = new JFrame("测试输入对话框");
    JTextArea jta = new JTextArea(15,30);
    JButton btn = new JButton(new AbstractAction("弹出输入消息对话框") {
        @Override
        public void actionPerformed(ActionEvent e) {
           String result =  JOptionPane.showInputDialog(jf, "请填写你的银行卡账号", "输入对话框", JOptionPane.INFORMATION_MESSAGE);
       jta.append(result);
        }
        });
    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

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

import com.sun.jdi.PathSearchingVirtualMachine;

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

public class Demo19 {
    JFrame jf = new JFrame("测试选项对话框");
    JTextArea jta = new JTextArea(15,30);
    JButton btn = new JButton(new AbstractAction("弹出选项消息对话框") {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("\n");
 int result =JOptionPane.showOptionDialog(jf,"选择尿不湿号码","选项对话框",JOptionPane.DEFAULT_OPTION,
        JOptionPane.INFORMATION_MESSAGE,null,new String[]{"大号","中号","小号"},"中号");
 switch (result){
     case 0:
         jta.append("用户选择了大号");
         break;
     case 1 :
         jta.append("用户选择了中号");
         break;
     case 2 :
         jta.append("用户选择了小号");
         break;
 }
        }
    });
    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

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

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicButtonListener;

public class Demo20 {
    int i =0;
    JFrame jf = new JFrame("测试JTabledPane");
JTabbedPane jTabbedPane = new JTabbedPane(SwingConstants.LEFT,JTabbedPane.SCROLL_TAB_LAYOUT);
    public void init(){


        //添加标签
        jTabbedPane.addTab("用户管理",new ImageIcon("\\img\\1.jpg"),new JList<String>(new String[]{"商品一","商品二","商品三"}));
        jTabbedPane.addTab("用户管理",new JList<String>(new String[]{"用户一","用户二","用户三"}));
        jTabbedPane.addTab("用户管理",new ImageIcon("\\img\\2.jpg"),new JList<String>(new String[]{"订单一","订单二","订单三","订单4"}));
        //完成设置
        jTabbedPane.setEnabledAt(0,false);
        jTabbedPane.setSelectedIndex(1);
        //监听当前选中情况
        jTabbedPane.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                int selectedIndex=jTabbedPane.getSelectedIndex();
                JOptionPane.showMessageDialog(jf,"当前选中了第:"+(selectedIndex+1)+"个标签");
                i++;
                System.out.println("ok pofen"+i);
            }
        });

        jf.add(jTabbedPane);
        //设置窗口位置大小
        jf.setBounds(400,400,400,400);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }
    public static void main(String[] args){
        new Demo20().init();
    }
}
package Demo1;

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

public class Demo21 {
    JFrame jf  = new JFrame("测试进度条");
    JCheckBox indeterminate = new JCheckBox("不确定进度");
    JCheckBox noBorder= new JCheckBox("不绘制边框");
    //创建进度条
    JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL,0,100);

    public void init(){
        //组装视图

        //处理复选框行为
indeterminate.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取有没有选中
      boolean select =  indeterminate.isSelected();
      //设置不确定进度
      bar.setIndeterminate(select);
      bar.setStringPainted(!select);
    }
});
noBorder.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        boolean selected = noBorder.isSelected();
        bar.setStringPainted(!selected);
    }
});
Box box = Box.createVerticalBox();
box.add(indeterminate);
box.add(noBorder);
//设置进度条属性
        bar.setStringPainted(true);//百分百
        bar.setBorderPainted(true);//边框
        jf.setLayout(new FlowLayout());
        jf.add(box);
        jf.add(bar);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
        //通过模拟循环修改进度条的精度
        for (int i = 0; i <=100; i++) {
            //修改已经完成的工作量
            bar.setValue(i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import java.util.Vector;

public class Demo22 {
    JFrame jf =new JFrame("列表测试框");
    String[] books = {"java自学宝典","轻量级javaee企业应用实战","Android基础教程",
    "Jquery实战教程","spriingboot企业级开发"};
    //定义 布局选择按钮,所在的面板
    JPanel layoutPanel = new JPanel();
    ButtonGroup layoutgroup = new ButtonGroup();
    //定义 选择模式按钮,所在面板
    JPanel selectModelPanel = new JPanel();
    ButtonGroup selectModeGroup = new ButtonGroup();
    JTextArea favorite= new JTextArea(4,40);
    //用一个字符串数组来创建一个JList对象
    JList<String > bookList;
    JComboBox<String> bookSelector;
    public void init(){

        //组装视图
        //组装JList
        bookList = new JList<>(books);
        addBtn2layoutPanel("纵向滚动",JList.VERTICAL);
        addBtn2layoutPanel("纵向滚动",JList.VERTICAL_WRAP);
        addBtn2layoutPanel("纵向滚动",JList.HORIZONTAL_WRAP);

        addBtn2SelectPanel("无限制",ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        addBtn2SelectPanel("单选",ListSelectionModel.SINGLE_SELECTION);
        addBtn2SelectPanel("单范围",ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        //对JList设置
        bookList.setVisibleRowCount(3);
        bookList.setSelectionInterval(2,4);
        bookList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                //获取当前选择的条目
                List<String> selectdValueList = bookList.getSelectedValuesList();
                //把当前条目的内容设置到文本域中
                favorite.setText("");
                for(String str: selectdValueList){
                    favorite.append(str+"\n");
                }
            }
        });

        Box booklistVBox =Box.createVerticalBox();
        booklistVBox.add(new JScrollPane(bookList));
        booklistVBox.add(layoutPanel);
        booklistVBox.add(selectModelPanel);


        //组装Jcombox
        Vector<String> vector = new Vector<>();
        List<String> list = List.of("java自学宝典","轻量级javaee企业应用实战","Android基础教程",
                "Jquery实战教程","spriingboot企业级开发");
        vector.addAll(list);

        bookSelector = new JComboBox<>(vector);
        bookSelector.setEditable(true);
        bookSelector.setMaximumRowCount(5);
        bookSelector.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
              Object selectedItem =   bookSelector.getSelectedItem();
              favorite.setText(selectedItem.toString());
            }
        });
        //组装顶部左右两部分
        Box topBox = Box.createHorizontalBox();
        topBox.add(booklistVBox);
        JPanel booksSelectPanel = new JPanel();
        booksSelectPanel.add(bookSelector);
        topBox.add(booksSelectPanel);
        //柱状底部
        JPanel bottonPanel = new JPanel();
        bottonPanel.setLayout(new BorderLayout());
        bottonPanel.add(new JLabel("你追喜欢的书是"),BorderLayout.NORTH);
        bottonPanel.add(favorite);

        //组装整体
        Box holeBox = Box.createVerticalBox();
        holeBox.add(topBox);
        holeBox.add(bottonPanel);
        jf.add(holeBox);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }
//封装方法,往layout中添加单选
    public void addBtn2layoutPanel(String name ,  int layoutType){
        //设置标题边框
        layoutPanel.setBorder(new TitledBorder(new EtchedBorder(),"确定选项布局"));
   JRadioButton button = new JRadioButton(name);
   layoutPanel.add(button);
   if(layoutgroup.getButtonCount()==0){
       //让默认第一个按钮选中
       button.setSelected(true);
   }
   layoutgroup.add(button);
   button.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
           bookList.setLayoutOrientation(layoutType);
       }
   });
    }
    //封装方法给selectModelPanle添加按钮
    public void addBtn2SelectPanel(String name ,  int selectModel){
        //设置标题边框
       selectModelPanel.setBorder(new TitledBorder(new EtchedBorder(),"确定选项布局"));
        JRadioButton button = new JRadioButton(name);
        layoutPanel.add(button);
        if(selectModeGroup.getButtonCount()==0){
            //让默认第一个按钮选中
            button.setSelected(true);
        }
        selectModelPanel.add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                bookList.setSelectionMode(selectModel);
            }
        });
    }
    public static void main(String[] args) {
        new Demo22().init();
    }
}
package Demo1;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Demo23 {
    JFrame jf = new JFrame("简单数");
    public void init() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("中国");
        DefaultMutableTreeNode guangdong = new DefaultMutableTreeNode("广东");
        DefaultMutableTreeNode guanxi = new DefaultMutableTreeNode("广西");
        DefaultMutableTreeNode foshan = new DefaultMutableTreeNode("佛山");
        DefaultMutableTreeNode shantou = new DefaultMutableTreeNode("汕头");
        DefaultMutableTreeNode guilin = new DefaultMutableTreeNode("桂林");
        DefaultMutableTreeNode nanling = new DefaultMutableTreeNode("南宁");
       //定义按钮。完成操作
        JButton addSiblingBtn = new JButton("添加兄弟结点");
        JButton addChildBtn = new JButton("添加子节点");
        JButton deletBtn = new JButton("删除结点");
        JButton editBtn = new JButton("编辑当前结点");
        //组装结点之间的关系
        root.add(guangdong);
        root.add(guanxi);
        guangdong.add(foshan);
        guangdong.add(shantou);
        guanxi.add(guilin);
        guanxi.add(nanling);
        JTree tree = new JTree(root);
        //完成树的结点编辑代码
tree.setEditable(true);

        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

        jf.add(tree);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

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

import javax.swing.*;
import javax.swing.table.TableColumn;

public class Demo24 {
    JFrame jf = new JFrame("简单表格");
//创建一个一维数组,用于存放标题
    Object[] titles = {"姓名","年龄","性别"};
    //创建一个二维数组,存储数据
    Object[][] data = {
            {"李清照","女","20"},
            {"苏格拉底","男","55"},
            {"苏格拉高","男","45"},
            {"苏格拉中","男","65"},
            {"李白","男","95"},
            {"冗余和","男","40"},
            {"和域诗","女","18"}};
    public void init(){
//组装视图
        JTable jtable = new JTable(data,titles);
        //设置选择模式
        //jtable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//默认,无限制
        jtable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//单行
        //jtable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);//只能选择两个连续范围
        //设置宽列
        TableColumn column_1 = jtable.getColumn(titles[0]);
        column_1.setMaxWidth(30);
        TableColumn column_3 = jtable.getColumn(titles[2]);
        column_3.setMaxWidth(30);


        jf.add(new JScrollPane(jtable));
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);

    }

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

你可能感兴趣的:(java学习,java,c#,windows)