• Post Reply Bookmark Topic Watch Topic
  • New Topic

JPanel component problem  RSS feed

Alex Kravets
Ranch Hand
Posts: 476
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a class that extends JPanel so I can use it in my other classes. What this class does is gets the url once it is entered in JTextField. The problem is that I paint the background of the JPanel blue, but there is some kind of border around the whole new component. I called class getBorder(), but it returns 'null'. I do not understand where this "border" is comming from. Below is the code and the image.
import java.applet.*;
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class URLField extends JPanel implements ActionListener {
private JButton button;
private JTextField urlField;
private AppletContext ac;
private JPanel jp;
private Color color;
private JLabel desc;
private Font descFont = new Font("Courier New", Font.PLAIN, 11);
public URLField(AppletContext ac, Color bg){
color = bg;
this.ac = ac;
jp = new JPanel();
System.out.println("BORDER: " + jp.getInsets());
button = new JButton("GO");
desc = new JLabel("url format: http://www.sitename...");
jp.setLayout(new BorderLayout(2,1));
urlField = new JTextField(20);
button.setMargin(new Insets(1,1,1,1));
button.setPreferredSize(new Dimension(30,21));
jp.add(urlField, BorderLayout.WEST);
jp.add(button, BorderLayout.CENTER);
jp.add(desc, BorderLayout.SOUTH);
public void paint(Graphics g){
Graphics gg = (Graphics)g;
public void actionPerformed(ActionEvent ae){
String str = urlField.getText();
if (ae.getSource() == button){
ac.showDocument(new URL(str), "_blank");
catch (Exception e) {
if(!((str.substring(0,3)).equals("http")) || !((str.substring(0,4)).equals("https")))
ac.showDocument(new URL("http://" + str), "_blank");
catch(Exception exp){}
JOptionPane.showMessageDialog(null,"No connection to URL, please contact technical support","URL ERROR",JOptionPane.ERROR_MESSAGE);

Angela Lamb
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "border" is showing up because your overridden paint method isn't written correctly. The background for the panel is never being changed. Just take the paint method out and add this line to your constructor:
There's no need to override the paint method if the only thing you need to do is change the background.
Also, to explain why your paint method is not working - the setColor method of the Graphics object doesn't do anything other than setting the color for future painting. To actually paint the background, you would need to use something like the fillRect method.
[ June 04, 2002: Message edited by: Angela Lamb ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!