Отобразить BufferedImage из другого класса, используя Swing - PullRequest
0 голосов
/ 01 марта 2019

Я создал графический интерфейс, который открывает селектор файлов, используя следующий класс:

 public class FileSelector {
    File fp;
    BufferedImage selectedFile;

    public void SelectFile() {
        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        jfc.setDialogTitle("Select an image");
        jfc.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG and jpeg images", "png", "jpg", "jpeg");
        jfc.addChoosableFileFilter(filter);

        int returnValue = jfc.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            fp = jfc.getSelectedFile();
            System.out.println(fp);

        }

    }

    public BufferedImage createBufferedImage() throws IOException {
        ImageFileHandler img_handler = new ImageFileHandler();

        if (fp.isFile() && fp.exists()) {
            selectedFile = ImageIO.read(fp);
            System.out.println(selectedFile);
        }

        BufferedImage bimage = new BufferedImage(28, 28, BufferedImage.TYPE_INT_ARGB);

        // Draw the image on to the buffered image
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(selectedFile, 0, 0, null);
        System.out.println(bimage);
        bGr.dispose();

        JFrame frame = new JFrame("Image from Desktop");
        JLabel picLabel = new JLabel(new ImageIcon(bimage));

        JPanel jPanel = new JPanel();
        jPanel.add(picLabel);
        frame.setSize(new Dimension(400, 300));
        frame.add(jPanel);
        frame.setVisible(true);
        return bimage;
    }
}

Затем у меня есть другой класс, который использует Swing для создания графического интерфейса.В настоящее время выбранное изображение открывается в отдельном JFrame.Я хотел бы, чтобы изображение отображалось внутри основного интерфейса в displayPanel

 public class Interface {

    JFrame frame;

    /**
     * Create the application.
     * @throws IOException 
     */
    public Interface() throws IOException {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Button panel with open file and draw digit buttons
        JPanel buttonPanel = new JPanel();
        frame.getContentPane().add(buttonPanel, BorderLayout.NORTH);

        JButton openFileButton = new JButton("Open File");
        openFileButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                 FileSelector FileSelector = new FileSelector();
                    FileSelector.SelectFile();
                    try {
                        FileSelector.createBufferedImage();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

            }
        });
        buttonPanel.add(openFileButton);

        JButton drawDigitButton = new JButton("Draw Digit");
        drawDigitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        buttonPanel.add(drawDigitButton);

        //kNN
        JPanel kNNPanel = new JPanel();
        frame.getContentPane().add(kNNPanel, BorderLayout.SOUTH);

        JButton kNNButton = new JButton("kNN");
        kNNButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                kNNCalculation kNN = new kNNCalculation();

                try {
                    kNN.Calculation();
                }
                catch (Exception e1) {
                    e1.printStackTrace();
                }

            }
        });
        kNNPanel.add(kNNButton);


        //Display image here????

        JPanel displayPanel = new JPanel();
        displayPanel.setPreferredSize(new Dimension (150, 150));
        displayPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
        frame.getContentPane().add(displayPanel, BorderLayout.CENTER);
    }

}

Но я не совсем понимаю, как это сделать объектно-ориентированным способом?

1 Ответ

0 голосов
/ 01 марта 2019

Ниже показано, как нарисовать BufferedImage, полученный из другого класса.Он также может быть использован в качестве примера для MCVE .MCVE должен продемонстрировать проблему , а не вашего приложения и не зависеть от недоступных ресурсов.Следующий код можно скопировать в один файл (Interface.java) и запустить:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;

public class Interface {

    private JFrame frame;

    public Interface(){
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Button panel with open file and draw digit buttons
        JPanel buttonPanel = new JPanel();
        frame.getContentPane().add(buttonPanel, BorderLayout.NORTH);
        DrawPanel displayPanel = new DrawPanel();

        JButton openFileButton = new JButton("Open File");
        openFileButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BufferedImage image = new FileSelector().createBufferedImage();
                displayPanel.setImage(image);
                frame.pack();
            }
        });

        buttonPanel.add(openFileButton);

        frame.getContentPane().add(displayPanel, BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()-> new Interface());
    }
}

class DrawPanel extends JPanel{

    private BufferedImage image;

    public DrawPanel() {
        setPreferredSize(new Dimension (150, 150));
        setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
    }

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

    void setImage(BufferedImage image) {
        this.image = image;
        setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    }
}

class FileSelector {

    public BufferedImage createBufferedImage(){
        try {
            URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
            return ImageIO.read(url);
        } catch ( IOException ex) { ex.printStackTrace();}
        return null;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...