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 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


Oldest  Newest  Rating
+1 Javier Perez · May 29, 2015
Try calling repaint(); inside the listener.

If not this works for me:

import java.awt.*;

import javax.swing.*;

public class graphics extends JPanel{
    private Color c = (Color.BLACK);
    public void setC(Color co){
        c = co;
    public void paintComponent(Graphics g){
        g.fillRect(100, 100, 50, 50);

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

import javax.swing.*;

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

import javax.swing.JFrame;

public class run extends JFrame{
    public static void main(String args[]){
        window go = new window();

+1 Javier Perez · May 29, 2015
Did it work?
0 Anshuman Kaushik · June 2, 2015
Thanks a lot brother :)
  • 1

Java / Android Development


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

Bucky Roberts Administrator