Reputation: 2301
I want to create a panel with a titledborder. And the title needs to be clickable. Is there a way to do this? Because when I place a mouslistener on the panel you can click everywhere on the panel the event happens. And it must be triggered only when I click on the title of the titledborder
Upvotes: 0
Views: 377
Reputation: 11
In case anyone needs it, here is a working example as per camickr's suggestion.
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
final Border border = panel.getBorder();
if (border instanceof TitledBorder) {
final TitledBorder tb = (TitledBorder) border;
final FontMetrics fm = panel.getFontMetrics(panel.getFont());
final int titleWidth = fm.stringWidth(tb.getTitle()) + 20;
final Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
if (bounds.contains(e.getPoint())) {
// YOUR BUSINESS LOGIC
}
}
}
});
Upvotes: 1
Reputation: 324118
Here is an example that displays a tooltip when you hover over the title of the TitledBorder:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderTest
{
private static void createAndShowUI()
{
UIManager.getDefaults().put("TitledBorder.titleColor", Color.RED);
Border lowerEtched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
String titleText = "Long title that will be truncated in the panel";
TitledBorder title = BorderFactory.createTitledBorder(lowerEtched, titleText);
JPanel panel = new JPanel()
{
@Override
public String getToolTipText(MouseEvent e)
{
Border border = getBorder();
if (border instanceof TitledBorder)
{
TitledBorder tb = (TitledBorder)border;
FontMetrics fm = getFontMetrics( getFont() );
int titleWidth = fm.stringWidth(tb.getTitle()) + 20;
Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
return bounds.contains(e.getPoint()) ? super.getToolTipText() : null;
}
return super.getToolTipText(e);
}
};
panel.setBorder( title );
panel.setToolTipText(title.getTitle());
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
The concept should be similar when using a MouseListener on the panel.
Upvotes: 1