[Java] My color changing button is not working.

Started by
1 comment, last by monp 13 years, 7 months ago
I am doing the tutorials from the book Learning Java and I am having trouble finding out why my button that is suppose to change the foreground color is not working. Any help is appreciated.

Gui2.class
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Gui2{	public static void main(String[] args)	{		JFrame frame = new JFrame("Gui Loaded");		frame.add(new GuiCore2("Core has been loaded!"));		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		frame.setSize(640, 480);		frame.setVisible(true);	}}


GuiCore2.class
class GuiCore2 extends JComponent implements MouseMotionListener, ActionListener{	String message;	int m_x = 125;	int m_y = 95;		JButton button;		int colorIndex;	static Color[] colors = {Color.black, Color.red, Color.blue, Color.green};		public GuiCore2(String msg)	{		message = msg;		button = new JButton("Change Colors");		setLayout(new FlowLayout());		add(button);		button.addActionListener(this);		addMouseMotionListener(this);	}		public void paintComponent(Graphics g)	{		g.drawString(message, m_x, m_y);	}		public void mouseDragged(MouseEvent e)	{		m_x = e.getX();		m_y = e.getY();	}		public void mouseMoved(MouseEvent e)	{	}		public void actionPerformed(ActionEvent e)	{		if(e.getSource() == button)		{			changeColor();		}	}		synchronized private void changeColor()	{		if(++colorIndex == colors.length)		{			colorIndex = 0;			setForeground(currentColor());			repaint();		}	}		synchronized private Color currentColor()	{		return colors[colorIndex];	}}
Advertisement
Here:

if(++colorIndex == colors.length){    colorIndex = 0;    setForeground(currentColor());    repaint();}


You probably meant to write:

if(++colorIndex == colors.length)    colorIndex = 0;setForeground(currentColor());repaint();
Wow I can't believe I missed that, thanks.

This topic is closed to new replies.

Advertisement