简体   繁体   English

如何避免激活类中的所有方法?

[英]How can I avoid activating all the methods on a class?

I am trying to make an ArrayList which handles different GUI components. 我正在尝试制作一个处理不同GUI组件的ArrayList。 This class should have methods and some of them wouldn't apply to all of the components so i tried to use a conditional buy it seems impossible to solve it that way. 此类应具有方法,其中某些方法不适用于所有组件,因此我尝试使用条件购买,似乎无法以这种方式解决。

Could you point me in the right direction to solve this problem? 您能指出我正确的方向来解决这个问题吗?

code: 码:

    public class ArrGUI
    {
    private ArrayList <JLabel>  lab;
    private ArrayList <JButton> but;
        //...
    final int t;

    public ArrGUI(JLabel x){
    lab = new ArrayList <JLabel> ();
    t=0;}
    //... more constructors with different paramenters different t values
    //common methods of array list

    if(tipo==0)
    {
    public void VisibleSI() {
    for (JLabel i: lab) i.setVisible(true);}

    public void VisibleNO() {
    for (JLabel i: lab) i.setVisible(false);}
    //...

edit: i solved my problem this way. 编辑:我这样解决了我的问题。 to access any other method i would use the obtener method. 访问任何其他方法,我将使用obtener方法。 thanks for the help. 谢谢您的帮助。

    public class ArregloGUI
    {
private ArrayList <Component> lab;

public ArregloGUI(Component x){
lab = new ArrayList <Component> ();}

//Operaciones
public void adicionar(Component x) {
    lab.add(x);}

public int tamaño() {
    return lab.size();}

public Component obtener(int i) {
    return lab.get(i);}

public void eliminarAlFinal() {
    if (tamaño() > 0)   lab.remove(tamaño()-1);}

public void reinicializarArreglo() {
    if (tamaño() > 0)   lab.clear();}

public void ubicar(int i, int x, int y, int xx, int yy){
    obtener(i).setBounds(x,y,xx,yy);}
    }

If a certain method is available to be called on an object is determined statically in Java. 是否可以在对象上调用某个方法是用Java静态确定的。 It may not depend on data stored in the object. 它可能不依赖于存储在对象中的数据。

You could let the method throw an IllegalStateException if it is called when it should not. 如果不应该调用该方法,则可以让该方法抛出IllegalStateException For example: 例如:

public void VisibleSI() {
    if (tipo != 0) {
        throw new IllegalStateException();
    }
    for (JLabel i: lab) i.setVisible(true);
}

However, a better approach is to define different classes for the different cases. 但是,更好的方法是为不同的情况定义不同的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM