2012-07-10 4 views
1

프로젝트 용 프로그램 작성. 다른 패널에서 사용하는 CardLayout에 대한 현재 카드를 결정하기 위해 JList에서 현재 선택을 가져 오려면 ListSelectionListener를 사용해야합니다. 적어도 Listener에서 현재 카드를 변경하기 위해 CardLayout 클래스의 show 메서드를 사용하지 않으면 리스너에 의해 만들어진 선택 항목의 이름을 가진 String을 가질 수 있어야합니다. 이를 수행하는 가장 간단한 방법은 궁극적으로 현재 카드가 변경되게하는 것입니다. 어떤 도움을 주셔서 감사합니다!내부 클래스 및 로컬 변수 문제

출처 :

import javax.swing.*; 
import java.util.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.event.*; 

public class ClientApp extends JFrame 
{ 
    public static void main(String[] args) 
    { 
     new ClientApp(); 
    } 


    public ClientApp() 
    { 
     this.setSize(750,380); 
     this.setTitle("Honeydukes Muggle Ordering System"); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel infoPanel = new JPanel(new CardLayout()); 
     JPanel invntryPanel = new JPanel(); 


     //Creating the array for the invntryPanel Jlist 

     String[] candy = {"Acid Pops", "Bat's Blood Soup", 
          "Bertie Bott's Every Flavour Beans", 
          "Blood-flavoured Lollipops", 
          "Cauldron Cakes", "Charm Choc", 
          "Chocoballs", "Chocolate Cauldrons", 
          "Chocolate Frogs", "Chocolate Skeletons", 
          "Chocolate Wands", "Choco-Loco", "Cockroach Clusters", 
          "Nougat", "Crystallised Pineapple", 
          "Drooble's Best Blowing Gum", "Exploding Bonbons", 
          "Toffees", "Fizzing Whizzbees", 
          "Fudge Flies", "Ice Mice", 
          "Jelly Slugs", "Liquourice Wands", 
          "Pepper Imps", "Peppermint Toads", 
          "Pink Coconut Ice", "Pixie Puffs", 
          "Pumpkin Fizz", "Salt Water Taffy", 
          "Shock-o-Choc", "Skeletal Sweets", 
          "Splindle's Lick'O'Rish Spiders", 
          "Sugar Quills", "Sugared Butterfly Wings", 
          "Toothflossing Stringmints", "Tooth-Splintering Strongmints", 
          "Treacle Fudge", "Chocolates", "Wizochoc"}; 
     JList candyList = new JList(candy); 
     candyList.setVisibleRowCount(18); 
     candyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

     ListSelectionListener sl = new ListSelectionListener() { 
      public void valueChanged(ListSelectionEvent e) { 
      if (e.getValueIsAdjusting() == false) { 
       CardLayout.show(infoPanel, (String)candyList.getSelectedValue()); 
      } 
      } 
     }; 

     candyList.addListSelectionListener(sl); 

     //Creating a scrollpane for the JList 
     JScrollPane scroll = new JScrollPane(candyList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     invntryPanel.add(scroll); 


     //Creating the cards 
     JPanel startCard = new JPanel(new BorderLayout()); 
     JPanel acidPopsCard = new JPanel(); 
     JPanel batsBloodSoupCard = new JPanel(); 
     JPanel bertieBottsCard = new JPanel(); 
     JPanel bloodPopsCard = new JPanel(); 
     JPanel cauldronCakesCard = new JPanel(); 
     JPanel charmChocCard = new JPanel(); 
     JPanel chocoballsCard = new JPanel(); 
     JPanel chocCauldronsCard = new JPanel(); 
     JPanel chocFrogsCard = new JPanel(); 
     JPanel chocSkeleCard = new JPanel(); 
     JPanel chocWands = new JPanel(); 
     JPanel chocolocoCard = new JPanel(); 
     JPanel roachClustersCard = new JPanel(); 
     JPanel nougatCard = new JPanel(); 
     JPanel crystalPineappleCard = new JPanel(); 
     JPanel droobleGumCard = new JPanel(); 
     JPanel explodeBonbonsCard = new JPanel(); 
     JPanel toffeesCard = new JPanel(); 
     JPanel fizzWhizCard = new JPanel(); 
     JPanel fudgeFliesCard = new JPanel(); 
     JPanel iceMiceCard = new JPanel(); 
     JPanel jellySlugsCard = new JPanel(); 
     JPanel liquorWandsCard = new JPanel(); 
     JPanel pepImpsCard = new JPanel(); 
     JPanel pepToadsCard = new JPanel(); 
     JPanel pinkCocoIceCard = new JPanel(); 
     JPanel pixiePuffsCard = new JPanel(); 
     JPanel pumpkFizzCard = new JPanel(); 
     JPanel saltTaffeyCard = new JPanel(); 
     JPanel shockChocCard = new JPanel(); 
     JPanel skeleSweetsCard = new JPanel(); 
     JPanel spindleSpidersCard = new JPanel(); 
     JPanel sugarQuillsCard = new JPanel(); 
     JPanel sugarWingsCard = new JPanel(); 
     JPanel flossMintsCard = new JPanel(); 
     JPanel splintMintsCard = new JPanel(); 
     JPanel treacleFudgeCard = new JPanel(); 
     JPanel chocolatesCard = new JPanel(); 
     JPanel wizochocCard = new JPanel(); 

     //Adding the cards to the infoPanel 
     infoPanel.add(startCard, "Start"); 
     infoPanel.add(acidPopsCard, "Acid Pops"); 
     infoPanel.add(batsBloodSoupCard, "Bat's Blood Soup"); 
     infoPanel.add(bertieBottsCard, "Bertie Bott's Every Flavour Beans"); 
     infoPanel.add(bloodPopsCard, "Blood-flavoured Lollipops"); 
     infoPanel.add(cauldronCakesCard, "Cauldron Cakes"); 
     infoPanel.add(charmChocCard, "Charm Choc"); 
     infoPanel.add(chocoballsCard, "Chocoballs"); 
     infoPanel.add(chocCauldronsCard, "Chocolate Cauldrons"); 
     infoPanel.add(chocFrogsCard, "Chocolate Frogs"); 
     infoPanel.add(chocSkeleCard, "Chocolate Skeletons"); 
     infoPanel.add(chocWands, "Chocolate Wands"); 
     infoPanel.add(chocolocoCard, "Choco-Loco"); 
     infoPanel.add(roachClustersCard, "Cockroach Clusters"); 
     infoPanel.add(nougatCard, "Nougat"); 
     infoPanel.add(crystalPineappleCard, "Crystallised Pineapple"); 
     infoPanel.add(droobleGumCard, "Drooble's Best Blowing Gum"); 
     infoPanel.add(explodeBonbonsCard, "Exploding Bonbons"); 
     infoPanel.add(toffeesCard, "Toffees"); 
     infoPanel.add(fizzWhizCard, "Fizzing Whizzbees"); 
     infoPanel.add(fudgeFliesCard, "Fudge Flies"); 
     infoPanel.add(iceMiceCard, "Ice Mice"); 
     infoPanel.add(jellySlugsCard, "Jelly Slugs"); 
     infoPanel.add(liquorWandsCard, "Liquourice Wands"); 
     infoPanel.add(pepImpsCard, "Pepper Imps"); 
     infoPanel.add(pepToadsCard, "Peppermint Toads"); 
     infoPanel.add(pinkCocoIceCard, "Pink Coconut Ice"); 
     infoPanel.add(pixiePuffsCard, "Pixie Puffs"); 
     infoPanel.add(pumpkFizzCard, "Pumpkin Fizz"); 
     infoPanel.add(saltTaffeyCard, "Salt Water Taffy"); 
     infoPanel.add(shockChocCard, "Shock-o-Choc"); 
     infoPanel.add(skeleSweetsCard, "Skeletal Sweets"); 
     infoPanel.add(spindleSpidersCard, "Splindle's Lick'O'Rish Spiders"); 
     infoPanel.add(sugarQuillsCard, "Sugar Quills"); 
     infoPanel.add(sugarWingsCard, "Sugared Butterfly Wings"); 
     infoPanel.add(flossMintsCard, "Toothflossing Stringmints"); 
     infoPanel.add(splintMintsCard, "Tooth-Splintering Strongmints"); 
     infoPanel.add(treacleFudgeCard, "Treacle Fudge"); 
     infoPanel.add(chocolatesCard, "Chocolates"); 
     infoPanel.add(wizochocCard, "Wizochoc"); 

     //startCard building 
     JLabel startLbl = new JLabel("<html><center>Welcome to the Honeydukes Muggle Ordering System!<br />Please select from one of our products to the left to begin!</center></html>"); 
     startCard.add(startLbl, BorderLayout.CENTER); 

     this.add(invntryPanel, BorderLayout.LINE_START); 
     this.add(infoPanel, BorderLayout.CENTER); 
     this.setVisible(true); 
    } 
} 

오류 :

ClientApp.java:54: error: local variable infoPanel is accessed from within inner 
class; needs to be declared final 
       CardLayout.show(infoPanel, (String)candyList.getSelectedValue()) 
; 
           ^
ClientApp.java:54: error: local variable candyList is accessed from within inner 
class; needs to be declared final 
       CardLayout.show(infoPanel, (String)candyList.getSelectedValue()) 
; 
               ^
ClientApp.java:54: error: non-static method show(Container,String) cannot be ref 
erenced from a static context 
       CardLayout.show(infoPanel, (String)candyList.getSelectedValue()) 
; 
         ^
Note: ClientApp.java uses unchecked or unsafe operations. 
Note: Recompile with -Xlint:unchecked for details. 
3 errors 
+3

infoPanel을 final로 선언 한 다음 컴파일을 시도하십시오. – Patton

+1

또한 'candyList'를 final로 선언해야합니다. 그리고 새로운 CardLayout(). show (infoPanel, (String) candyList.getSelectedValue());'인스턴스를 만들어야합니다. – matcauthon

+0

최종본을 만들려고 할 때마다 식별자가 필요하다고합니다. 왜 어떤 아이디어? 나는 그것이 단지 무엇이든 될 수 있다는 것을 안다. – Sam

답변

3

나는 몇 가지 방법을 생각할 수있다. 먼저 candyList에 대한 참조를 만듭니다.

final JList candyList = new JList(candy); 

이렇게하면 내부 클래스가 목록을 볼 수 있습니다. 개인적으로, 나는이 접근법을 좋아하지 않는다. 그러나 그것은 나만의 것이다. 당신이 시도 할 수

다른 것은 이벤트 객체

ListSelectionListener sl = new ListSelectionListener() { 
    public void valueChanged(ListSelectionEvent e) { 
     JList candyList = (JList)e.getSource(); 
     if (e.getValueIsAdjusting() == false) { 
      CardLayout.show(infoPanel, (String)candyList.getSelectedValue()); 
     } 
     } 
    }; 

를 통해 목록을 참조하거나 매개 변수로에 목록 과거를 가질 수있는 새로운 내부 클래스를 구성하는 것입니다

public class MyInnerListener implements ListSelectionListener { 

    private JList list; 

    public MyInnerListener(JList list) { 

     this.list = list; 

    } 
    public void valueChanged(ListSelectionEvent e) { 
     if (e.getValueIsAdjusting() == false) { 
      CardLayout.show(infoPanel, (String)list.getSelectedValue()); 
     } 
    } 

} 

그냥)

+0

아주 좋은 아이디어입니다. 최소한 JList를 다룹니다. "속임수"에 반하는 유혹이 있으며 현재 카드를 전환하기 위해 JList 아래에 버튼을 추가하기 만하면됩니다. 최소한 내부 수업 등을 다루어야하는 문제를 해결할 것입니다. – Sam