gpt4 book ai didi

java - 在 JTabbedPane header 中添加一个 JLabel

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:20 24 4
gpt4 key购买 nike

我有这个带有 JTabbedPane 的 JDialog:

enter image description here

我只想在 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 标签可能位于中间)上定位自身(除非您修改代码以支持更多“功能”)。如果标签与标签交叉,它也会被绘制在标签上。

所以你会得到这样的东西:

enter image description here

无论如何,您可以轻松地修改应用到布局内的 JLabel 边界以制作一些侧边距等...

关于java - 在 JTabbedPane header 中添加一个 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10620630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com