![](/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.