Results 1 to 13 of 13
- 01-24-2012, 03:13 AM #1
Adding Scaled BufferedImage to ContentPane
I'm having a problem adding the background image to the contentPane. I was using ImageIcon but was using a pre-sized background images. I've since learned how to resize the image so I can use it on different screensizes, but I haven't been able to add the image to the contentPane. I have been able to add it to the JFrame, but I'm using JInternalframes, so adding the background to the JFrame isn't the correct way to go about this. Any suggestions?
Java Code:// ImagePanel class ImagePanel extends JPanel { private BufferedImage image; public ImagePanel() { try { file = new File("background.jpg"); //get operating system and path to image file nameOS = System.getProperty("os.name").toLowerCase(); if(nameOS.indexOf("win") >= 0){ String path = file.getAbsolutePath(); String newpath = path.replace('\\', '/'); imagepath = newpath.replace("C:/", "/"); }else if(nameOS.indexOf("mac") >= 0){ String path = file.getAbsolutePath(); imagepath = path.replace("~/", "/"); } image = ImageIO.read(new File(imagepath)); } catch (IOException ioe) {ioe.getCause();} } @Override public void paintComponent(Graphics g) { scaledImage = image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT); g.drawImage(scaledImage, 0, 0, null); } }Java Code:// part of JMenu if(!exists){ //send the user a message about the desktopPane image JOptionPane.showMessageDialog(frame, "Can't find " + filename + "! Painting background light gray...", "Error", JOptionPane.ERROR_MESSAGE); //initialize desktopPane desktopPane = new JDesktopPane(); desktopPane.setBackground(Color.LIGHT_GRAY); frame.setContentPane(desktopPane); }else if(exists){ //initialize desktopPane desktopPane = new JDesktopPane(); frame.setContentPane(desktopPane); //get background image frame.getContentPane().add(new ImagePanel()); }
-
Re: Adding Scaled BufferedImage to ContentPane
You could always make the JLabel that holds the ImageIcon the contentPane. Just be sure to give it a decent layout manager, and be sure that it is set to be opaque.
-
Re: Adding Scaled BufferedImage to ContentPane
Or you could use a JPanel and draw the BufferedImage in the JPanel's paintComponent method. Either way could work.
- 01-24-2012, 06:14 AM #4
Re: Adding Scaled BufferedImage to ContentPane
You can do custom painting in a JDesktopPane too -- it's the same approach, just override paintComponent(...)I'm using JInternalframes, so adding the background to the JFrame isn't the correct way to go about this.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 01-24-2012, 06:35 PM #5
Re: Adding Scaled BufferedImage to ContentPane
Thanks for your help. I have tried these things you have suggested but nothing is working. If I comment out //scaledImage = img.blah,,, and change scaledImage to img on the next line, it will put the "huge" image on the content pane. But, because I've changed the name of img to scaledImage, Java ignores this line of code. I'm not a student, and have been learning Java on my own. I took an intro course a few years ago online, but the cost of the next course has doubled + a dollar since, so I'm trying to learn intermediate Java by using the Internet. My understanding is still a little fuzzy. Learning by example is my best option. I don't program for a living. This program is just a study guide for the three classes of Amateur Radio Operating License Exams. I hope that asking for an example is "not asking too much." Any help is appreciated. Thanks again.
Yours Truly,
switch
-
Re: Adding Scaled BufferedImage to ContentPane
Create and post an SSCCE and we'll be in a much better position to help you.
- 01-24-2012, 07:04 PM #7
Re: Adding Scaled BufferedImage to ContentPane
Let me explain a little further. What I've done is made two different sized background images. One is backgroundW.jpg (W for windows) and the other is backgroundM.jpg (M for mac), and by retrieving the operating system (windows or macintosh) I use the appropriate file so the image is displayed on my HP laptop and on my iMac. But, if I were to send this program to a friend to use on their computer, I would have to make a different image sized to their computers screen size, or make one huge image and have the program re-size the image according to the the screen size of the computer that the program is running on. That's what I'm trying to do. As you know, there's more than one way to skin a cat, but I think that the best way to write this program is to use one image and have the program re-size the image accordingly. Does this make sense?
73 = Best Regards (--... ...--)
switch
- 01-24-2012, 07:13 PM #8
Re: Adding Scaled BufferedImage to ContentPane
Then I will post an SSCCE! Thanks...
- 01-24-2012, 08:34 PM #9
Re: Adding Scaled BufferedImage to ContentPane
You don't need to create a scaled instance of the image. You can use the overload of Graphics#drawImage(...) that take a width and height.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 01-24-2012, 10:05 PM #10
Re: Adding Scaled BufferedImage to ContentPane

Add the image file to the folder containing all folders for your program build. If you want to run the program from the *.jar file add the image file to the folder with the *.jar file.
Java Code:import java.awt.*; import java.io.File; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; import java.io.IOException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; /** * * @author switch * Date: January 24, 2012 */ public class ResizeImageProblem extends JFrame implements ActionListener, InternalFrameListener { private File file; private JFrame frame; private JMenu techMenu; private Image scaledImage; private JInternalFrame techFrame; private JDesktopPane desktopPane; private JMenuItem openTech, quitTech; private String filename, imagepath, nameOS; //class required for setting the ContentPane image class ImagePanel extends JPanel { private BufferedImage image; public ImagePanel() { try { //get operating system and path to path to image file nameOS = System.getProperty("os.name").toLowerCase(); if(nameOS.indexOf("win") >= 0){ String path = file.getAbsolutePath(); String newpath = path.replace('\\', '/'); imagepath = newpath.replace("C:/", "/"); }else if(nameOS.indexOf("mac") >= 0){ String path = file.getAbsolutePath(); imagepath = path.replace("~/", "/"); } image = ImageIO.read(new File(imagepath)); } catch (IOException ioe) {ioe.getCause();} } @Override public void paintComponent(Graphics g) { //comment out the next two lines and un comment the third and the image //will be displayed large, otherwise it will resized as long as //frame.setContentPane(desktopPane) is commented out scaledImage = image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT); g.drawImage(scaledImage, 0, 0, null); //g.drawImage(image, 0, 0, null); } } public ResizeImageProblem() { //initialize JFrame frame = new JFrame(); //set JFrame frame window properties frame.setTitle("Resize Image Problem"); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //screenSize.width -= 683; screenSize.height -= 45; frame.setSize(screenSize); frame.setLocation(0, 3); frame.setResizable(false); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //initialize menuBar JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); //initialize techMenu techMenu = new JMenu("Technician Class"); techMenu.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); techMenu.setFont(new Font("Times New Roman", Font.BOLD, 14)); techMenu.setMnemonic('T'); menuBar.add(techMenu); //initialize tech menu menu items openTech = new JMenuItem("Open Technician..."); openTech.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); openTech.setAccelerator(KeyStroke.getKeyStroke("control T")); openTech.setFont(new Font("Times New Roman", Font.BOLD, 14)); //set tool tip delay toolTipDelay(); openTech.setToolTipText("Technician Class Exam Questions."); techMenu.add(openTech); quitTech = new JMenuItem("Quit Technician..."); quitTech.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); quitTech.setAccelerator(KeyStroke.getKeyStroke("control Q")); quitTech.setFont(new Font("Times New Roman", Font.BOLD, 14)); quitTech.setEnabled(false); techMenu.add(quitTech); // initialize file file = new File("background.jpg"); filename = "background.jpg"; //if file does not exist send user a message boolean exists = file.exists(); if(!exists){ //send the user a message about the desktopPane image JOptionPane.showMessageDialog(frame, "Can't find " + filename + "! " + "Painting background light gray...", "Error", JOptionPane.ERROR_MESSAGE); //initialize desktopPane desktopPane = new JDesktopPane(); desktopPane.setBackground(Color.LIGHT_GRAY); frame.setContentPane(desktopPane); }else if(exists){ //initialize desktopPane desktopPane = new JDesktopPane(); /************************************************************/ frame.setContentPane(desktopPane); // comment out this line /************************************************************/ //add ImagePanel to the ContentPane frame.getContentPane().add(new ImagePanel()); } //call Method menuListener menuListeners(); //set internal frames look and feel try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(frame); }catch(Exception e){e.getCause();} //set JFrame as visible frame.setVisible(true); } /** * Tool tip delay method. */ private void toolTipDelay(){ // Show tool tips immediately ToolTipManager.sharedInstance().setInitialDelay(0); } /** * Add Listener to MenuBar.(according to netbeans 'this' leaks memory in the * constructors in the main class, so I add the listeners via method. */ private void menuListeners() { openTech.addActionListener(this); quitTech.addActionListener(this); } /** * Constructors for techFrame. */ private void openTechFrame() { //initialize techFrame techFrame = new JInternalFrame("Technician Class", false, true, false, false); // set frame properties techFrame.setTitle("Technicain Class Exam Pool"); techFrame.setSize(550,650); // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the location of the default application. int w = getSize().width; int h = getSize().height; int x = ((dim.width-w)/2)-280; int y = ((dim.height-h)/2)-400; techFrame.setLocation(x, y); techFrame.setResizable(false); techFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); techFrame.addInternalFrameListener(this); techFrame.setFocusable(true); desktopPane.add(techFrame); //set internal frame techFrame as selectable try { techFrame.setSelected(true); }catch(java.beans.PropertyVetoException v){v.getCause();} techFrame.setVisible(true); } /** * ActionEvent Listeners. * @param ae */ @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == openTech) { openTechFrame(); }else if(ae.getSource() == quitTech) { techFrame.dispose(); } } /** * InternalFrame Listeners. * @param e */ @Override public void internalFrameClosing(InternalFrameEvent e) {} @Override public void internalFrameClosed(InternalFrameEvent e) { //enable disable JMenu menuItems if(e.getInternalFrame() == techFrame){ openTech.setEnabled(true); quitTech.setEnabled(false); } } @Override public void internalFrameOpened(InternalFrameEvent e){ //enable disable JMenu menuItems if(e.getInternalFrame() == techFrame){ openTech.setEnabled(false); quitTech.setEnabled(true); } } @Override public void internalFrameIconified(InternalFrameEvent e){} @Override public void internalFrameDeiconified(InternalFrameEvent e){} @Override public void internalFrameActivated(InternalFrameEvent e){} @Override public void internalFrameDeactivated(InternalFrameEvent e){} /** * Run Program * @param args */ public static void main(String[] args){ javax.swing.SwingUtilities.invokeLater(new Runnable(){ @Override public void run(){ ResizeImageProblem rip = new ResizeImageProblem(); } }); } }
- 01-25-2012, 05:26 PM #11
Re: Adding Scaled BufferedImage to ContentPane
I solved it with three lines of code. Now I feel stupid. Go figure.
Java Code://class required for setting the ContentPane image class ImagePanel extends JPanel { private Image img; Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize(); int w = screensize.width; int h = screensize.height; public ImagePanel(Image img) { this.img = img; Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); setPreferredSize(size); setMinimumSize(size); setMaximumSize(size); setSize(size); setLayout(null); } @Override public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, w, h, null); } }
- 01-25-2012, 05:39 PM #12
Re: Adding Scaled BufferedImage to ContentPane
I tried using another image with planets and I was very surprised that the image didn't loose its aspect ratio. The planets remained round not ovals.
switch
- 01-26-2012, 01:46 AM #13
Re: Adding Scaled BufferedImage to ContentPane
I forgot to tell those of you that are interested how I called the class ImagePanel. Here's the code:
Java Code://initialize desktopPane desktopPane = new JDesktopPane(); frame.setContentPane(desktopPane); //add ImagePanel to the ContentPane ImagePanel panel = new ImagePanel(new ImageIcon(imagepath).getImage()); frame.getContentPane().add(panel);
Similar Threads
-
exception: contentPane cannot be set to null.
By Chaosje in forum New To JavaReplies: 5Last Post: 05-04-2011, 06:53 PM -
update contentpane and jOptionPane problem
By Jhovarie in forum Threads and SynchronizationReplies: 4Last Post: 03-02-2011, 03:59 AM -
contentpane
By marodia in forum AWT / SwingReplies: 7Last Post: 08-27-2009, 07:30 AM -
Rootpane,ContentPane,LayeredPane
By makpandian in forum AWT / SwingReplies: 2Last Post: 01-30-2009, 11:22 PM -
adding the Java Console to a ContentPane
By naipulb in forum New To JavaReplies: 1Last Post: 06-10-2008, 08:51 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks