将图像添加到JCheckBoxMenuItem

编程入门 行业动态 更新时间:2024-10-11 01:17:38
本文介绍了将图像添加到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

本文发布于:2023-08-06 11:28:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1311979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   JCheckBoxMenuItem

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!