我正在尝试创建一个处理不同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);}
}
答案 0 :(得分:1)
如果某个方法可用于在对象上调用,则在Java中静态确定。它可能不依赖于存储在对象中的数据。
如果不应该调用它,可以让方法抛出IllegalStateException
。例如:
public void VisibleSI() {
if (tipo != 0) {
throw new IllegalStateException();
}
for (JLabel i: lab) i.setVisible(true);
}
但是,更好的方法是为不同的案例定义不同的类。