已更新*** 如何在JTabbedPane中动态更改选项卡的图标? 这是代码。我需要从初始处理决赛改变图标 这段代码刚刚进入初始
代码:
package tabs;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
public class ChangeIconTest {
private JFrame frame;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChangeIconTest window = new ChangeIconTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ChangeIconTest() {
initialize();
addtabs();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(0, 0, 434, 262);
frame.getContentPane().add(tabbedPane);
}
private void addtabs(){
tabbedPane.insertTab("tab name", displayInitial(), addButton(), null, 0);
tabbedPane.setSelectedIndex(0);
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ChangeIconTest.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public Icon displayInitial(){
ImageIcon initialIcon = createImageIcon("first.gif");
return initialIcon;
}
public Icon displayMid(){
ImageIcon midIcon = createImageIcon("second.gif");
return midIcon;
}
public Icon displayFinal(){
ImageIcon finalIcon2 = createImageIcon("third.jpg");
return finalIcon2;
}
public Component addButton(){
JButton jb = new JButton("The Big Button to change the Icon");
jb.addActionListener(new ChangeTabListener());
return jb;
}
class ChangeTabListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tabbedPane.setIconAt(0, displayMid());
tabbedPane.revalidate();
tabbedPane.repaint();
tabbedPane.setIconAt(0, displayFinal());
tabbedPane.revalidate();
tabbedPane.repaint();
}
}
}
那么我应该添加或修改什么?谢谢!
答案 0 :(得分:0)
为什么使用Thread.sleep()?您可能导致事件调度线程处于休眠状态,这意味着GUI无法重新绘制。
如果您想在一段时间内动态更改图标,请使用Swing Timer来安排更改图标。
如果您需要更多帮助,请更新您的问题并发布展示问题的正确SSCCE。
答案 1 :(得分:0)
尝试添加此
tabs.revalidate();
tabs.repaint();
或者
tabs.getParent().revalidate();
tabs.getParent().repaint();