problem with awt.Color

T

tss

Hi,
It's my first application with JFrame. I have a problem with changing
colors in my application.
Frame name is: JFrame1.
It contains a JPanel class named jPanel1.
The panel contains a JButton.
Event handler for the button has this code, which does nothing to the
colors. It only draws in black no matter what the color is:

jPanel1.getGraphics().setColor(java.awt.Color.blue);
jPanel1.getGraphics().drawRect(0,0,100,100);

I tried to change the foreground:

jPanel1.setForeground(java.awt.Color.blue);

It drew also in black !!!!!!

can anyone explain this to me?????

Thanks alot :)
 
A

ak

//your JButton

Color rc;

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(rc);
g.drawRect(0,0,100,100);
}

event handler should set rc and call repaint();
 
A

Andrew Thompson

ak said:
//your JButton

Color rc;

public void paintComponent(Graphics g) {

What is it with coder's penchant for stuffing
paint/repaint/paintComponent?

Personally I blame all the 'Java in 24hrs'
books that start with things like..
'..now lets set the layout of the applet to
null before we call paint'.. Aaaargh!

Try this code that does not use any of those things..
(I might put it on my site later ..no it's too trivial)
____________________________________________
import javax.swing.*;
import java.awt.Color;
import java.awt.BorderLayout;

public class JColoredButtonFrame extends JFrame
{
JButton b1, b2;

JColoredButtonFrame()
{
b1 = new JButton("White");
b1.setForeground(Color.WHITE);
b1.setBackground(Color.BLACK);
b1.setOpaque(true);

b2 = new JButton("Normal");

getContentPane().add(b1, BorderLayout.NORTH);

getContentPane().add(b2, BorderLayout.SOUTH);

pack();
setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
setVisible(true);
}

public static void main(String args[])
{
JColoredButtonFrame cbf = new JColoredButtonFrame();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top