![](/img/trans.png)
[英]How can I avoid having to rely on an object of another class to make the methods in a different class work?
[英]How can I avoid activating all the methods on a class?
我正在尝试制作一个处理不同GUI组件的ArrayList。 此类应具有方法,其中某些方法不适用于所有组件,因此我尝试使用条件购买,似乎无法以这种方式解决。
您能指出我正确的方向来解决这个问题吗?
码:
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);}
//...
编辑:我这样解决了我的问题。 访问任何其他方法,我将使用obtener方法。 谢谢您的帮助。
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);}
}
是否可以在对象上调用某个方法是用Java静态确定的。 它可能不依赖于存储在对象中的数据。
如果不应该调用该方法,则可以让该方法抛出IllegalStateException
。 例如:
public void VisibleSI() {
if (tipo != 0) {
throw new IllegalStateException();
}
for (JLabel i: lab) i.setVisible(true);
}
但是,更好的方法是为不同的情况定义不同的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.