graphics在标题栏中呈现

graphics在标题栏中不断渲染。 我使用封装在jlabel中的缓冲图像,并使用生成的graphics对象在我的代码中绘制矩形。 这是jframe类构造函数的重要部分:

super(); BufferedImage image=new BufferedImage(680,581,BufferedImage.TYPE_INT_ARGB); m_graphicsObject =image.getGraphics(); JLabel label=new JLabel(new ImageIcon(image)); // buttons, mouse events and other controls use listeners to handle actions // these listener are classes btn1 = new JButton("Go!"); //btn1.setPreferredSize(new Dimension(100, 30)); btn1.addActionListener(new button_go_Click()); //listener 1 btn2 = new JButton("Clear!"); //btn2.setPreferredSize(new Dimension(100, 30)); btn2.addActionListener(new button_clear_Click()); //listener 2 //always add created buttons/controls to form JPanel panel=new JPanel(new GridLayout(20,2)); panel.add(btn1); panel.add(btn2); Container pane = this.getContentPane(); pane.add(label); pane.add(panel, BorderLayout.EAST); this.setSize(680,581); this.setVisible(true); 

问题是你没有考虑框架的边框(也可能是菜单栏),当设置框架的大小…

而不是使用this.setSize(680,581)这将导致图像在框架边界内(和超出到不可见的空间)渲染,你应该简单地调用JFrame#pack ,让框架决定如何最好地调整自己的尺寸基于它的内容的首选大小)

在这里输入图像描述在这里输入图像描述

左,绝对大小,正确的首选大小

 public class SimpleImageLabel { public static void main(String[] args) { new SimpleImageLabel(); } public SimpleImageLabel() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JLabel imageLabel = new JLabel(); try { imageLabel.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/image")))); } catch (Exception e) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(imageLabel); frame.pack(); // <-- The better way // frame.setSize(imageLabel.getPreferredSize()); // <-- The not better way frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } 

正如我之前提到的,你应该使用你的JLabel的位置

 aJLabel.setLocation(Point p) 

要么

 aJLabel.setLocation(int x, int y) 

如果你的图片太大,你也需要调整它的大小以获得一个好的位置(:

最好的祝福。