darkpegasus5
asked on
How do I overlay a JLabel image with text?
I am extending the JLabel class using the JLabel(ImageIcon imageicon) constructor.
What I would like to do is put text directly in the center of the label, directly overlaying the image itself.
I have tried code like the following, which does not seem to work:
public void paint(Graphics g)
{
super.paint(g);
g.drawString("some text", 5, 5);
}
the JLabel itself is about 20 x 20 so I would think that I would at least see something. Thanks in advance for any help.
What I would like to do is put text directly in the center of the label, directly overlaying the image itself.
I have tried code like the following, which does not seem to work:
public void paint(Graphics g)
{
super.paint(g);
g.drawString("some text", 5, 5);
}
the JLabel itself is about 20 x 20 so I would think that I would at least see something. Thanks in advance for any help.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That did it, thanks!
:-)
mb...
mb...
import javax.swing.*;
import javax.swing.text.*;
import java.util.StringTokenizer;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
class labelTest extends JDialog implements ActionListener{
JTextField txtField = new JTextField();
JButton btnOk = new JButton("Ok");
int lineNumber = 0;
// Fetch icon
ImageIcon icon = new ImageIcon("c:\\somegif.gif
// Create a label with text and an icon; the icon appears to the left of the text
JLabel label = new JLabel("Text Label", icon, JLabel.CENTER);
public labelTest(Dialog dlg, boolean modal){
JLabel label = new myLabel("Text Label", icon.getImage()); //, JLabel.TOP)
btnOk.setName("Ok");
//this.getContentPane().ad
this.getContentPane().add(
this.getContentPane().add(
btnOk.addActionListener(th
this.setTitle("Select Line no.");
this.setSize(200, 100);
this.setModal(modal);
this.show();
}
public void actionPerformed(ActionEven
Object obj = event.getSource();
if(obj instanceof JButton){
if(((JButton)obj).getName(
String str = txtField.getText();
if(str != null && ! str.equals("")){
try{
lineNumber = Integer.parseInt(str);
}catch(Exception ex){
lineNumber = 0;
}
}
this.setVisible(false);
System.exit(0);
}
}
}
int getLineNumber(){
return lineNumber;
}
public static void main(String[] s){
new labelTest(null, true);
}
}
class myLabel extends JLabel{
Image image;
String text;
public myLabel(String text, Image image) {
this.image = image;
this.text = text;
}
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint background
// Draw image at its natural size first.
g.drawImage(image, 25, 10, this);
g.drawString("mystring", 15,28) ;
}
}