本文介绍了将图像添加到JCheckBoxMenuItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被分配了一个作业,其中我需要使用JCheckBoxMenuItem并在右侧添加图像
I have been given an assignment in which i need to a use JCheckBoxMenuItem and add an image to it on the right side
我用过setIcon()方法.
I've used the setIcon() method.
创建了一个自定义面板,并向其中添加了图像,然后将该面板添加到复选框.
Created a custom panel and added image to it and then adding the panel to checkbox.
试图添加如下所示的面板.
Tried to add panel like below.
JCheckBoxMenuItem item = new JCheckBoxMenuItem(); item.setText("Option1"); JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JLabel label = new JLabel(new ImageIcon( "C:\\Users\\abcd\\Desktop\\facebook.jpg")); panel.add(label); item.add(panel);以上内容似乎可以正常工作,但仅右侧图像可见,并且复选框和文本丢失.
The above seemed like working but only image on the right side was visible and the checkbox and text were missing.
推荐答案这可以通过标准的复选框菜单项来完成,只需调整水平文本位置即可.
This can be done with a standard check box menu item, simply by adjusting the horizontal text position.
import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; import javax.swing.border.EmptyBorder; public class CheckBoxMenuItemIconPosition { private JComponent ui = null; private JMenuBar mb = null; CheckBoxMenuItemIconPosition() { initUI(); } public void initUI() { if (ui!=null) return; ui = new JPanel(new BorderLayout(4,4)); ui.setBorder(new EmptyBorder(40,160,40,160)); } public JComponent getUI() { return ui; } public JMenuBar getMenuBar() { if (mb != null) return mb; mb = new JMenuBar(); JMenu fileMenu = new JMenu("File"); mb.add(fileMenu); BufferedImage bi = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB); JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem( "Text", new ImageIcon(bi)); checkBoxMenuItem.setHorizontalTextPosition(SwingConstants.LEFT); fileMenu.add(checkBoxMenuItem); return mb; } public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { CheckBoxMenuItemIconPosition o = new CheckBoxMenuItemIconPosition(); JFrame f = new JFrame(o.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setLocationByPlatform(true); f.setContentPane(o.getUI()); f.setJMenuBar(o.getMenuBar()); f.pack(); f.setMinimumSize(f.getSize()); f.setVisible(true); } }; SwingUtilities.invokeLater(r); } }
更多推荐
将图像添加到JCheckBoxMenuItem
发布评论