JAVA JPanel and JFrame problem

0 Anshuman Kaushik · May 28, 2015
i have created a JPanel class and created a rectangle with blue color and then i create a JFrame class and made a button and add action listener to it.....in action listener i add a JColorchooser box.... so i want to do that when someone chooses color by clicking button then rectangle color will change as color choosen by user...

Post a Reply

Replies

Oldest  Newest  Rating
0 Anshuman Kaushik · June 2, 2015
Thanks a lot brother :)
+1 Javier Perez · May 29, 2015
Try calling repaint(); inside the listener.

If not this works for me:

import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class graphics extends JPanel{
    private Color c = (Color.BLACK);
    public void setC(Color co){
        c = co;
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(c);
        g.drawRect(100,100,50,50);
        g.fillRect(100, 100, 50, 50);
    }
}


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class window extends JFrame{
    private Color colors;
    private JButton button;
    public void w(){
        button = new JButton("Colors");
        graphics panel = new graphics();
        button.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent event){
                        colors = JColorChooser.showDialog(null, "Chooser a Color", colors);
                        panel.setC(colors);
                        panel.repaint();
                    }
                }
        );
        panel.setBackground(Color.BLUE);
        add(BorderLayout.CENTER, panel);
        add(button, BorderLayout.SOUTH);
    }
}


import javax.swing.JFrame;

@SuppressWarnings("serial")
public class run extends JFrame{
    public static void main(String args[]){
        window go = new window();
        go.w();
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(250,250);
        go.setVisible(true);
    }
}


+1 Javier Perez · May 29, 2015
Did it work?
  • 1

Java / Android Development

107,080 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator