我正在尝试将图像添加到选项卡,使其看起来像一个图标。我想在选项卡上放置一个png图像(检查图像)
是否可以在java中执行此操作?
答案 0 :(得分:5)
JTabbedPane
允许您提供一个组件作为选项卡“渲染器”(各种)。
请查看JTabbedPane#setTabComponentAt了解更多详情,并查看this example了解详情。
更新了示例
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTabbedPaneIcon {
public static void main(String[] args) {
new TestTabbedPaneIcon();
}
public TestTabbedPaneIcon() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTabbedPane tp = new JTabbedPane();
tp.addTab("Dates", new JPanel());
tp.addTab("Deliveries", new JPanel());
tp.addTab("Exports", new JPanel());
tp.setTabComponentAt(0, getLabel("Dates", "/Icon03.png"));
tp.setTabComponentAt(1, getLabel("Deliveries", "/Icon01.png"));
tp.setTabComponentAt(2, getLabel("Exports", "/Icon02.png"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected JLabel getLabel(String title, String icon) {
JLabel label = new JLabel(title);
try {
label.setIcon(new ImageIcon(ImageIO.read(getClass().getResource(icon))));
} catch (IOException ex) {
ex.printStackTrace();
}
return label;
}
}
答案 1 :(得分:3)
JTabbedPane有api为标签设置图标,无论是在添加标签内容时还是稍后:
// when adding
tabbedPane.addTab(String, Icon, Component);
// after having added
tabbedPane.setIconAt(int, Icon);