gpt4 book ai didi

java - JTabbedPane:更改选项卡标题时更改选项卡大小

转载 作者:行者123 更新时间:2023-11-30 04:53:23 25 4
gpt4 key购买 nike

我的 JFrame 中有一个 JTabbedPane myTab。它的第一个选项卡的标题为“旧标题”。我想动态改变标题,所以我用这段代码来设置:

myTab.setTitleAt(myTab.getSelectedIndex(), "my full new title");

不知何故,我的新标题比旧标题更长。问题是,选项卡大小没有改变,并且没有完全显示新标题,只有“我的完整n...”。

如果我单击该选项卡,该选项卡突然可以显示完整的新标题。

我也已经尝试过这段代码来设置标题名称:

myTab.setTabComponentAt(myTab.getSelectedIndex(), new JLabel("my full new title"));

此代码可以帮助我根据新标题更改选项卡大小。但是用于关闭选项卡的十字 (x) 不再存在。

有谁知道如何在更改选项卡标题时更改选项卡大小,但仍保留关闭选项卡选项?

谢谢您,非常感谢!

最佳答案

我没见过

但这仅在一种情况下可能,您运行的代码超出了 EDT,

Swing 是单线程的,对 Swing GUI 的所有更改都必须在事件调度线程上完成,有关此主题的更多信息请参见 Concurency in Swing ,(我建议在这个论坛上搜索这个共同话题),

enter image description here enter image description here

来自代码,

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Random;
import javax.swing.*;

/*based on @trashgod code original code
@see http://stackoverflow.com/questions/5617027 */
public class Cab extends JPanel {

private static final Random random = new Random();
private static final String format = "00000000";
private static final DecimalFormat df = new DecimalFormat(format);
private static JTabbedPane tabbedPane = new JTabbedPane();
private static final long serialVersionUID = 1L;
private Hue hue = Hue.Yellow;
private Timer timer;
private JLabel odometer = new JLabel(df.format(0));
private int km;

public Cab() {
this.setPreferredSize(new Dimension(320, 240));
this.setBackground(hue.getColor());
this.add(odometer);
final JComboBox colorBox = new JComboBox();
for (Hue h : Hue.values()) {
colorBox.addItem(h);
}
colorBox.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
Hue h = (Hue) colorBox.getSelectedItem();
Cab.this.setBackground(h.getColor());
tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), "my full new title");
}
});
this.add(colorBox);
timer = new Timer(250, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
km += random.nextInt(100);
odometer.setText(df.format(km));
}
});
timer.start();
}

private enum Hue {

Yellow(Color.yellow), Cyan(Color.cyan), Magenta(Color.magenta);
private final Color color;

private Hue(Color color) {
this.color = color;
}

public Color getColor() {
return color;
}
}

private static void display() {
JFrame f = new JFrame("Dispatch");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabbedPane.add("Cab #1", new Cab());
tabbedPane.add("Cab #2", new Cab());
tabbedPane.add("Cab #3", new Cab());
f.add(tabbedPane);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
display();
}
});
}
}

关于java - JTabbedPane:更改选项卡标题时更改选项卡大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9357727/

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