Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Swing Eclipse
Hi,
I am creating a GraphGUI. I have attached 2 panels a GraphPanel(for graph sheet) and a COntrolPanel(for button controls). I placed two buttons a 'sine' and 'cosine' which should display it's corresponding wave on GraphPanel upon clicking them. Right now I am doing event handling for my GUI and I am having problem there.
Here is the code:
1) Main Class:
 public class GraphGUI extends JFrame {
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame f = new MainFrame("GraphGUI");
				f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				f.setVisible(true);
				f.setSize(900, 725);
				f.setResizable(false);
			}
		});
	}
} 
2)Frame Class:
 public class MainFrame extends JFrame {
	private GraphPanel gPanel;
	private ControlPanel pPanel;	
	public MainFrame(String title) {
		super(title);		
		pPanel = new ControlPanel();
		gPanel = new GraphPanel();		
		Container con = getContentPane();		
		con.add(pPanel, BorderLayout.EAST);
		con.add(gPanel, BorderLayout.WEST);		
		pPanel.addGraphListener(new GraphListener() {
			@Override
			public void graphEventOccured(GraphEvent event) {
				System.out.println("hi");				
			}			
		}, gPanel);
	}
} 
3) GraphPanel Class:
public class GraphPanel extends JPanel {
	public GraphPanel() {
		super();
		setBorder(BorderFactory.createLineBorder(Color.black));		
		Dimension size = getPreferredSize();
		size.width = 666;
		setPreferredSize(size);
		setBackground(Color.black);
	}	
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		final int h = getHeight();
		final int w = getWidth();
		System.out.println("h = " + h + "\tw = " + w);
		g2.setColor(Color.RED);
		g2.drawLine(300, 0, 300, h);
		g2.drawLine(0, 340, w, 340);
		g2.setColor(Color.GREEN);
		int i = 1;
		int z  = 1;
		while(z > 0) {
			z = 300 - (i*20);
			g2.drawLine(z, 0, z, h);
			i++;
		}
		i = 1;
		while(z < w) {
			z = 300 + (i*20);
			g2.drawLine(z, 0, z, h);
			i++;
		}
		i = 1;
		while(z > 0) {
			z = 340 - (i*20);
			g2.drawLine(0, z, w, z);
			i++;
		}
		i = 1;
		while(z < h) {
			z = 340 + (i*20);
			g2.drawLine(0, z, w, z);
			i++;
		}
	}
}
4) ControlPanel Class:
 public class ControlPanel extends JPanel {
	private JButton sineBtn;
	private JButton cosineBtn;	
	private EventListenerList listenerList = new EventListenerList();
	public ControlPanel() {
		super();
		setBorder(BorderFactory.createLineBorder(Color.green));
		setLayout(new GridBagLayout());
		Dimension size = getPreferredSize();
		size.width = 300;
		setPreferredSize(size);
		setLayout(new GridBagLayout());
		
		sineBtn = new JButton("Sine");
		cosineBtn = new JButton("Cosine");
		
		//action listener for sineBtn
		sineBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				fireGraphEvent(new GraphEvent(this));//exception here when Sine Button is clicked
			}			
		});
		//action listener for cosineBtn
		cosineBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				fireGraphEvent(new GraphEvent(this));//exception here when Cosine Button is clicked				
			}
		});		
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();		
		//adding buttons
		gc.anchor = GridBagConstraints.CENTER;
		gc.weightx = 0.5;
		gc.weighty = 0.5;
		//changing the default size of the buttons
		gc.ipadx = 40;
		gc.ipady = 40;
		//adding sineBtn
		gc.gridx = 0;
		gc.gridy = 0;
		add(sineBtn, gc);
		//adding cosineBtn
		gc.gridx = 0;
		gc.gridy = 1;
		add(cosineBtn, gc);
	}	
	public void fireGraphEvent(GraphEvent event) {
		Object[] listeners = listenerList.getListenerList();
		for(int i = 0; i < listeners.length; i++) {
			if(listeners[i] == GraphListener.class) {
				((GraphListener)listeners[i]).graphEventOccured(event);//exception here for both events
			}
		}
	}
	public void addGraphListener(GraphListener listener, GraphPanel gPanel) {
		listenerList.add(GraphListener.class, listener);
	}	
	public void removeGraphListener(GraphListener listener) {
		listenerList.remove(GraphListener.class, listener);
	}
} 
5)GraphEvent Class:
public class GraphEvent extends EventObject {
    public GraphEvent(Object source) {
        super(source);
        System.out.println("Source : " + source);
    }
}
6) GraphListener Interface:
public interface GraphListener extends EventListener {
    public void graphEventOccured(GraphEvent event);
}
 
Right now I am not at the stage of plotting waves, I am just checking whether my events are occurring as desired and expected. Exceptions are occurring in ControlPanel class as mentioned in the code. Please show me where am I erring and point me in the right direction for plotting sine waves and cosine waves in my GUI.
 
Thank you for your valuable time.
Posted 28-Aug-12 21:45pm
Edited 29-Aug-12 2:11am
TorstenH.33.8K
v3
Comments
Mehdi Gholam at 29-Aug-12 2:51am
   
What exceptions are you getting?
stib_markc at 29-Aug-12 2:56am
   
This is what the log shows:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Class cannot be cast to GraphListener
at ControlPanel.fireGraphEvent(ControlPanel.java:74)
at ControlPanel$2.actionPerformed(ControlPanel.java:46)
Richard MacCutchan at 29-Aug-12 4:09am
   
In the statement ((GraphListener)listeners[i]).graphEventOccured(event);, your cast is not valid.
stib_markc at 29-Aug-12 4:15am
   
Yes, the problem is I wrote the code similarly in another application and it worked, but I can't understand why this is not valid here. Of-course in that application no graph was involved, but here also before involving my GraphPanel, the exceptions arouse.
Richard MacCutchan at 29-Aug-12 4:46am
   
If you are using casts in your code without understanding them then you are on the road to some major problems in your development. Take a look at the section on it in this tutorial.
stib_markc at 29-Aug-12 4:59am
   
please modify the link, it echoes this page only.
No, I am casting there because 'listener[i]' will be a type of EventListener, from which my GraphListener is derived, so I think there shouldn't be any problem, becase I am passing ActionListener(derived from EventListener) object to fireGraphEvent method.
Richard MacCutchan at 29-Aug-12 6:13am
   
Sorry about that; something to do with the 'intelligent' editor. With reference to your actual cast, the error message is clearly telling you that you cannot use this cast in this situation, so you need to change your code to fix it. It's not good saying "I think there shouldn't be any problem", as there clearly is one.
TorstenH. at 29-Aug-12 4:47am
   
...What are you actually trying to achieve with this construction?
Way to complicated. Make it simpler.
stib_markc at 29-Aug-12 5:10am
   
I know there might be easier ways to do this event handling, but to maintain the code and add additional features(controls and their event handlers), I am handling all the event via a single interface. Anyway, what i want to achieve is display sine and cosine waves upon clicking the corresponding buttons. Please point me in right direction, ignore my code(if necessary), I am open to try other ways also, but I wanted to share what I have tried so far. Thank you.
Nagy Vilmos at 29-Aug-12 6:14am
   
If you had read the code, you'd have seen a simple error.
Try and answer the question rather than impart you colossal intellect upon us mere mortals.
stib_markc at 29-Aug-12 6:23am
   
Please do not mock me. :)
I am just a beginner to Java as well as to programming.
Nagy Vilmos at 29-Aug-12 6:28am
   
Not you, but Torsten. He has a habit of telling people to do things a different way.
 
Looking at your code, it should be okay and is a sensible approach. It is better to have several small specialised classed then one big monolith class. What you are doing with two graphs could be done more simply, but as soon as you start adding more graphs the complexity will grow to an unmanageable state.
TorstenH. at 29-Aug-12 7:26am
   
...There is a simple error - and he is not able to see it.
Why? The code might not be maintainable to him.
You might have noticed that this is not his first question towards Swing/GUI creation.
 
Yes, I sometimes suggest to rethink something. That's what I do when I struggle on some task. But there might be others who cannot fail - right Nagy?
Richard MacCutchan at 29-Aug-12 6:22am
   
I have just looked at this again, and suspect that the exception actually occurs on the preceding line where you are trying to compare with a class, but I think you may need to use the instanceof operator as described on this page.
Nagy Vilmos at 29-Aug-12 6:29am
   
Better to use isAssignableFrom as that allows for future sub-classes without needing to re-write the code.
Richard MacCutchan at 29-Aug-12 7:49am
   
Quite right. It's a while since I did something similar so I chose the first one that came into my head.
stib_markc at 29-Aug-12 6:32am
   
Yes, instanceof also works.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

The comparison in the if statement is wrong, you want to know if the item in the listener array can be cast to a GraphListener. This works:
 
if (GraphListener.class.isAssignableFrom(listeners[i].getClass())) {
  Permalink  
Comments
stib_markc at 29-Aug-12 6:18am
   
Thank you, it worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 319
1 Maciej Los 295
2 Sergey Alexandrovich Kryukov 230
3 CPallini 205
4 Sinisa Hajnal 166
0 OriginalGriff 7,760
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,785


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 29 Aug 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100