SWING ISSUE
Hi
I have a problem with SWING. I wish to paint a small icon over the corner of a text field. I wish to do this without using the glass pane or the layered pane approach.
At present the icon is painted behind the textfield even though I am overridding paint(Graphics g) and then painting my icon last. For example the painting process is in the following order:
paint(Graphics g)
paintComponent(Graphics g)
paintBorder(Graphics g)
paintChildren(Graphics g)
paintIcon(Graphics g)
The program is below:
You will need the following icon from:
http://images.google.co.uk/images?q=blue+square+icon&imgsz=icon&svnum=10&hl=en&start=20&sa=N&ndsp=20
-
BlueSquare.gif
10 x 10
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class Problem {
private static final String BLUE_SQUARE_ICON = "BlueSquare.gif";
public Problem() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300,300));
frame.getContentPane().add(new Panel());
frame.pack();
frame.setVisible(true);
}
private class Panel extends JPanel{
public Panel () {
setLayout(new GridBagLayout());
Dimension componentSize = new Dimension(80,30);
ImageIcon icon = createImageIcon(BLUE_SQUARE_ICON);
Image img = icon.getImage();
JTextField textField = new SomeTextField(img);
textField.setPreferredSize(componentSize);
JTextField textField2 = new JTextField();
textField2.setPreferredSize(componentSize);
JTextField textField3 = new SomeTextField(img);
textField3.setPreferredSize(componentSize);
Component space = Box.createRigidArea(componentSize);
Component space2 = Box.createRigidArea(componentSize);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy++;
add(textField, gbc);
gbc.gridy++;
add(space, gbc);
gbc.gridy++;
add(textField2, gbc);
gbc.gridy++;
add(space2, gbc);
gbc.gridy++;
add(textField3, gbc);
}
public void paint(Graphics g) {
super.paint(g);
paintIcon(g);
}
public void paintIcon(Graphics g) {
Component[] comps = getComponents();
for (Component component : comps) {
if (component instanceof SomeTextField) {
SomeTextField someTextField = (SomeTextField)component;
Rectangle bounds = someTextField.getBounds();
int w = (int)bounds.getWidth();
int h = (int)bounds.getHeight();
int x = (int)bounds.getX();
int y = (int)bounds.getY();
Image image = someTextField.getImage();
if (image != null) {
g.drawImage(image,(x - 5) + w , (y - 7) + h, this);
}
}
}
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
private ImageIcon createImageIcon(String path) {
URL imgURL = Panel.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
}
else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private class SomeTextField extends JTextField {
private Image m_Image = null;
public SomeTextField(Image image) {
m_Image = image;
}
public Image getImage() {
return m_Image;
}
}
public static void main(String[] args) {
new Problem();
}
}

