有效更新 JTabbedPane 外观
在 Swing 应用程序中,JTabbedPane 允许创建选项卡式窗格。有时,需要动态更改应用程序的外观 (L&F)。但是,这样做可能并不总是按预期更新 JTabbedPane。
问题:在 JTabbedPane 中添加新选项卡后,更改 L&F 不会反映在新选项卡中。
解决方案:要解决此问题,请考虑以下方法方法:
import javax.swing.*; import javax.swing.UIManager.LookAndFeelInfo; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JTabbedPaneLookAndFeelUpdate { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Tab 1", new JPanel()); frame.add(createToolbar(tabbedPane), BorderLayout.NORTH); frame.add(tabbedPane, BorderLayout.CENTER); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } private static JToolBar createToolbar(JTabbedPane tabbedPane) { List<LookAndFeelInfo> availableLooks = new ArrayList<>(Arrays.asList(UIManager.getInstalledLookAndFeels())); JComboBox<LookAndFeelInfo> lookAndFeelComboBox = new JComboBox<>(availableLooks.toArray(new LookAndFeelInfo[0])); lookAndFeelComboBox.addActionListener(e -> { try { LookAndFeelInfo selectedLookAndFeel = (LookAndFeelInfo) e.getSource(); UIManager.setLookAndFeel(selectedLookAndFeel.getClassName()); SwingUtilities.updateComponentTreeUI(tabbedPane); } catch (Exception ex) { ex.printStackTrace(); } }); JToolBar toolbar = new JToolBar(); toolbar.add(new JLabel("Look and Feel:")); toolbar.add(lookAndFeelComboBox); return toolbar; } }
解释:
此解决方案允许动态 L&F 更改,确保JTabbedPane 以及新添加的选项卡反映了所选的 L&F。
以上是在 Swing 中添加新选项卡后如何动态更新 JTabbedPane 的外观?的详细内容。更多信息请关注PHP中文网其他相关文章!