简体   繁体   中英

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

I am trying to make an ArrayList which handles different GUI components. 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. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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