Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to add components to JFrame after coloring the JFrame

 
Sunil Babu
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
I got this problem
" iam not able to add components to the frame(JFrame) which i created it below is the code which i used if u got any suggestions please do advice me
bye

import java.util.*;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
public class Swg extends JFrame implements ActionListener
{
Timer tm;
JLabel l1,l2;
JTextField t1,t2;
JButton b1,b2;
JPanel pn;
Swg()
{
tm = new Timer(10000,this);
tm.start();
java.awt.Container cn = this.getContentPane();
pn = new JPanel();
l1 = new JLabel("User ID");
t1 = new JTextField(10);
l2 = new JLabel("Password");
t2 = new JTextField(10);
b1 = new JButton("Login");
b2 = new JButton("Exit");
pn.add(l1);
pn.add(t1);
pn.add(l2);
pn.add(t2);
pn.add(b1);
pn.add(b2);
cn.add(pn);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == tm)
{
System.exit(0);
}
repaint();
}

public void paint (Graphics g)
{
setForeground(java.awt.Color.orange);
g.fillRect(0,0,500,200);
setForeground(java.awt.Color.black);
g.drawString("HELLOOOOOOO",30,30);

}
public static void main(String[] args)
{
JFrame f = new Swg();
f.setSize(500,200);
f.setLocationRelativeTo(null);
f.setUndecorated(true);
f.show();

}
}//eof clas Swg
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When using Swing one shouldn't use the paint(Graphics g) method, one should instead use the paintComponent(Graphics g) method.
Swing components have 5 paint methods:
1) repaint() -- calls paint (and does other things)
2) paint(Graphics g) -- calls paintBorder(Graphics g), paintChildren(Graphics g), and paintComponent(Graphics g). Best to leave this alone, to make sure everything gets painted correctly
3) paintBorder(Graphics g) -- paints the area surrounding the visible area of your container (the 'border' if you would). You can override this to create a custom border for you swing component
4) paintChildren(Graphics g) -- calls the paint method for each of the components added to this components content pane. Best not to touch this.
5) paintComponent(Graphics g) -- paints the contents of the current component. You should use this to change backgrounds, make neat shapes, or do most of your graphics work.
So if you do paint(Graphics g) make sure you call the paintBorder and painChildren methods at the TOP of your method, but you can run into trouble, so it is best if you avoid using it, and instead just use paintComponent
Steve, master of the way too long post
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic