java jmenuitem重新渲染_java - 摇摆-删除JMenu中除最后一个JMenuItem之外的所有内容 - 堆栈内存溢出...

您是否考虑过仅删除所有菜单项并重新添加最后一个菜单项,例如...

int count = menu.getMenuComponentCount();

Component last = menu.getMenuComponent(count - 1);

menu.removeAll();

menu.add(last);

您应该提防JMenu可能包含其他组件,因此使用remove(int)可能实际上并未删除菜单项,而是另一个组件...

aHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9hSzkwby5naWY=

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Component;

import java.awt.EventQueue;

import java.awt.GridBagLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.SwingUtilities;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

import javax.swing.border.LineBorder;

import org.jdesktop.jxlayer.JXLayer;

import org.pbjar.jxlayer.demo.TransformUtils;

import org.pbjar.jxlayer.plaf.ext.transform.DefaultTransformModel;

public class MenuExample {

public static void main(String[] args) {

new MenuExample();

}

public MenuExample() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {

}

final JMenu menu = new JMenu("Test");

JButton build = new JButton("Build");

build.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

makeItSo(menu);

}

});

JButton remove = new JButton("Remove");

remove.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

int count = menu.getMenuComponentCount();

Component last = menu.getMenuComponent(count - 1);

menu.removeAll();

menu.add(last);

}

});

makeItSo(menu);

JPanel buttons = new JPanel();

buttons.add(build);

buttons.add(remove);

JMenuBar mb = new JMenuBar();

mb.add(menu);

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setJMenuBar(mb);

frame.add(buttons, BorderLayout.SOUTH);

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

});

}

protected void makeItSo(JMenu menu) {

for (int index = 0; index < (Math.random() * 20); index++) {

menu.add("MenuItem " + index);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值