我想创建一个带有标题边框的面板。标题需要点击。有没有办法做到这一点?因为当我在面板上放置一个mouslistener时,你可以点击面板上的任何地方事件发生。只有当我点击titledborder的标题
时才能触发它答案 0 :(得分:0)
以下是将鼠标悬停在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();
}
});
}
}
在面板上使用MouseListener时,概念应该类似。
答案 1 :(得分:0)
万一有人需要,这是根据camickr的建议工作的示例。
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
}
}
}
});