java – 在JTabbedPane标头中添加JLabel
作者:互联网
我有一个带有JTabbedPane的JDialog:
我只是想在JTabbedPane的右上角区域添加一个JLabel,这样我就可以触发一些事件(例如关闭JDialog).
我不想把它变成JFrame.
PS:我知道这可能是重复的,但没有一个回复给我一个解决方案.
解决方法:
实际上,在Swing中不支持JTabbedPane中的定位.但你可以随时使用布局和图层制作一些街头魔术:
public static void main ( String[] args )
{
try
{
UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName () );
}
catch ( Throwable e )
{
e.printStackTrace ();
}
JFrame frame = new JFrame ();
frame.setUndecorated ( true );
frame.setLayout ( new LayoutManager ()
{
private List<Component> special = new ArrayList<Component> ();
public void addLayoutComponent ( String name, Component comp )
{
if ( name != null )
{
special.add ( comp );
}
}
public void removeLayoutComponent ( Component comp )
{
special.remove ( comp );
}
public Dimension preferredLayoutSize ( Container parent )
{
Dimension ps = new Dimension ();
for ( Component component : parent.getComponents () )
{
if ( !special.contains ( component ) )
{
Dimension cps = component.getPreferredSize ();
ps.width = Math.max ( ps.width, cps.width );
ps.height = Math.max ( ps.height, cps.height );
}
}
return ps;
}
public Dimension minimumLayoutSize ( Container parent )
{
return preferredLayoutSize ( parent );
}
public void layoutContainer ( Container parent )
{
Insets insets = parent.getInsets ();
for ( Component component : parent.getComponents () )
{
if ( !special.contains ( component ) )
{
component.setBounds ( insets.left, insets.top,
parent.getWidth () - insets.left - insets.right,
parent.getHeight () - insets.top - insets.bottom );
}
else
{
Dimension ps = component.getPreferredSize ();
component.setBounds ( parent.getWidth () - insets.right - 2 - ps.width,
insets.top + 2, ps.width, ps.height );
}
}
}
} );
final JTabbedPane tabbedPane = new JTabbedPane ();
tabbedPane.addTab ( "Tab1", new JLabel () );
tabbedPane.addTab ( "Tab2", new JLabel () );
tabbedPane.addTab ( "Tab3", new JLabel () );
frame.add ( tabbedPane );
final JLabel label = new JLabel ( "Close X" );
label.addMouseListener ( new MouseAdapter ()
{
public void mousePressed ( MouseEvent e )
{
System.exit ( 0 );
}
} );
frame.add ( label, "special", 0 );
frame.setSize ( 200, 150 );
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setVisible ( true );
}
这将在任何地方都可以正常工作.请注意,标签将始终位于右上角,并且不会定位自己(除非您修改代码以支持更多“功能”)在其他OS LaF上,例如Mac OS laf,其中选项卡可能位于中间.如果它们与标签交叉,它也将被涂在标签上.
所以你会得到这样的东西:
无论如何,您可以轻松修改应用于布局内部的JLabel边界,以制作一些侧面间距等…
标签:java,swing,jlabel,jdialog,jtabbedpane 来源: https://codeday.me/bug/20190716/1480892.html