简体   繁体   English

如何在Java中制作可拆分点击的图片?

[英]How to make an image that has been split clickable in Java?

The program lets the user select a picture, then select how many pieces are going to be made. 该程序允许用户选择一张图片,然后选择要制作多少张。 The goal (later on) is to have a math problem under each piece. 目标(后来)是在每个部分下都有一个数学问题。 So if they select 4 problems then the picture will be made into 4 pieces and under each piece will be a math problem (4 total of course). 因此,如果他们选择4个问题,则图片将被分成4个部分,并且在每个部分下面将是一个数学问题(当然总共有4个问题)。 My question is: How do I make this possible? 我的问题是:我如何做到这一点? I have read that I need a mouse listener, but I'm not sure if that is the right way about going this and I'm not quite sure how to use them in this case. 我已经读到我需要一个鼠标侦听器,但是我不确定这是否是正确的方法,并且我不确定在这种情况下如何使用它们。

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.KeyStroke;

public class Menu extends JFrame {
    JMenuBar menuBar;
    ButtonGroup pictureGroup, problemsGroup;
    BufferedImage picture1img, picture2img, picture3img;
    JMenu choiceOfThreePictures, numberOfProblems;
    JRadioButtonMenuItem picture1, picture2, picture3, fourProblems, nineProblems, sixteenProblems;
    private String picture1Address = "/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture1.jpg";
    private String picture2Address = "/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture2.jpg";
    private String picture3Address = "/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg";
    KeyStroke picture1HotKey, picture2HotKey, picture3HotKey, fourProblemsHotKey, nineProblemsHotKey, sixteenProblemsHotKey;
    public Menu() {
        // Create the menu bar.
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        // Create Picture choices on Menu Bar and make Mnemonic 
        choiceOfThreePictures = new JMenu("Picture Choices");
        choiceOfThreePictures.setMnemonic(KeyEvent.VK_J);

        // Add Picture choices on Menu Bar
        menuBar.add(choiceOfThreePictures);

        // Create MenuItems onto Picture choices
        pictureGroup = new ButtonGroup();

        // Create button and accelerator for picture 1
        picture1 = new JRadioButtonMenuItem("Picture 1");
        picture1HotKey = KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.CTRL_DOWN_MASK);
        picture1.setAccelerator(picture1HotKey);

        // Create button and accelerator for picture 2
        picture2 = new JRadioButtonMenuItem("Picture 2");
        picture2HotKey = KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_DOWN_MASK);
        picture2.setAccelerator(picture2HotKey);

        // Create button and accelerator for picture 3
        picture3 = new JRadioButtonMenuItem("Picture 3");
        picture3HotKey = KeyStroke.getKeyStroke(KeyEvent.VK_3, KeyEvent.CTRL_DOWN_MASK);
        picture3.setAccelerator(picture3HotKey);

        // Add Picture Choices to Picutre choices menu
        choiceOfThreePictures.add(picture1);
        pictureGroup.add(picture1);
        choiceOfThreePictures.add(picture2);
        pictureGroup.add(picture2);
        choiceOfThreePictures.add(picture3);
        pictureGroup.add(picture3);

        // Create Number Of Problems on Menu Bar and make Mnemonic
        numberOfProblems = new JMenu("Number Of Problems");
        numberOfProblems.setMnemonic(KeyEvent.VK_T);

        // Add Number Of problems on Menu Bar
        menuBar.add(numberOfProblems);

        // Create Menu Items onto Number Of problems
        problemsGroup = new ButtonGroup();

        // Create button and accelerator for fourProblems 
        fourProblems = new JRadioButtonMenuItem("4");
        fourProblemsHotKey = KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.CTRL_DOWN_MASK);
        fourProblems.setAccelerator(fourProblemsHotKey);

        // Create button and accelertor for nineProblems
        nineProblems = new JRadioButtonMenuItem("9");
        nineProblemsHotKey = KeyStroke.getKeyStroke(KeyEvent.VK_F9, KeyEvent.CTRL_DOWN_MASK);
        nineProblems.setAccelerator(nineProblemsHotKey);

        // Create button and accelerator for sixteenProblems
        sixteenProblems = new JRadioButtonMenuItem("16");
        sixteenProblemsHotKey = KeyStroke.getKeyStroke(KeyEvent.VK_F12, KeyEvent.CTRL_DOWN_MASK);
        sixteenProblems.setAccelerator(sixteenProblemsHotKey);

        // Add Number Of problems onto menu
        numberOfProblems.add(fourProblems);
        problemsGroup.add(fourProblems);
        numberOfProblems.add(nineProblems);
        problemsGroup.add(nineProblems);
        numberOfProblems.add(sixteenProblems);
        problemsGroup.add(sixteenProblems);

        // Start creating ActionListeners for pictures
        picture1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Working");
                try {
                    picture1img = ImageIO.read(new File(picture1Address));
                    getContentPane().removeAll();
                    getContentPane().add(new JLabel(new ImageIcon(picture1img)));
                    revalidate();
                } catch (IOException e) {
                    System.out.println("Couldn't find image.");
                }
            }
        });
        picture2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Working");
                try {
                    picture2img = ImageIO.read(new File(picture2Address));
                    getContentPane().removeAll();
                    getContentPane().add(new JLabel(new ImageIcon(picture2img)));
                    revalidate();
                } catch (IOException e) {
                    System.out.println("Couldn't find image.");
                }
            }
        });
        picture3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Working");
                try {
                    picture3img = ImageIO.read(new File(picture3Address));
                    getContentPane().removeAll();
                    getContentPane().add(new JLabel(new ImageIcon(picture3img)));
                    revalidate();

                } catch (IOException e) {
                    System.out.println("Couldn't find image.");
                }
            }
        });
        // Create Action Listeners for problems
        fourProblems.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                if (picture1.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture1Address, 2);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture2.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture2Address, 2);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture3.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture3Address, 2);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        nineProblems.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                if (picture1.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture1Address, 3);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture2.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture2Address, 3);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture3.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture3Address, 3);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        sixteenProblems.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                if (picture1.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture1Address, 4);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture2.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture2Address, 4);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                } else if (picture3.isSelected()){
                    try {
                        getContentPane().removeAll();
                        imageSplitter(picture3Address, 4);
                        revalidate();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    // Image Splitter Method
        public void imageSplitter(String filename, int rowsandcolumns) throws IOException {
            getContentPane().setLayout(new GridLayout(rowsandcolumns, rowsandcolumns));
            // reads in file as an image
            BufferedImage image = ImageIO.read(new File(filename));
            int rows = rowsandcolumns; // You should decide the values for rows and cols
                            // variables
            int columns = rowsandcolumns;
            int chunks = rows * columns;
            int chunkWidth = image.getWidth() / columns; // determines the chunk
                                                            // width and height
            int chunkHeight = image.getHeight() / rows;
            int count = 0;
            // initialize array to store 4 new images
            BufferedImage images[] = new BufferedImage[chunks];

            // For loop for rows
            for (int x = 0; x < rows; x++) {
                // For loop for columns
                for (int y = 0; y < columns; y++) {

                    // Creates subimages of the main image and stores them in the
                    // order of Quadrant II, III, I, IV
                    images[count] = image.getSubimage((x * chunkWidth), (y * chunkHeight), chunkWidth, chunkHeight);
                    count++;
                }
            }
            // For Loop that writes the each of the 4 new images from the array.
            for (int i = 1; i < images.length + 1; i++) {
                // ImageIO.write(images[i - 1], "jpg", new File("image" + i +
                // ".jpg"));
                getContentPane().add(new JLabel(new ImageIcon(images[i - 1])));

            }
        }

    public static void main(String[] args) {
        Menu mb = new Menu();
        mb.setSize(900, 700);
        mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mb.setVisible(true);

    }
}

This is the class ImageButton that is a button that shows part of an Image, when that button is clicked then it will show the question. 这是ImageButton类,它是显示图像一部分的按钮,当单击该按钮时,它将显示问题。

public class ImageButton extends JButton{
    private String problem;
    private BufferedImage image;
    private Boolean status;//true -> image, false -> problem, null -> answered

    public ImageButton(String problem, BufferedImage image, int x, int y, int width, int height){
        this.image = image.subImage(x,y,width,height);
        this.problem = problem;
        this.setFocusPainted(false);
        this.setBorderPainted(false);
        this.setContentAreaFilled(false);
        this.addActionListener(new DefaultListener());
        this.status = true;
    }

    public void action(){
        if(status == true){
            status = false;
        }
    }

    public void answer(){
        if(status == false){
            status = null;
        }
    }

    public void paintComponent(Graphics g){
        if(status == null){
            // TODO what will happen after it is answered
        }else{
            g.drawImage(image, 0, 0, this);
            if(!status){
                printString(g, problem, 10);
            }
        }
    }

    public static void printString(Graphics g, String string, int height) {
        if (string != null) {
            int width = g.getFontMetrics().stringWidth(string);
            int length = string.length();
            if (width > getWidth() - 40) {
                length = cutString(g, string);
                g.drawString(string.substring(0, length), 20, height);
                printString(g, string.substring(length), height + 35);
            }
            g.drawString(string.substring(0, length), 20, height);
        }
    }

    public static int cutString(Graphics g, String string) {
        int count = 1;
        int space = 0;
        while (g.getFontMetrics().stringWidth(string.substring(0, count)) < getWidth() - 40) {
            if (string.charAt(count) == 32) {
                space = count;
            }
            count++;
        }
        return space;
    }
}

Here is the ActionListener , the reason I did it like this is because this is more elegant and easier to review and maintain in the future. 这是ActionListener ,之所以这样做,是因为它更优雅,将来更易于查看和维护。

public class DefaultListener implements ActionListener{

    @override
    public void actionPerformed(ActionEvent event){
        Object source = event.getSource();
        if(source instanceof ImageButton){
            (ImageButton)source.action();
        }
    }

}

Finally here is the method that gets the images: 最后,这里是获取图像的方法:

public JPanel getPanel(BufferedImage image, int count){
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, 1));//0 is horizontal, 1 is vertical
    int columns = (int)Math.ceil(Math.sqrt(count));
    int rows = (int)Math.ceil((double)count / (double)columns);
    int imageHeight = image.getHeight();
    int imageWidth = image.getWidth();
    int buttonWidth = imageWidth / columns;
    int buttonHeight = imageHeight / rows;
    int index = 0;
    for(int row = 0; row < rows; row++){
        JPanel smallPanel = new JPanel();
        smallPanel.setLayout(new BoxLayout(panel, 0));
        for(int column = 0; column < columns; column++){
            if(index >= count){
                break;
            }
            int x = buttonWidth * column;
            int y = buttonHeight * row;
            int width = buttonWidth;
            int height = buttonHeight;
            ImageButton button = new ImageButton(--Insert Problem--,image, x,y,width,height);
            smallPanel.add(button);
        }
        panel.add(smallPanel);
        index++;
    }
    return panel;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何制作可点击的图片? - How to make a clickable image? 如何恢复用Java中的正则表达式拆分的字符串 - How to recover a string that has been split by a regular expression in Java 如何让JButton在java中无法点击? - how to make a JButton not clickable in java? 将图像拆分为可点击区域 - Split image into clickable regions 读取已分割为两个文件的Java序列化对象? - Reading Java serialized object that has been split across two files? 如何在Java JFrame中制作一堆可点击的面板 - How to make a bunch of clickable panels in Java JFrame 如何在Java中使用Selenium WebDriver查找图像标签,以及如何检查它是否已正确显示? - how to find an image tag using selenium webdriver in java and how to check if it has been properly displayed? 如何使一个按钮执行一项任务,该任务取决于Java android中单击了哪个先前的按钮? - How to make one button do a task that depends on which previous buttons has been clicked in Java android? 如何使Java程序不断检查是否有更改并循环进行直到出现 - How to make a Java program to constantly check if there has been changes and loop it until there is 如何确保在循环遍历列表后添加的Java并发列表中的元素得到正确处理? - How to make sure elements of a concurrent list in java, that are added after the list has been looped through, are handled properly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM