필자는 텍스트 형식으로 잘 작동하는 프로그램 용 GUI를 만들기 위해 혼란을 겪었습니다.다른 클래스에서 인스턴스화 된 객체의 메서드 호출
기본적으로 프로그램은 인벤토리를 추적합니다. 제품 이름, 번호, 비용, 수량 등 처음에는 모든 게터와 세터를 다루는 클래스 '항목'만있었습니다. 그런 다음 스캐너 등을 사용하여 각 요소를 체계적으로 입력 할 수있는 텍스트 기반 메뉴를 표시합니다. 나는 내가 조작 할 수있는 모든 Item 객체를 저장하는 Item의 배열을 인스턴스화 할 수 있기 때문에 모든 것이 잘 작동하는 것을 이해합니다. 그러나 모든 것은 main()에서 발생했습니다.
이제 main()에서 처리하고 처리 한 항목의 대부분을 처리하는 Inventory 클래스를 추가로 만들었습니다. 주로 내 ActionListeners 내에서 내 프로그램 전체에서 사용할 수있는 하나의 "Inventory"객체를 만들고 싶습니다. I.E. inventory.displayText (position); 불행히도 내 GUI는 main()과 별도의 클래스이기 때문에 Inventory 클래스를 인스턴스화 할 때 로컬 변수 인 "inventory"가 없으므로 오류가 발생합니다.
이것은 불합리하게 단순해야하는 것처럼 보이지만 내 뇌는 단지 주위를 감싸는 것처럼 보이지 않습니다. 여기
는 생각 :public class Items{
all item variables
setters and getters()
}
public class Inventory{
Items[] arrayOfItems = new Items[10]
displayItem(int placement){
...code to display items
}
}
public class GUI extends JFrame{
public GUI(){
...general gui layout...
forwardButton = new JButton("Forward");
}
private class eventHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
int placement = 1;
if (event.getSource()==forwardButton){
if (placement < 10){
placement++;
inv.displayItem(placement); //this is where the problem is and where I
} //have lost myself. inv doesnt exist here.
//so i cant call upon the object from here.
public class Company{
public static void main(String args[]){
//Open GUI
GUI mainGUI = new GUI();
mainGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainGUI.setSize(1000,1000);
mainGUI.setVisible(true);
//initialize inventory object
Inventory inv = new Inventory();
}
}
내가 슈퍼 근본적인 그 무언가 거의 100 % 확신하지만, 난 그냥 아니에요 그걸로. 너희들이 나를 도울 수 있다면 크게 감사 하겠어!
오류가 발생했습니다. 어떤 오류가 있습니까? 내 GUI 클래스에서 – Sugar
나는 "inv"isnt 인식 된 로컬 변수 때문에 "inv.displayItem (placement)"가 작동하지 않는다는 오류가 발생합니다. – user3721017