Advertisement
Darker666

Function to display image in jframe

May 1st, 2015
443
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1.    public static void displayImage(final Image image, String message) throws InterruptedException {
  2.      if(image==null)
  3.        throw new IllegalArgumentException("No image to draw. Given image is null.");
  4.  
  5.      //The window
  6.      JFrame frame = new JFrame();
  7.      //Topmost component of the window
  8.      Container main = frame.getContentPane();
  9.      //Turns out this is probably the simplest way to render image on screen
  10.      //with guaranteed 1:1 aspect ratio
  11.      JPanel panel = new JPanel() {
  12.         @Override
  13.         protected void paintComponent(Graphics g) {
  14.             super.paintComponent(g);
  15.             g.drawImage(image, 0, 0, null);
  16.         }
  17.      };
  18.      panel.setSize(image.getWidth(null), image.getHeight(null));
  19.      //Put the image drawer in the topmost window component
  20.      main.add(panel);
  21.      //System.out.println(image.getWidth(null)+", "+image.getHeight(null));
  22.      //frame.pack();
  23.      frame.setTitle(message+" ["+image.getWidth(null)+" x "+image.getHeight(null)+"]");
  24.      //Set window size to the image size plus some padding dimensions
  25.      frame.pack();
  26.      frame.setVisible(true);
  27.      final Thread t = Thread.currentThread();
  28.      frame.addWindowListener(new WindowListener() {
  29.        @Override
  30.        public void windowOpened(WindowEvent e) {}
  31.        @Override
  32.        public void windowClosing(WindowEvent e) {
  33.          synchronized(t) {t.notify();}
  34.          //System.out.println("Closing");
  35.          frame.dispose();
  36.        }
  37.        @Override
  38.        public void windowClosed(WindowEvent e) {
  39.          //System.out.println("Closed");
  40.          //synchronized(t) {
  41.            //t.notify();
  42.          //}
  43.        }
  44.        @Override
  45.        public void windowIconified(WindowEvent e) {}
  46.        @Override
  47.        public void windowDeiconified(WindowEvent e) {}
  48.        @Override
  49.        public void windowActivated(WindowEvent e) {}
  50.        @Override
  51.        public void windowDeactivated(WindowEvent e) {}
  52.      });
  53.      synchronized(t) {
  54.        t.wait();
  55.        //System.out.println("Wait over.");
  56.      }
  57.      //JOptionPane.showMessageDialog(null, scrollPane, message, javax.swing.JOptionPane.INFORMATION_MESSAGE);
  58.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement