Sign in to follow this  
monp

[Java] My color changing button is not working.

Recommended Posts

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];
}
}

Share this post


Link to post
Share on other sites
Here:

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


You probably meant to write:

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this