• Post Reply Bookmark Topic Watch Topic
  • New Topic

SetBackground for JFrame  RSS feed

 
raymond hsu
Greenhorn
Posts: 23
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
I tried to set foreground or background color of JFrame with no success,

setLocation, setSize works

below are my codes :

JFrame fr = new JFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocation(100,100);
JTextField tf = new JTextField();
fr.add(tf, BorderLayout.CENTER);
fr.setBackground(Color.RED);

fr.setSize(550,200);

fr.setForeground(Color.GREEN);
fr.setVisible(true);

From stackover, some suggest to use
Container c = fr.getContentPane();
c.setBackground(Color.RED);

I tried this suggestion, it didn't work as well.

Can anyone help?
Thanks
 
Knute Snortum
Sheriff
Posts: 4087
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please surround your code with code tags the next time you post code. I have added this thread to the Swing forum.
 
Campbell Ritchie
Marshal
Posts: 55775
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't make such changes to a frame or other top‑level container because you will add things to that frame and hide the red colour.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Raymond,

add this line right below the line where you define your 'tf' textfield:

Now have a look at the frame. Can you explain what you see? (hint: type some characters).
 
Rob Camick
Ranch Hand
Posts: 2801
15
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


That code will work.

The problem is you also use:



so the text field covers the entire content pane.

Instead try:

 
raymond hsu
Greenhorn
Posts: 23
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Camick,

it works now, wonderfully
I will find out details of JFrame add components,
as I merely copy some existing code without understanding it.

Thanks.
 
Rob Camick
Ranch Hand
Posts: 2801
15
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as I merely copy some existing code without understanding it.


I suggest you start with code you find in the Swing tutorial.

Most of the code there has explanations and the code will be better structured.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!