Jump to content
gongpex

java button clicked event

Recommended Posts

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...