gongpex

java button clicked event

2 posts in this topic

Hello everyone,

 

I'm still new to learn java,

 

I take code from o'reilly book about GUI, this my code :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui3c implements ActionListener {
    
	JFrame frame;

	public static void main(String[] args) {
		SimpleGui3c gui = new SimpleGui3c();
		gui.go();
	}
	
	public void go(){
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JButton button = new JButton("Change new colors");
		button.addActionListener(this);
		
		MyDrawPanel drawpanel = new MyDrawPanel();
		
		frame.getContentPane().add(BorderLayout.SOUTH, button);
		frame.getContentPane().add(BorderLayout.CENTER, drawpanel);
		frame.setSize(300,300);
		frame.setVisible(true);
		
	}
	
	public void actionPerformed(ActionEvent e){
		frame.repaint();
		
	}

}

and this MyDrawPanel class :

import javax.swing.*;
import java.awt.*;

public class MyDrawPanel extends JPanel {
		
		public void paintComponent(Graphics g){
			//Image img = new ImageIcon("double/image/test.jpg").getImage();
			//g.drawImage(img,5,5,this);
			
			g.setColor(Color.blue);
			g.fillOval(70, 70, 100, 100);
			
			g.setColor(Color.orange);
			g.fillOval(70, 70, 100, 100);
		}
		
	}
I had tried to change color using JButton ,so, when I clicked the button it supposed there is change color from blue, turn into orange,
but this didn't work....
Maybe there is something wrong on my code?
Please help me
Thanks

Share this post


Link to post
Share on other sites

The problem is your color will always be orange, because paintComponent() sets the color to blue but then immediately sets it back to orange. You need paintComponent to set a desired color...

public class MyDrawPanel extends JPanel {
        int color = 0;

	public void setColor(int c){
           color = c;
        }

	public void paintComponent(Graphics g){
	       
		if (color == 0){
		   g.setColor(Color.blue);
		} else if (color == 1){
		   g.setColor(Color.orange);
                }else{
                   g.setColor(Color.red);
                }

		g.fillOval(70, 70, 100, 100);
	}
		
}
//declare drawpanel outside of go()

public void actionPerformed(ActionEvent e){

   drawpanel.setColor(1);
   frame.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