Results 1 to 11 of 11
  1. #1
    Brovahkiin501 is offline Member
    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Default Java drawImage Not Showing Up in Program

    Hi everyone! I am trying to use drawImage in the paintComponent() method and then paint it when the user does a certain action but the image is not showing up for some reason and I am not sure why. If somebody is willing to help me it would be much appreciated!! My code is rather lengthy so I will not post it all but I will post the relevant parts.

    Java Code:
    protected void paintComponent(Graphics g) {
    		super.paintComponents(g);
    			try {
    				busImage = ImageIO.read(new File("School_Bus.jpg"));
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			g.drawImage(busImage, 200, 200, 20, 20, this);
    	}
    
    	private void doAction() {
    		Graphics g = getGraphics();
    		String actionCommand = rtsItem + actionMode;
    		if (actionCommand.equals("BusStopNew")) {
    			BusStop bs = new BusStop(actionCommand, Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    			points.put(name.getText(), bs);
    			busStopList.addItem(name.getText());
    		}
    //this is where I am trying the image to show up!
    		else if (actionCommand.equals("BusStopShow")) {
    			repaint();
    		}
    		else if (actionCommand.equals("BusStopMove")) {
    			Location lo = points.get((String)busStopList.getSelectedItem());
    			lo.move(Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    		}
    		customPanel.repaint();
    		resetFields();
    	}

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,936
    Rep Power
    4

    Default Re: Java drawImage Not Showing Up in Program

    You should not be reading in a file in your paintComponent method. Initialize the image outside of that method to an instance variable and then simply call repaint() when you want to paint it. To control whether to paint the image or not you can use boolean values. I can't do much more because your code is incomplete.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    Brovahkiin501 is offline Member
    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Default Re: Java drawImage Not Showing Up in Program

    Quote Originally Posted by jim829 View Post
    You should not be reading in a file in your paintComponent method. Initialize the image outside of that method to an instance variable and then simply call repaint() when you want to paint it. To control whether to paint the image or not you can use boolean values. I can't do much more because your code is incomplete.

    Regards,
    Jim
    Here is my full code. There are more classes involved in the program but here is the main one that I am working on.

    Java Code:
     
    
    
    import javax.imageio.ImageIO;
    import javax.swing.ButtonGroup;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTextArea;
    import javax.swing.border.*;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Collection;
    import java.io.File;
    import java.io.IOException;
    
    public class MapApp extends JFrame implements ActionListener {
    
    	/** Contains radio buttons for various RTS Items */
    	JPanel selectionPanel;
    	/** Map is drawn on this panel */
    	JPanel drawingPanel;
    	/** Contains the actionListPanel at the NORTH and the customPanel at the CENTER */
    	JPanel actionPanel;
    	/** Contains a JComboBox for actions and the UIelements for the parameters */
    	JPanel actionListPanel;
    	/** The contents of this panel changes based on the chosen RTS Item and the action*/
    	JPanel customPanel;
    	JPanel busPanel;
    
    	/** All created RTS Items are stored in this data structure as (name of the object, the object) pair */
    	HashMap<String, Location> points = new HashMap();	 
    	HashMap<String, Line> lines = new HashMap();
    
    	/** Each group of action parameter components is stored in a separate ArrayList of JComponents. 
    	 *  This data structure stores (rtsItem + actionMode, ArrayList of JComponent)  pairs  
    	 */
    	HashMap<String, ArrayList<JComponent>> actionComponents = new HashMap();
    
    	/** Array of action types for location (busstop etc) */ 
    	String[] locationActions = {"New", "Show", "Hide", "Move", "Write Line Info"};
    	/** Array of action types for line */
    	String[] lineActions = {"New", "Add BusStop", "Write Schedule"};
    	/** Stores the RTS Item currently selected. Default is BusStop. */
    	String rtsItem = "BusStop";
    	/** Stores the selected action type. Default is New. */
    	String actionMode = "New";
    
    	/** This gets concatenated with rtsItem to store and fetch the relevant action list combo box */
    	String actionListKeyword = "ActionList";
    
    	/** Used to enter name of the map item */
    	JTextField name;
    	/** Used to enter x coordinate of the map item */
    	JTextField x;
    	/** Used to enter y coordinate of the map item */
    	JTextField y;
    	/** Used to enter the duration when adding next bus stop to a line */
    	JTextField duration;
    	/** Used to enter the hours and minutes of first and last service of a line */
    	JTextField firstH, firstM, lastH, lastM;
    	/** Used to enter the period by which the bus schedule changes */
    	JTextField period;
    
    	/** Used to specify whether a busstop is also a time point */
    	JCheckBox timePoint;
    
    	/** Action list combo box for location type map items */
    	JComboBox locationActionList;	 
    	/** Action list combo box for line */
    	JComboBox lineActionList;
    
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopList;
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopListDep;
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopListDest;
    	/** When a Line object gets created, its name is added to this list */
    	JComboBox lineList;
    
    	/** Holds the image of the map */
    	BufferedImage mapImage;
    	BufferedImage busImage;
    
    
    	int lastX, lastY;
    
    	class ShapeMouseListener extends MouseAdapter {
    		public void mousePressed(MouseEvent e) {
    
    		}
    	}
    
    
    	/** Inner class to handle events fired from RTS Item radio buttons */
    	class RtsItemListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			// If change in selection
    			if (rtsItem.compareTo(e.getActionCommand()) != 0)
    			{	 
    				actionMode = "New";
    				if (rtsItem.equals("BusStop"))
    					locationActionList.setSelectedIndex(0);
    				if (rtsItem.equals("Line"))
    					lineActionList.setSelectedIndex(0);	
    			}		
    			// Stores the type of the object that is chosen
    			rtsItem = e.getActionCommand();
    			System.out.println(rtsItem);
    			updateCustomComponent();
    		}
    	}
    
    	/** Inner class to handle events fired from action list */
    	class RtsItemActionListener implements ItemListener
    	{
    		public void itemStateChanged(ItemEvent e)
    		{
    			if (e.getStateChange() == ItemEvent.SELECTED) 
    			{	
    				actionMode = (String) e.getItem();
    				System.out.println(actionMode);
    				updateCustomComponent();
    			}   
    		}
    	}
    
    
    	/** Creates a UI that consistes of 3 panels.
    	 * The left panel provides choices for RTS Items.
    	 * The middle panel provides choices for action types and the relevant data fields.
    	 * The right panel draws the map items based on the chosen map item and action type.
    	 */ 
    	public MapApp(String s)  {
    		super(s);
    
    		// Create the left panel that holds radio buttons for shape types
    		selectionPanel = new JPanel(new GridLayout(2, 1, 5, 5));
    		selectionPanel.setBorder(new TitledBorder("Items"));
    		// By default rectangle button will be selected, determined by the boolean parameter to the constructor
    		JRadioButton busStopButton = new JRadioButton("BusStop", true);
    		JRadioButton lineButton = new JRadioButton("Line", false);
    		// ButtonGroup class helps us ensure only one shape can be selected at a time
    		ButtonGroup group = new ButtonGroup();
    		group.add(busStopButton);
    		group.add(lineButton);
    
    		RtsItemListener rtsItemListener = new RtsItemListener();
    		/** rtsItemListener object receives events from busStopButton */
    		busStopButton.addActionListener(rtsItemListener);
    		/** rtsItemListener object receives events from lineButton */
    		lineButton.addActionListener(rtsItemListener);
    		selectionPanel.add(busStopButton); 
    		selectionPanel.add(lineButton);
    
    
    
    		try {
    			mapImage  = ImageIO.read(new File("campus_map.jpg"));
    		}
    		catch (IOException e) { System.out.println("Could not load the map image");}
    
    		// A panel for drawing the shapes that are created and for redrawing any changes related to them
    		drawingPanel = new JPanel() {
    			public void paintComponent(Graphics g)
    			{
    				super.paintComponent(g);
    
    				int width = getWidth();
    				int height = getHeight(); 
    
    				if (width == 0 || height == 0)
    				{
    					width = (int)getPreferredSize().getWidth();
    					height = (int)getPreferredSize().getHeight();
    				}
    				g.clearRect(0,  0,  getWidth(),  getHeight());
    				g.drawImage(mapImage, 0, 0, width, height, null);
    			}
    
    
    			public Dimension getPreferredSize()
    			{
    				return new Dimension(600, 500);
    			}
    
    
    		};
    		drawingPanel.setBorder(new TitledBorder("Map"));
    		drawingPanel.add(new JLabel("Map"));
    		drawingPanel.setPreferredSize(new Dimension(50, 50)); 
    
    		// This middle panel lets users choose an action on the RTS Items
    		actionPanel = new JPanel(new BorderLayout(5,5));
    		actionPanel.setBorder(new TitledBorder("Actions"));
    		actionListPanel = new JPanel();
    		customPanel = new JPanel();
    		actionPanel.add(actionListPanel, BorderLayout.NORTH);
    		actionPanel.add(customPanel, BorderLayout.CENTER);
    		/** Initializes the customPanel that holds the fields for parameters */
    		makeCustomPanelComponents();      
    
    		setLayout(new BorderLayout(5,5));
    		add(drawingPanel, BorderLayout.EAST);
    		add(selectionPanel, BorderLayout.WEST); 
    		add(actionPanel, BorderLayout.CENTER);
    
    
    	}
    
    
    	public void makeCustomPanelComponents()
    	{	
    
    		/** For displaying the actions for Location type objects */
    		locationActionList = new JComboBox(locationActions); 
    		/** an RtsItemActionListener object receives events from locationActionList */
    		locationActionList.addItemListener(new RtsItemActionListener());
    		JPanel locActionPanel = new JPanel();
    		locActionPanel.add(locationActionList);
    		ArrayList<JComponent> bsActionList = new ArrayList();
    		bsActionList.add(locActionPanel);        
    		actionComponents.put("BusStop" + actionListKeyword, bsActionList);
    
    		/** For diplaying the actions for Line objects */ 
    		lineActionList = new JComboBox(lineActions);
    		/** an RtsItemActionListener object receives events from lineActionList */
    		lineActionList.addItemListener(new RtsItemActionListener());
    		JPanel lineActionPanel = new JPanel();
    		lineActionPanel.add(lineActionList);
    		ArrayList<JComponent> lnActionList = new ArrayList();
    		lnActionList.add(lineActionPanel);
    		actionComponents.put("Line" + actionListKeyword, lnActionList);
    
    		/** For entering the name of the map item */
    		JLabel nLabel = new JLabel("Name");
    		name = new JTextField(10);
    		JPanel nPanel = new JPanel();
    		nPanel.add(nLabel);
    		nPanel.add(name);
    
    		JLabel dLabel = new JLabel("Duration");
    		duration = new JTextField("Duration", 3);
    		JPanel dPanel = new JPanel();
    		dPanel.add(dLabel);
    		dPanel.add(duration);
    
    		/** For entering the x and y coordinates */
    		JLabel xLabel = new JLabel("x");
    		x = new JTextField(4);
    		JPanel xPanel = new JPanel();
    		xPanel.add(xLabel);
    		xPanel.add(x);
    		JLabel yLabel = new JLabel("y");
    		y = new JTextField(4);
    		JPanel yPanel = new JPanel();
    		yPanel.add(yLabel);
    		yPanel.add(y);
    
    		firstH = new JTextField(4);
    		firstM = new JTextField(4);
    		JPanel firstPanel = new JPanel();
    		firstPanel.add(new JLabel("First"));
    		firstPanel.add(firstH);
    		firstPanel.add(new JLabel(":"));
    		firstPanel.add(firstM);
    
    		lastH = new JTextField(4);
    		lastM = new JTextField(4);
    		JPanel lastPanel = new JPanel();
    		lastPanel.add(new JLabel("Last"));
    		lastPanel.add(lastH);
    		lastPanel.add(new JLabel(":"));
    		lastPanel.add(lastM);
    
    
    		period = new JTextField(4);
    		JPanel periodPanel = new JPanel();
    		periodPanel.add(new JLabel("Period"));
    		periodPanel.add(period);
    
    
    		/** For checking or unchecking timePoint feature */
    		JLabel timePointLabel = new JLabel("Time Point?");
    		timePoint = new JCheckBox("", false);
    		timePoint.addActionListener((ActionListener)this);
    		JPanel tPanel = new JPanel();
    		tPanel.add(timePointLabel);
    		tPanel.add(timePoint);
    
    		/** For doing the chosen action on the selected object based on the entered parameter values */
    		JButton ok = new JButton("OK");
    		ok.setBackground(Color.blue);
    		/** See actionPerformed method to see the action taken */
    		ok.addActionListener((ActionListener)this);
    
    		/** As objects get created their names will be added to the corresponding list */
    		String[] busStopNames = {};
    		busStopList = new JComboBox(busStopNames);
    		busStopListDep = new JComboBox(busStopNames);
    		busStopListDest = new JComboBox(busStopNames);
    		String[] lineNames = {};
    		lineList = new JComboBox(lineNames);
    		JPanel bsListPanel = new JPanel();
    		bsListPanel.add(new JLabel("BusStop"));
    		bsListPanel.add(busStopList);
    		JPanel bsListPanelDep = new JPanel();
    		bsListPanelDep.add(new JLabel("Departure"));
    		bsListPanelDep.add(busStopListDep);
    		JPanel bsListPanelDest = new JPanel();
    		bsListPanelDest.add(new JLabel("Destination"));
    		bsListPanelDest.add(busStopListDest);
    
    
    		JPanel lnListPanel = new JPanel();
    		lnListPanel.add(new JLabel("Line"));
    		lnListPanel.add(lineList);
    
    		/** Custom panel components for creating a new busstop */
    		ArrayList<JComponent> newBSComponents = new ArrayList();
    		newBSComponents.add(nPanel);
    		newBSComponents.add(xPanel);
    		newBSComponents.add(yPanel);
    		newBSComponents.add(tPanel);      
    		newBSComponents.add(ok);
    		actionComponents.put("BusStopNew", newBSComponents);
    
    		/** Custom panel components for moving a busstop */
    		ArrayList<JComponent> moveBSComponents = new ArrayList();
    		moveBSComponents.add(bsListPanel);
    		moveBSComponents.add(xPanel);
    		moveBSComponents.add(yPanel);
    		moveBSComponents.add(ok);
    		actionComponents.put("BusStopMove", moveBSComponents);     
    
    		/** Custom panel components for showing a busstop on the map */
    		ArrayList<JComponent> showBSComponents = new ArrayList();
    		showBSComponents.add(bsListPanel);
    		showBSComponents.add(ok);
    		actionComponents.put("BusStopShow", showBSComponents);
    
    		/** Custom panel components for hiding a bus stop from the map display */
    		ArrayList<JComponent> hideBSComponents = new ArrayList();
    		hideBSComponents.add(bsListPanel);
    		hideBSComponents.add(ok);
    		actionComponents.put("BusStopHide", hideBSComponents);
    
    		/** Custom panel components for showing the lines that stop at a busstop */
    		ArrayList<JComponent> showLnsComponents = new ArrayList();
    		showLnsComponents.add(bsListPanel);
    		showLnsComponents.add(ok);
    		actionComponents.put("BusStopWrite Line Info", showLnsComponents);       
    
    		/** Custom panel components for creating a bus line */
    		ArrayList<JComponent> newLNComponents = new ArrayList();
    		newLNComponents.add(nPanel);
    		newLNComponents.add(bsListPanelDep);
    		newLNComponents.add(bsListPanelDest);
    		newLNComponents.add(firstPanel);
    		newLNComponents.add(lastPanel);
    		newLNComponents.add(periodPanel);
    		newLNComponents.add(ok);
    		actionComponents.put("LineNew", newLNComponents);
    
    		/** Custom panel components for adding a bus stop to a line */
    		ArrayList<JComponent> addBSComponents = new ArrayList();
    		addBSComponents.add(bsListPanel);
    		addBSComponents.add(dPanel);
    		addBSComponents.add(ok);
    		actionComponents.put("LineAdd BusStop", addBSComponents); 
    
    		/** Custom panel components for writing the schedule of a line to a file */
    		ArrayList<JComponent> writeSchComponents = new ArrayList();
    		writeSchComponents.add(lnListPanel);
    		writeSchComponents.add(ok);
    		actionComponents.put("LineWrite Schedule", writeSchComponents);           
    	}
    
    	private void resetFields()
    	{
    		name.setText("");
    		x.setText("");
    		y.setText("");
    		duration.setText("");
    		period.setText("");
    		firstH.setText("");
    		firstM.setText("");
    		lastH.setText("");
    		lastM.setText("");
    		timePoint.setSelected(false);
    
    	}
    
    	/** Removes the UI components in customPanel and adds the new components based on the selected shape and the action type */
    	private void updateCustomComponent()
    	{
    		resetFields();	
    
    		actionListPanel.removeAll();
    		actionListPanel.add(actionComponents.get(rtsItem + actionListKeyword).get(0), BorderLayout.NORTH);
    		actionListPanel.revalidate();
    		actionListPanel.repaint();
    
    		customPanel.removeAll();
    		ArrayList<JComponent> list = actionComponents.get(rtsItem + actionMode);
    		for(int i=0; i < list.size(); i++)
    			customPanel.add(list.get(i));
    		// Updates the view of the customPanel with new components
    		customPanel.revalidate();
    		customPanel.repaint();
    	}
    
    	public void paintComponent(Graphics g) {
    		super.paintComponents(g);
    		g.drawImage(busImage, 200, 200, 20, 20, this);
    	}
    
    	private void doAction() {
    		Graphics g = getGraphics();
    		String actionCommand = rtsItem + actionMode;
    		if (actionCommand.equals("BusStopNew")) {
    			BusStop bs = new BusStop(actionCommand, Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    			points.put(name.getText(), bs);
    			busStopList.addItem(name.getText());
    		}
    		else if (actionCommand.equals("BusStopShow")) {
    			repaint();
    		}
    		else if (actionCommand.equals("BusStopMove")) {
    			Location lo = points.get((String)busStopList.getSelectedItem());
    			lo.move(Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    		}
    		customPanel.repaint();
    		resetFields();
    	}
    
    
    	/** Handles the OK button events */
    	public void actionPerformed(ActionEvent e) {
    		String command = e.getActionCommand();
    		if (command.equals("OK")) 
    			System.out.println(rtsItem + actionMode);
    		doAction();
    	}
    
    	public static void main(String[] args) {
    
    		MapApp myapp = new MapApp("The BusStop on the Map!"); 
    		myapp.setSize(1200, 600);
    		myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		myapp.setVisible(true);
    		myapp.updateCustomComponent();
    	}
    
    }
    I have tried to initialize the image outside of the method but I keep getting an error. Can you please help me figure out where to initialize the image?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Java drawImage Not Showing Up in Program

    Quote Originally Posted by Brovahkiin501 View Post
    I have tried to initialize the image outside of the method but I keep getting an error. Can you please help me figure out where to initialize the image?
    If you're having problems and you're seeing an error, you will want to post the full error text here so we can understand just what it is. You'll also want to indicate in some way which line(s) is(are) causing the error.

  5. #5
    Brovahkiin501 is offline Member
    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Default Re: Java drawImage Not Showing Up in Program

    Quote Originally Posted by Fubarable View Post
    If you're having problems and you're seeing an error, you will want to post the full error text here so we can understand just what it is. You'll also want to indicate in some way which line(s) is(are) causing the error.
    Java Code:
    
    import javax.imageio.ImageIO;
    import javax.swing.ButtonGroup;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTextArea;
    import javax.swing.border.*;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Collection;
    import java.io.File;
    import java.io.IOException;
    
    public class MapApp extends JFrame implements ActionListener {
    
    	/** Contains radio buttons for various RTS Items */
    	JPanel selectionPanel;
    	/** Map is drawn on this panel */
    	JPanel drawingPanel;
    	/** Contains the actionListPanel at the NORTH and the customPanel at the CENTER */
    	JPanel actionPanel;
    	/** Contains a JComboBox for actions and the UIelements for the parameters */
    	JPanel actionListPanel;
    	/** The contents of this panel changes based on the chosen RTS Item and the action*/
    	JPanel customPanel;
    	JPanel busPanel;
    
    	/** All created RTS Items are stored in this data structure as (name of the object, the object) pair */
    	HashMap<String, Location> points = new HashMap();	 
    	HashMap<String, Line> lines = new HashMap();
    
    	/** Each group of action parameter components is stored in a separate ArrayList of JComponents. 
    	 *  This data structure stores (rtsItem + actionMode, ArrayList of JComponent)  pairs  
    	 */
    	HashMap<String, ArrayList<JComponent>> actionComponents = new HashMap();
    
    	/** Array of action types for location (busstop etc) */ 
    	String[] locationActions = {"New", "Show", "Hide", "Move", "Write Line Info"};
    	/** Array of action types for line */
    	String[] lineActions = {"New", "Add BusStop", "Write Schedule"};
    	/** Stores the RTS Item currently selected. Default is BusStop. */
    	String rtsItem = "BusStop";
    	/** Stores the selected action type. Default is New. */
    	String actionMode = "New";
    
    	/** This gets concatenated with rtsItem to store and fetch the relevant action list combo box */
    	String actionListKeyword = "ActionList";
    
    	/** Used to enter name of the map item */
    	JTextField name;
    	/** Used to enter x coordinate of the map item */
    	JTextField x;
    	/** Used to enter y coordinate of the map item */
    	JTextField y;
    	/** Used to enter the duration when adding next bus stop to a line */
    	JTextField duration;
    	/** Used to enter the hours and minutes of first and last service of a line */
    	JTextField firstH, firstM, lastH, lastM;
    	/** Used to enter the period by which the bus schedule changes */
    	JTextField period;
    
    	/** Used to specify whether a busstop is also a time point */
    	JCheckBox timePoint;
    
    	/** Action list combo box for location type map items */
    	JComboBox locationActionList;	 
    	/** Action list combo box for line */
    	JComboBox lineActionList;
    
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopList;
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopListDep;
    	/** When a BusStop object gets created, its name is added to this list */
    	JComboBox busStopListDest;
    	/** When a Line object gets created, its name is added to this list */
    	JComboBox lineList;
    
    	/** Holds the image of the map */
    	
    	//This is where the error is.  It says there is an unresolved compilation problem.
    	BufferedImage mapImage;
    	try {
    		BufferedImage busImage = ImageIO.read(new File("School_Bus.jpg"));
    	} catch (IOException e) { 
    		e.printStackTrace();
    	}
    
    
    	int lastX, lastY;
    
    	class ShapeMouseListener extends MouseAdapter {
    		public void mousePressed(MouseEvent e) {
    
    		}
    	}
    
    
    	/** Inner class to handle events fired from RTS Item radio buttons */
    	class RtsItemListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			// If change in selection
    			if (rtsItem.compareTo(e.getActionCommand()) != 0)
    			{	 
    				actionMode = "New";
    				if (rtsItem.equals("BusStop"))
    					locationActionList.setSelectedIndex(0);
    				if (rtsItem.equals("Line"))
    					lineActionList.setSelectedIndex(0);	
    			}		
    			// Stores the type of the object that is chosen
    			rtsItem = e.getActionCommand();
    			System.out.println(rtsItem);
    			updateCustomComponent();
    		}
    	}
    
    	/** Inner class to handle events fired from action list */
    	class RtsItemActionListener implements ItemListener
    	{
    		public void itemStateChanged(ItemEvent e)
    		{
    			if (e.getStateChange() == ItemEvent.SELECTED) 
    			{	
    				actionMode = (String) e.getItem();
    				System.out.println(actionMode);
    				updateCustomComponent();
    			}   
    		}
    	}
    
    
    	/** Creates a UI that consistes of 3 panels.
    	 * The left panel provides choices for RTS Items.
    	 * The middle panel provides choices for action types and the relevant data fields.
    	 * The right panel draws the map items based on the chosen map item and action type.
    	 */ 
    	public MapApp(String s)  {
    		super(s);
    
    		// Create the left panel that holds radio buttons for shape types
    		selectionPanel = new JPanel(new GridLayout(2, 1, 5, 5));
    		selectionPanel.setBorder(new TitledBorder("Items"));
    		// By default rectangle button will be selected, determined by the boolean parameter to the constructor
    		JRadioButton busStopButton = new JRadioButton("BusStop", true);
    		JRadioButton lineButton = new JRadioButton("Line", false);
    		// ButtonGroup class helps us ensure only one shape can be selected at a time
    		ButtonGroup group = new ButtonGroup();
    		group.add(busStopButton);
    		group.add(lineButton);
    
    		RtsItemListener rtsItemListener = new RtsItemListener();
    		/** rtsItemListener object receives events from busStopButton */
    		busStopButton.addActionListener(rtsItemListener);
    		/** rtsItemListener object receives events from lineButton */
    		lineButton.addActionListener(rtsItemListener);
    		selectionPanel.add(busStopButton); 
    		selectionPanel.add(lineButton);
    
    
    
    		try {
    			mapImage  = ImageIO.read(new File("campus_map.jpg"));
    		}
    		catch (IOException e) { System.out.println("Could not load the map image");}
    
    		// A panel for drawing the shapes that are created and for redrawing any changes related to them
    		drawingPanel = new JPanel() {
    			public void paintComponent(Graphics g)
    			{
    				super.paintComponent(g);
    
    				int width = getWidth();
    				int height = getHeight(); 
    
    				if (width == 0 || height == 0)
    				{
    					width = (int)getPreferredSize().getWidth();
    					height = (int)getPreferredSize().getHeight();
    				}
    				g.clearRect(0,  0,  getWidth(),  getHeight());
    				g.drawImage(mapImage, 0, 0, width, height, null);
    			}
    
    
    			public Dimension getPreferredSize()
    			{
    				return new Dimension(600, 500);
    			}
    
    
    		};
    		drawingPanel.setBorder(new TitledBorder("Map"));
    		drawingPanel.add(new JLabel("Map"));
    		drawingPanel.setPreferredSize(new Dimension(50, 50)); 
    
    		// This middle panel lets users choose an action on the RTS Items
    		actionPanel = new JPanel(new BorderLayout(5,5));
    		actionPanel.setBorder(new TitledBorder("Actions"));
    		actionListPanel = new JPanel();
    		customPanel = new JPanel();
    		actionPanel.add(actionListPanel, BorderLayout.NORTH);
    		actionPanel.add(customPanel, BorderLayout.CENTER);
    		/** Initializes the customPanel that holds the fields for parameters */
    		makeCustomPanelComponents();      
    
    		setLayout(new BorderLayout(5,5));
    		add(drawingPanel, BorderLayout.EAST);
    		add(selectionPanel, BorderLayout.WEST); 
    		add(actionPanel, BorderLayout.CENTER);
    
    
    	}
    
    
    	public void makeCustomPanelComponents()
    	{	
    
    		/** For displaying the actions for Location type objects */
    		locationActionList = new JComboBox(locationActions); 
    		/** an RtsItemActionListener object receives events from locationActionList */
    		locationActionList.addItemListener(new RtsItemActionListener());
    		JPanel locActionPanel = new JPanel();
    		locActionPanel.add(locationActionList);
    		ArrayList<JComponent> bsActionList = new ArrayList();
    		bsActionList.add(locActionPanel);        
    		actionComponents.put("BusStop" + actionListKeyword, bsActionList);
    
    		/** For diplaying the actions for Line objects */ 
    		lineActionList = new JComboBox(lineActions);
    		/** an RtsItemActionListener object receives events from lineActionList */
    		lineActionList.addItemListener(new RtsItemActionListener());
    		JPanel lineActionPanel = new JPanel();
    		lineActionPanel.add(lineActionList);
    		ArrayList<JComponent> lnActionList = new ArrayList();
    		lnActionList.add(lineActionPanel);
    		actionComponents.put("Line" + actionListKeyword, lnActionList);
    
    		/** For entering the name of the map item */
    		JLabel nLabel = new JLabel("Name");
    		name = new JTextField(10);
    		JPanel nPanel = new JPanel();
    		nPanel.add(nLabel);
    		nPanel.add(name);
    
    		JLabel dLabel = new JLabel("Duration");
    		duration = new JTextField("Duration", 3);
    		JPanel dPanel = new JPanel();
    		dPanel.add(dLabel);
    		dPanel.add(duration);
    
    		/** For entering the x and y coordinates */
    		JLabel xLabel = new JLabel("x");
    		x = new JTextField(4);
    		JPanel xPanel = new JPanel();
    		xPanel.add(xLabel);
    		xPanel.add(x);
    		JLabel yLabel = new JLabel("y");
    		y = new JTextField(4);
    		JPanel yPanel = new JPanel();
    		yPanel.add(yLabel);
    		yPanel.add(y);
    
    		firstH = new JTextField(4);
    		firstM = new JTextField(4);
    		JPanel firstPanel = new JPanel();
    		firstPanel.add(new JLabel("First"));
    		firstPanel.add(firstH);
    		firstPanel.add(new JLabel(":"));
    		firstPanel.add(firstM);
    
    		lastH = new JTextField(4);
    		lastM = new JTextField(4);
    		JPanel lastPanel = new JPanel();
    		lastPanel.add(new JLabel("Last"));
    		lastPanel.add(lastH);
    		lastPanel.add(new JLabel(":"));
    		lastPanel.add(lastM);
    
    
    		period = new JTextField(4);
    		JPanel periodPanel = new JPanel();
    		periodPanel.add(new JLabel("Period"));
    		periodPanel.add(period);
    
    
    		/** For checking or unchecking timePoint feature */
    		JLabel timePointLabel = new JLabel("Time Point?");
    		timePoint = new JCheckBox("", false);
    		timePoint.addActionListener((ActionListener)this);
    		JPanel tPanel = new JPanel();
    		tPanel.add(timePointLabel);
    		tPanel.add(timePoint);
    
    		/** For doing the chosen action on the selected object based on the entered parameter values */
    		JButton ok = new JButton("OK");
    		ok.setBackground(Color.blue);
    		/** See actionPerformed method to see the action taken */
    		ok.addActionListener((ActionListener)this);
    
    		/** As objects get created their names will be added to the corresponding list */
    		String[] busStopNames = {};
    		busStopList = new JComboBox(busStopNames);
    		busStopListDep = new JComboBox(busStopNames);
    		busStopListDest = new JComboBox(busStopNames);
    		String[] lineNames = {};
    		lineList = new JComboBox(lineNames);
    		JPanel bsListPanel = new JPanel();
    		bsListPanel.add(new JLabel("BusStop"));
    		bsListPanel.add(busStopList);
    		JPanel bsListPanelDep = new JPanel();
    		bsListPanelDep.add(new JLabel("Departure"));
    		bsListPanelDep.add(busStopListDep);
    		JPanel bsListPanelDest = new JPanel();
    		bsListPanelDest.add(new JLabel("Destination"));
    		bsListPanelDest.add(busStopListDest);
    
    
    		JPanel lnListPanel = new JPanel();
    		lnListPanel.add(new JLabel("Line"));
    		lnListPanel.add(lineList);
    
    		/** Custom panel components for creating a new busstop */
    		ArrayList<JComponent> newBSComponents = new ArrayList();
    		newBSComponents.add(nPanel);
    		newBSComponents.add(xPanel);
    		newBSComponents.add(yPanel);
    		newBSComponents.add(tPanel);      
    		newBSComponents.add(ok);
    		actionComponents.put("BusStopNew", newBSComponents);
    
    		/** Custom panel components for moving a busstop */
    		ArrayList<JComponent> moveBSComponents = new ArrayList();
    		moveBSComponents.add(bsListPanel);
    		moveBSComponents.add(xPanel);
    		moveBSComponents.add(yPanel);
    		moveBSComponents.add(ok);
    		actionComponents.put("BusStopMove", moveBSComponents);     
    
    		/** Custom panel components for showing a busstop on the map */
    		ArrayList<JComponent> showBSComponents = new ArrayList();
    		showBSComponents.add(bsListPanel);
    		showBSComponents.add(ok);
    		actionComponents.put("BusStopShow", showBSComponents);
    
    		/** Custom panel components for hiding a bus stop from the map display */
    		ArrayList<JComponent> hideBSComponents = new ArrayList();
    		hideBSComponents.add(bsListPanel);
    		hideBSComponents.add(ok);
    		actionComponents.put("BusStopHide", hideBSComponents);
    
    		/** Custom panel components for showing the lines that stop at a busstop */
    		ArrayList<JComponent> showLnsComponents = new ArrayList();
    		showLnsComponents.add(bsListPanel);
    		showLnsComponents.add(ok);
    		actionComponents.put("BusStopWrite Line Info", showLnsComponents);       
    
    		/** Custom panel components for creating a bus line */
    		ArrayList<JComponent> newLNComponents = new ArrayList();
    		newLNComponents.add(nPanel);
    		newLNComponents.add(bsListPanelDep);
    		newLNComponents.add(bsListPanelDest);
    		newLNComponents.add(firstPanel);
    		newLNComponents.add(lastPanel);
    		newLNComponents.add(periodPanel);
    		newLNComponents.add(ok);
    		actionComponents.put("LineNew", newLNComponents);
    
    		/** Custom panel components for adding a bus stop to a line */
    		ArrayList<JComponent> addBSComponents = new ArrayList();
    		addBSComponents.add(bsListPanel);
    		addBSComponents.add(dPanel);
    		addBSComponents.add(ok);
    		actionComponents.put("LineAdd BusStop", addBSComponents); 
    
    		/** Custom panel components for writing the schedule of a line to a file */
    		ArrayList<JComponent> writeSchComponents = new ArrayList();
    		writeSchComponents.add(lnListPanel);
    		writeSchComponents.add(ok);
    		actionComponents.put("LineWrite Schedule", writeSchComponents);           
    	}
    
    	private void resetFields()
    	{
    		name.setText("");
    		x.setText("");
    		y.setText("");
    		duration.setText("");
    		period.setText("");
    		firstH.setText("");
    		firstM.setText("");
    		lastH.setText("");
    		lastM.setText("");
    		timePoint.setSelected(false);
    
    	}
    
    	/** Removes the UI components in customPanel and adds the new components based on the selected shape and the action type */
    	private void updateCustomComponent()
    	{
    		resetFields();	
    
    		actionListPanel.removeAll();
    		actionListPanel.add(actionComponents.get(rtsItem + actionListKeyword).get(0), BorderLayout.NORTH);
    		actionListPanel.revalidate();
    		actionListPanel.repaint();
    
    		customPanel.removeAll();
    		ArrayList<JComponent> list = actionComponents.get(rtsItem + actionMode);
    		for(int i=0; i < list.size(); i++)
    			customPanel.add(list.get(i));
    		// Updates the view of the customPanel with new components
    		customPanel.revalidate();
    		customPanel.repaint();
    	}
    
    	public void paintComponent(Graphics g) {
    		super.paintComponents(g);
    		g.drawImage(busImage, 200, 200, 20, 20, this);
    	}
    
    	private void doAction() {
    		Graphics g = getGraphics();
    		String actionCommand = rtsItem + actionMode;
    		if (actionCommand.equals("BusStopNew")) {
    			BusStop bs = new BusStop(actionCommand, Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    			points.put(name.getText(), bs);
    			busStopList.addItem(name.getText());
    		}
    		else if (actionCommand.equals("BusStopShow")) {
    			repaint();
    		}
    		else if (actionCommand.equals("BusStopMove")) {
    			Location lo = points.get((String)busStopList.getSelectedItem());
    			lo.move(Integer.parseInt(x.getText()), Integer.parseInt(y.getText()));
    		}
    		customPanel.repaint();
    		resetFields();
    	}
    
    
    	/** Handles the OK button events */
    	public void actionPerformed(ActionEvent e) {
    		String command = e.getActionCommand();
    		if (command.equals("OK")) 
    			System.out.println(rtsItem + actionMode);
    		doAction();
    	}
    
    	public static void main(String[] args) {
    
    		MapApp myapp = new MapApp("The BusStop on the Map!"); 
    		myapp.setSize(1200, 600);
    		myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		myapp.setVisible(true);
    		myapp.updateCustomComponent();
    	}
    
    }
    I have reposed my code indicating where the problem is. It is at line 96. It says there is an unresolved compilation problem.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Java drawImage Not Showing Up in Program

    Quote Originally Posted by Brovahkiin501 View Post
    I have reposed my code indicating where the problem is. It is at line 96. It says there is an unresolved compilation problem.
    This means that you're trying to run code that can't be compiled, something that never should be attempted. You should first compile it, and if you get a compiler error, show us the error since the above error isn't very helpful, but the compiler's error likely *will* be helpful. I'm betting though that there's a risk that you're using an uninitialized variable. If so, trying setting the BufferedImage variable initially to null.

    Also note that you are declaring a busImage variable inside of a try block, and this means that this variable will exist *only inside of that block* which of course means that it will not be a very useful variable if it is invisible everywhere else in your program. Your program also declares a variable of the same name, but it will be null since it never gets initialized.
    Last edited by Fubarable; 03-29-2013 at 10:50 PM.

  7. #7
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,226
    Rep Power
    6

    Default Re: Java drawImage Not Showing Up in Program

    From your original question I noticed the following problems:

    1. Invoke paintComponent(), not paintComponents() (note the "s")
    2. Don't do I/O in the paintComponent() method.
    3. Don't use getGraphics() to do painting. All painting should be done in the paintComponent() method.

  8. #8
    Brovahkiin501 is offline Member
    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Default Re: Java drawImage Not Showing Up in Program

    Hi Fubarable,

    I tried initializing the BufferedImage variable to null right after the line that says
    Java Code:
     Buffered Image = mapImage;
    but then I get a syntax error on the semi-colon of
    Java Code:
     Buffered Image = mapImage;
    saying "Syntax error on token ";" , , expected" and I have NO idea why /:can you help me?

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

  10. #10
    Brovahkiin501 is offline Member
    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Default Re: Java drawImage Not Showing Up in Program

    Quote Originally Posted by Fubarable View Post
    What is a Buffered object? I've never heard of such a beast.
    Haha, I'm sorry I just wrote it wrong. The line should be:

    Java Code:
    BufferedImage mapImage;

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

Similar Threads

  1. My program is running, but it isnt showing up...
    By MW130 in forum New To Java
    Replies: 7
    Last Post: 01-15-2013, 03:55 AM
  2. Problem with drawImage
    By matevos in forum AWT / Swing
    Replies: 1
    Last Post: 08-06-2012, 10:44 PM
  3. DrawImage with transparency ?
    By mrhid6 in forum AWT / Swing
    Replies: 2
    Last Post: 10-01-2011, 11:58 PM
  4. drawImage im 13 plz help
    By pseudohawtcakes in forum New To Java
    Replies: 3
    Last Post: 05-17-2011, 08:07 PM
  5. Replies: 1
    Last Post: 03-30-2010, 09:23 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •