我有一个带有 JMenu
的 JFrame
。当我在某些情况下添加包含图像的 JPanel
时,程序首次启动时菜单会重复。调整大小时重复的菜单消失。任何建议都非常感激。谢谢。代码如下:
public class MwE implements ActionListener {
private JFrame frame;
private String path;
public static void main(String[] args) {
new MwE();
}
public MwE(){
frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(720,590);
frame.setTitle("MWE");
frame.setJMenuBar(getMenu());
frame.setSize(new Dimension(720,590));
frame.setVisible(true);
File f=new File("");
path=f.getAbsolutePath();
String fn=path.concat("\\1077neuron.jpg");
ImgPanel ip=new ImgPanel(fn);
frame.setContentPane(ip);
frame.addWindowListener(new MyWindowListener());
frame.validate();
frame.paintComponents(frame.getGraphics());
return;
}
class ImgPanel extends JPanel{
protected BufferedImage img;
public ImgPanel(String F){
try{
img=ImageIO.read(new File(F));
}
catch (IOException e){
System.out.println(e.getMessage());
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img,0,0, null);
}
}
private JMenuBar getMenu(){
JMenuBar menuBar=new JMenuBar();
JMenu menu=new JMenu("File");
JMenuItem mi=new JMenuItem("OpenNetwork");
mi.addActionListener(this);
menu.add(mi);
mi=new JMenuItem("SaveNetwork");
menuBar.add(menu);
menu=new JMenu("Help");
mi=new JMenuItem("About");
mi.addActionListener(this);
menu.add(mi);
menuBar.add(menu);
return menuBar;
}
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand()=="About"){
JOptionPane.showMessageDialog(frame, "MWE");
}
}
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
frame.dispose();
}
}
}
问题如下: https://drive.google.com/file/d/0BxEMTvXHiBACNVZ0blZyMHBma3c/view?usp=sharing
问题不是特定于图像的,但这是我使用的图像,以防万一它可能有帮助: https://drive.google.com/file/d/0BxEMTvXHiBACUnlWOEQ5THlrVEE/view?usp=sharing
最佳答案
摆脱frame.paintComponents(frame.getGraphics());
您无法控制绘制过程,该过程由重绘管理器和底层 API 控制。如果想要重绘UI,需要通过repaint
方法向系统发出请求
看看
此外,在设置初始 UI 之前不要调用 frame.setVisible(true);
,否则可能会导致某些元素无法正确更新。如果您需要在 UI 可见后更新 UI,则需要确保调用 revalidate
和 repaint
来强制 UI 正确更新...
并且,除非您打算捕获关闭事件(出于某种原因提示用户),否则您可以将框架 defaultCloseOperation
设置为 JFrame.EXIT_ON_CLOSE
并为自己节省一些代码
并且 if(arg0.getActionCommand()=="About"){
不是 String
的比较方式,您正在比较内存引用,它们是不太可能相同。相反,您应该使用更像 if("About".equals(arg0.getActionCommand())){
关于java - JMenu 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875085/