Ahmad Rajab
Ahmad Rajab

Reputation: 11

Drawing Swing components inside a Graphics object

is there any way I can make a Java Graphics object (g) draw a swing component? like a button or JLabel

something like g.drawJLabel ?

I'm trying to add a clickable text (Link) inside my graphic object but it's not possible to add a mouse listener to the graphics objects

Upvotes: 0

Views: 145

Answers (1)

Sync it
Sync it

Reputation: 1198

Your clickable text can be an JLabel with an mouselistener

 JLabel hyperlink=new JLabel("Click me");

 hyperlink.addMouseListener(new MouseAdapter()
{
 @Override
 public void mouseEntered(MouseEvent m)
 {
  hyperlink.setForeground(Color.blue);
 }

 @Override
 public void mouseExited(MouseEvent m)
{
 hyperlink.setForeground(Color.black);
}

 @Override
  public void mouseClicked(MouseEvent m)
  {
    if (Desktop.isDesktopSupported() && 
    Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
    Desktop.getDesktop().browse(new URI(hyperlink.getText())));
    }
   }

Make sure that your graphical object has some form of layout manager otherwise your text won't show up

Then inside your graphical objects which I assume all of them extends some form of JComponent you can add this text to your object and your text will still receive user input

Upvotes: 0

Related Questions