awt&swing 學習筆記(3)

小小雨傘發表於2020-12-09

圖片檢視器

package imageIo;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ReadAndSaveImage {

    private Frame frame = new Frame("圖片檢視器");

    private BufferedImage image;

    private class MyCanvas extends Canvas {

        @Override
        public void paint(Graphics g) {
            if (image != null) {
                g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            }
        }
    }

    private MyCanvas imageComponent = new MyCanvas();

    public void init() throws Exception {

        //設定選單項
        MenuBar mb = new MenuBar();
        Menu menu = new Menu("檔案");
        MenuItem openItem = new MenuItem("開啟");
        MenuItem saveItem = new MenuItem("另存為");

        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //彈出對話方塊,選擇本地圖片
                FileDialog oDialog = new FileDialog(frame);
                oDialog.setVisible(true);
                //讀取使用者選擇的圖片
                String dir = oDialog.getDirectory();
                String file = oDialog.getFile();
                try {
                    image = ImageIO.read(new File(dir, file));

                    imageComponent.repaint();

                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });


        saveItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //彈出對話方塊,另存為
                FileDialog sDialog = new FileDialog(frame, "儲存圖片", FileDialog.SAVE);
                sDialog.setVisible(true);
                String dir = sDialog.getDirectory();
                String file = sDialog.getFile();

                try {
                    ImageIO.write(image, "JPEG", new File(dir, file));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });


        mb.add(menu);
        menu.add(openItem);
        menu.add(saveItem);

        frame.setMenuBar(mb);
        frame.add(imageComponent);

        frame.setBounds(200, 200, 800, 600);

        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }


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

border

package swing.border;

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

public class Dome1 {


    JFrame f =new JFrame("測試邊框");



    public void init(){

        //組裝檢視

        f.setLayout(new GridLayout(2,4));

        //建立BevelBorder
        Border bevelBorder = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.red, Color.green, Color.blue, Color.gray);
        f.add(getJPanelWithBorder(bevelBorder,"bevelBorder"));

        //建立LineBorder
        Border lineBorder = BorderFactory.createLineBorder(Color.yellow, 10, true);
        f.add(getJPanelWithBorder(lineBorder,"lineBorder"));

        //emptyBorder
        Border emptyBorder = BorderFactory.createEmptyBorder(10, 5, 20, 30);
        f.add(getJPanelWithBorder(emptyBorder,"emptyBorder"));

        //建立etchedBorder
        Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.red,Color.green);
        f.add(getJPanelWithBorder(etchedBorder,"etchedBorder"));

        //建立titledBorder
        TitledBorder titledBorder = BorderFactory.createTitledBorder(new LineBorder(Color.orange, 10), "這是標題",TitledBorder.LEFT,TitledBorder.BOTTOM);
        f.add(getJPanelWithBorder(titledBorder,"titledBorder"));

        //建立matteBorder
        MatteBorder matteBorder = BorderFactory.createMatteBorder(10, 5, 20, 10, Color.green);
        f.add(getJPanelWithBorder(matteBorder,"matteBorder"));

        //建立compoundBorder

        CompoundBorder compoundBorder = BorderFactory.createCompoundBorder(titledBorder, new LineBorder(Color.red, 10));
        f.add(getJPanelWithBorder(compoundBorder,"compoundBorder"));


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

    }

    public JPanel getJPanelWithBorder(Border border, String content){
        JPanel jPanel =new JPanel();
        jPanel.add(new JLabel(content));

        //設定邊框
        jPanel.setBorder(border);

        return jPanel;
    }


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

}

工具條

package swing.JToolBar;

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

public class Dome {


    JFrame f =new JFrame();

    JToolBar jToolBar =new JToolBar("播放工具條",SwingConstants.HORIZONTAL);

    JTextArea ta =new JTextArea(10,20);

    Action pre =new AbstractAction("上一曲",new ImageIcon("src/main/java/img/component/pre.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            ta.append("上一曲\n");
        }
    };

    Action pause =new AbstractAction("暫停",new ImageIcon("src/main/java/img/component/pause.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            ta.append("暫停\n");
        }
    };

    Action next =new AbstractAction("下一曲",new ImageIcon("src/main/java/img/component/next.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            ta.append("下一曲\n");
        }
    };




    public void init(){

        //組裝檢視

        JButton preB =new JButton(pre);
        JButton pauseB =new JButton(pause);
        JButton nextB =new JButton(next);


        jToolBar.add(preB);
        jToolBar.addSeparator();
        jToolBar.add(pauseB);
        jToolBar.addSeparator();
        jToolBar.add(nextB);


        //可以讓工具條拖動
        jToolBar.setFloatable(true);


        //文字預設不支援滾動條
        JScrollPane jScrollPane =new JScrollPane(ta);

        f.add(jScrollPane);

        f.add(jToolBar, BorderLayout.NORTH);


//        f.add(ta);





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




    }


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


}

實戰綜合

package swing;

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

public class Dome1 {


    JFrame f = new JFrame("測試swing基本元件");

    //定義一個按鈕,併為其指定圖示
//    Icon okIcon = new ImageIcon(ImagePathUtil.getRealPath("2\\ok.png"));
    JButton ok = new JButton("確定");
//    JButton ok = new JButton("確定",okIcon);

    //定義一個單選按鈕,初始處於選中的狀態
    JRadioButton male = new JRadioButton("男",true);
    //定義一個單選按鈕,初始處於選中狀態
    JRadioButton female = new JRadioButton("女",false);

    //定義一個ButtonGroup,把male和female組合起來,實現單選
    ButtonGroup bg  = new ButtonGroup();

    //定義一個核取方塊,初始處於沒有選中狀態
    JCheckBox married = new JCheckBox("是否已婚?",false);

    //定義一個陣列儲存顏色
    String[] colors = { "紅色", "綠色 " , "藍色 " };

    //定義一個下拉選擇框,展示顏色
    JComboBox<String> colorChooser = new JComboBox<String>(colors);

    //定一個列表框,展示顏色
    JList<String> colorList = new JList<String>(colors);

    //定義一個8行20列的多行文字域
    JTextArea ta = new JTextArea(8,20);

    //定義一個40列的單行文字域
    JTextField name = new JTextField(40);

    //定義選單條
    JMenuBar mb = new JMenuBar();

    //定義選單
    JMenu file = new JMenu("檔案");
    JMenu edit = new JMenu("編輯");

    //建立選單項,並指定圖示
    JMenuItem newItem = new JMenuItem("新建");
    JMenuItem saveItem = new JMenuItem("儲存");
    JMenuItem exitItem = new JMenuItem("退出");

    //可選擇的選單欄
    JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自動換行");
    JMenuItem copyItem = new JMenuItem("複製");
    JMenuItem pasteItem = new JMenuItem("貼上");

    //定義二級選單,將來會新增到編輯中
    JMenu format = new JMenu("格式");
    JMenuItem commentItem = new JMenuItem("註釋");
    JMenuItem cancelItem = new JMenuItem("取消註釋");

    //定義一個右鍵選單,用於設定程式的外觀風格
    JPopupMenu pop = new JPopupMenu();

    //定義一個ButtongGroup物件,用於組合風格按鈕,形成單選
    ButtonGroup flavorGroup = new ButtonGroup();

    //定義五個單選按鈕選單項,用於設定程式風格
    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal 風格",true);
    JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("Nimbus 風格",true);
    JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows 風格",true);
    JRadioButtonMenuItem classicItem = new JRadioButtonMenuItem("Windows 經典風格",true);
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif 風格",true);



    //初始化介面
    public void init(){

        //------------------------組合主區域------------------------
        //建立一個裝載文字框和按鈕的JPanel
        JPanel bottom = new JPanel();
        bottom.add(name);
        bottom.add(ok);

        f.add(bottom, BorderLayout.SOUTH);

        //建立一個裝載下拉選擇框、三個JChekBox的JPanel
        JPanel checkPanel = new JPanel();
        checkPanel.add(colorChooser);
        bg.add(male);
        bg.add(female);

        checkPanel.add(male);
        checkPanel.add(female);
        checkPanel.add(married);

        //建立一個垂直排列的Box,裝載checkPanel和多行文字域
        Box topLeft = Box.createVerticalBox();

        //使用JScrollPane作為普通元件的JViewPort
        JScrollPane taJsp = new JScrollPane(ta);
        topLeft.add(taJsp);
        topLeft.add(checkPanel);

        //建立一個水平排列的Box,裝載topLeft和colorList
        Box top = Box.createHorizontalBox();
        top.add(topLeft);
        top.add(colorList);

        //將top Box 新增到視窗的中間
        f.add(top);

        //---------------------------組合選單條----------------------------------------------
        //為newItem新增快捷鍵 ctrl+N
        newItem.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_MASK));
        newItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ta.append("使用者點選了“新建”選單\n");
            }
        });


        //為file新增選單項
        file.add(newItem);
        file.add(saveItem);
        file.add(exitItem);

        //為edit新增選單項
        edit.add(autoWrap);
        edit.addSeparator();
        edit.add(copyItem);
        edit.add(pasteItem);
        //為commentItem新增提示資訊
        commentItem.setToolTipText("將程式程式碼註釋起來");

        //為format選單新增選單項
        format.add(commentItem);
        format.add(cancelItem);

        //給edit新增一個分隔符
        edit.addSeparator();

        //把format新增到edit中形成二級選單
        edit.add(format);

        //把edit file 新增到選單條中
        mb.add(file);
        mb.add(edit);

        //把選單條設定給視窗
        f.setJMenuBar(mb);

        //------------------------組合右鍵選單-----------------------------

        flavorGroup.add(metalItem);
        flavorGroup.add(nimbusItem);
        flavorGroup.add(windowsItem);
        flavorGroup.add(classicItem);
        flavorGroup.add(motifItem);

        //給5個風格選單建立事件監聽器
        ActionListener flavorLister = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                try {
                    changeFlavor(command);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        };

        //為5個風格選單項註冊監聽器
        metalItem.addActionListener(flavorLister);
        nimbusItem.addActionListener(flavorLister);
        windowsItem.addActionListener(flavorLister);
        classicItem.addActionListener(flavorLister);
        motifItem.addActionListener(flavorLister);

        pop.add(metalItem);
        pop.add(nimbusItem);
        pop.add(windowsItem);
        pop.add(classicItem);
        pop.add(motifItem);

        //呼叫ta元件的setComponentPopupMenu即可設定右鍵選單,無需使用事件
        ta.setComponentPopupMenu(pop);

        // 設定關閉視窗時推出程式
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //設定jFrame最佳大小並可見
        f.pack();
        f.setVisible(true);


    }

    //定義一個方法,用於改變介面風格
    private void changeFlavor(String command) throws Exception{
        switch (command){
            case "Metal 風格":
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                break;
            case "Nimbus 風格":
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
                break;
            case "Windows 風格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                break;
            case "Windows 經典風格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                break;
            case "Motif 風格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                break;
        }

        //更新f視窗內頂級容器以及所有元件的UI
        SwingUtilities.updateComponentTreeUI(f.getContentPane());
        //更新mb選單條及每部所有元件UI
        SwingUtilities.updateComponentTreeUI(mb);
        //更新右鍵選單及內部所有選單項的UI
        SwingUtilities.updateComponentTreeUI(pop);
    }


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

}

實戰2

package swing;

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

public class Dome2 {

    JFrame f =new JFrame();

    Icon okIcon = new ImageIcon("src/main/java/img/list/弄玉.gif");

    //文字域

    JTextArea ta =new JTextArea(8,20);

    //按鈕

    JButton jb =new JButton("確認",okIcon);

    //定義一個ButtonGroup,把選擇整合
    ButtonGroup bg  = new ButtonGroup();

    //定義單選框

    JRadioButton b1 =new JRadioButton("按鈕1");
    JRadioButton b2 =new JRadioButton("按鈕2");

    //定義一個選單

    JMenuBar jMenuBar =new JMenuBar();

    JMenu look =new JMenu("檢視");

    JMenu suoFang =new JMenu("縮放");

    JRadioButtonMenuItem zhuangTai =new JRadioButtonMenuItem("狀態列",false);


    JMenuItem big =new JMenuItem("放大");

    JMenuItem small =new JMenuItem("縮小");
    JMenuItem recover =new JMenuItem("恢復預設縮放");


    //設定選單單選組


    //定義一個右鍵選單,用於設定程式的外觀風格
    JPopupMenu pop = new JPopupMenu();

    ButtonGroup menuBj =new ButtonGroup();

    JRadioButtonMenuItem item1 =new JRadioButtonMenuItem("選擇1",true);
    JRadioButtonMenuItem item2 =new JRadioButtonMenuItem("選擇2");
    JRadioButtonMenuItem item3 =new JRadioButtonMenuItem("選擇3");
    JRadioButtonMenuItem item4 =new JRadioButtonMenuItem("選擇4");














    public void init(){

        Box top = Box.createHorizontalBox();

        top.add(ta);
        top.add(jb);

        f.add(top, BorderLayout.NORTH);

        bg.add(b1);
        bg.add(b2);


        Box bottom = Box.createVerticalBox();

        bottom.add(b1);
        bottom.add(b2);

        f.add(bottom);

        //新增選單.


        look.add(suoFang);
        look.add(zhuangTai);

        suoFang.add(big);
        suoFang.add(small);
        suoFang.add(recover);

        jMenuBar.add(look);

        //設定快捷鍵
        big.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.CTRL_MASK));


        //狀態列上要有一個單選框
//        menuBj.add(zhuangTai);

        f.setJMenuBar(jMenuBar);



        //設定右鍵選單

        menuBj.add(item1);
        menuBj.add(item2);
        menuBj.add(item3);
        menuBj.add(item4);


        pop.add(item1);
        pop.add(item2);
        pop.add(item3);
        pop.add(item4);

        //setComponentPopupMenu即可設定右鍵選單
        ta.setComponentPopupMenu(pop);


        //設定事件

        jb.addActionListener((e -> {
            String command = e.getActionCommand();
            System.out.println("點選了: "+command);
        }));

        big.addActionListener((e -> {
            System.out.println("放大~~~~~");
        }));



        // 設定關閉視窗時推出程式
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

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

相關文章