图形标题栏渲染(Graphics rendering in title bar)

2019-06-21 01:59发布

图形渲染保持在标题栏中。 我用封装在一个JLabel缓冲图像,并使用所得到的图形对象绘制矩形在我的代码。 这是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);

Answer 1:

问题是,你没有考虑到框架的边框(以及可能的菜单栏也一样)设置帧的大小时...

而不是使用的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);
            }
        });
    }


}


Answer 2:

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

aJLabel.setLocation(Point p)

要么

aJLabel.setLocation(int x, int y)

如果你的图片过大,则需要以获得良好的位置(也调整其大小:

最好的祝福。



文章来源: Graphics rendering in title bar