【问题标题】:how to compare Frame and button width and length?如何比较框架和按钮的宽度和长度?
【发布时间】:2014-01-26 07:18:57
【问题描述】:

在摇摆环境中,我绘制按钮并设置动作以在我的框架上移动。
当我的按钮到达框架或按钮的角落并且框架的长度和宽度相等时;执行其他操作或类似的操作。
我的问题是我找不到任何组件来比较按钮和框架的位置或长度和宽度。

    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            x= x + 10 ;
            y=y + 10 ;
            jButtonMove.setLocation(x, y);
    }
    };
    Timer t = new Timer(500 , al);
    t.start();

【问题讨论】:

  • if (button.getWidth() + button.locationX()
  • @shved90 谢谢回复。

标签: java swing frame


【解决方案1】:

请查看Component.getX()Component.getY() 以获得X 和Y 坐标Component.getWidth()Component.getHeight(),用于获取所述组件的Width和Height

这里是进一步帮助的示例代码:

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

public class LocationExample {

    private JButton button;
    private JTextField tField;
    private JPanel contentPane;

    private void displayGUI() {
        JFrame frame = new JFrame("Location Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new JPanel();
        button = new JButton("Useless");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                tField.setText("X : " + tField.getX() + 
                                " Y : " + tField.getY() +
                                " Width : " + tField.getWidth() +
                                " Height : " + tField.getHeight());
                System.out.println("X : " + button.getX() + 
                                    " Y : " + button.getY() + 
                                    " Width : " + button.getWidth() + 
                                    " Height : " + button.getHeight());
            }
        });
        tField = new JTextField("Useless", 10);

        contentPane.add(button);
        contentPane.add(tField);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new LocationExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2017-03-27
    • 2015-05-09
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多