更改窗口大小后如何更改对象的位置?

时间:2019-05-31 11:14:54

标签: java object position

与标题相同。我希望在板上移动的物体按比例改变位置,以改变窗口的大小。怎么做?

2 个答案:

答案 0 :(得分:1)

Let's assume that you are working with a JFrame.

You can get the dimensions of the JFrame as follows:

Dimension size = frame.getBounds().getSize()
double height = size.getHeight();
double width = size.getWidth();

Then you can make your object move by a percentage of those values.

Whenever the window's size changes, an event is triggered. You can update the dimensions whenever that event is triggered with a ComponentListener.

class ResizeListener implements ComponentListener {

    public void componentHidden(ComponentEvent e) {}
    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}

    public void componentResized(ComponentEvent e) {
        Dimension newSize = e.getComponent().getBounds().getSize();          
    }   
}

Do not forget to add the ComponentListener to your JFrame.

Sources: How to check current window size in java swing?

答案 1 :(得分:0)

You can use the componentResized method to recalculate the pieces' positions based on the actual frame size

public static void main(String[] args) {
    JPanel panel = new JPanel() {
      @Override
      public Dimension getPreferredSize() {
        return new Dimension(200, 200);
      }
    };
    panel.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentResized(ComponentEvent e) {
        System.out.println("Resized to " + e.getComponent().getSize());
      }
      @Override
      public void componentMoved(ComponentEvent e) {
        System.out.println("Moved to " + e.getComponent().getLocation());
      }
    });
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("test", panel);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(tabbedPane);
    frame.pack();

    frame.setVisible(true);
}