Java如何在窗口或JFrame的边框/环绕上放置一个按钮

时间:2014-01-19 10:03:36

标签: java swing jframe

如何在框架周围的边框上放置一个按钮,如下所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

  

_“这是一个简短的例子吗?”

是的,这里......这是非常基本的。你需要做更多的事情。您会注意到我必须将MouseMotionListener添加到充当顶部框架边框的JPanel,因为当您从框架中移除装饰时,您也会删除该功能。因此MouseMotionListener使帧可再次拖动。

如果您愿意,您还必须实施调整大小。按下图像时,我已经实现了System exit()`。测试一下。您需要提供自己的图像。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class UndecoratedExample {
    static JFrame frame = new JFrame();
    static class MainPanel extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }
    }

    static class BorderPanel extends JPanel {

        JLabel stackLabel;
        int pX, pY;

        public BorderPanel() {
            ImageIcon icon = new ImageIcon(getClass().getResource(
                    "/resources/stackoverflow1.png"));
            stackLabel = new JLabel();
            stackLabel.setIcon(icon);

            setBackground(Color.black);
            setLayout(new FlowLayout(FlowLayout.RIGHT));

            add(stackLabel);

            stackLabel.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent e) {
                    System.exit(0);
                }
            });
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent me) {
                    // Get x,y and store them
                    pX = me.getX();
                    pY = me.getY();
                }
            });
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent me) {
                    frame.setLocation(frame.getLocation().x + me.getX() - pX, 
                            frame.getLocation().y + me.getY() - pY);
                }
            });
        }
    }

    static class OutsidePanel extends JPanel {

        public OutsidePanel() {
            setLayout(new BorderLayout());
            add(new MainPanel(), BorderLayout.CENTER);
            add(new BorderPanel(), BorderLayout.PAGE_START);
            setBorder(new LineBorder(Color.BLACK, 5));
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                frame.setUndecorated(true);
                frame.add(new OutsidePanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

enter image description here