Jump to content
  • Advertisement
Sign in to follow this  
monp

[Java] My color changing button is not working.

This topic is 2857 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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();

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!