引用另一个类的组件

引用另一个类的组件

本文介绍了Java / Swing:引用另一个类的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swing-GUI(使用Netbeans GUI-Builder构建),有一个标签,我使用箭头键移动。
按空格键调用另一个类。如何从此课程中访问标签,例如获得该职位?

I have a Swing-GUI (built with Netbeans GUI-Builder), there is an label which I move around using the arrow-keys.Pressing the space-key another class is called. How can I access the label from this class and e.g. get the position?

提前感谢您的帮助!
示例 - 第二类的代码:

Thanks in advance for help!Example-Code of the second class:

    public class Xy extends Thread {
      private Window s; // this is the jFrame-form
      public Xy(Window s) {
        this.s = s;
        s.setBackground(Color.yellow); // works
}


public void run() {
          // here i want to use the position of a label which is located on the form s
}


推荐答案

最好的选择是不要暴露JLabel,如果你不是绝对需要这样做的话。如果您希望其他类更改标签的位置,则为包含标签的类提供允许外部类执行此操作的方法。如果其他类需要查询标签的位置,则给出包含类的public getter方法,以便外部代码可以获取位置数据(而不是标签本身)。这样,如果您以后决定不想使用JLabel,而是希望完全显示不同的组件,则不会破坏其他类中的代码。

The best option is not to expose the JLabel if you don't absolutely need to do it. If you want the other class to change the label's position, then give the class that holds the label a method that allows outside classes to do this. If other classes need to query the label's position, then give the containing class public getter methods so that outside code can obtain the position data (not the label itself). This way, if you later decide that you don't want to use a JLabel but rather would like to display a different component altogether, you won't break code in other classes.

或者更好的是,将GUI基于MVC模型,然后更改逻辑标签在模型中的位置。视图可以通过观察者模式监听模型中的更改,然后视图本身可以更改标签的位置。

Or better still, base your GUI on a MVC model, and then change the logical label's position in the model. The view can listen for changes in the model via the observer pattern and then the view itself can change the label's position.

他们所有这一切的关键是使用随时随地。

They key to all of this is use loose coupling whenever and wherever possible.

这篇关于Java / Swing:引用另一个类的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:19