0

基于以下示例:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class ExempleJFrame extends JFrame {

    public ExempleJFrame() {
        super("JFrame example");
        setLocation(50, 50);
        setSize(200, 200);
        getContentPane().add(new JLabel("This is a text label!", SwingConstants.CENTER));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        ExempleJFrame frame = new ExempleJFrame();
        frame.setVisible(true);
    }

}

有没有办法让我调用成员方法更明确(请参阅setLocation()setSize())?

我正在寻找一些东西this.setLocation()来明确我调用一个成员方法而不是来自外太空的东西。

4

3 回答 3

2

如果您使用的是 Eclipse,您可以设置保存操作(附加保存操作 -> 成员访问 -> 使用 'this' qualifier for method accesss'),它将自动转换setLocationthis.setlocation保存。

我个人觉得它不是特别有用,因为无前缀的方法调用只能是

  • 静态方法调用(在 Eclipse 中为斜体)
  • 一个 this 成员调用
  • 超级会员通话

由于运行时调度,最后两个很少需要区分恕我直言。

于 2012-10-26T13:25:48.823 回答
1

好的做法是支持组合而不是继承:不要扩展JFrame,而是删除JFrame yourFrame;类中的成员。然后你自然地调用 JFrame 方法:

yourFrame.someMethod();

ps:并从 EDT调用您的 GUI 方法:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            yourFrame = new JFrame("JFrame example");
            initFrame();
            yourFrame.setVisible(true);
        }
    }
}
于 2012-10-26T13:15:49.673 回答
0

正如评论中的其他人所说,您可以使用this.setwatever()。通常它被认为是一种使用的好习惯,this.membervariable但从未真正使用 this.method() 遇到过代码。但它工作得非常好。

于 2012-10-26T13:15:34.817 回答