2017-05-04 34 views
-2

我遇到了一些java代碼的問題。我無法弄清楚如何解決它。請注意,代碼大大簡化了。使用變量創建的Java動作監聽器

在panelQuestion中,我創建了一個帶有按鈕和兩個組合框的GUI。我添加一個動作監聽器到按鈕。

單擊此按鈕時,會創建一個帶有組合框值的字符串,稱爲objectName。

初始化GUI後,我創建了對象。

問題是我希望能夠在主類中使用objectName,以便我可以檢查它的一些屬性。例如,如果用戶要選擇Leicester和York,則會創建該字符串(leicester_york),並且該字符串將用於檢查該對象屬性。

但是這不起作用。我被告知objectName不存在。任何幫助將不勝感激,謝謝。

panelQuestion:

import java.awt.*; 
import java.awt.image.*; 
import javax.swing.*; 
import javax.swing.border.*; 
import java.awt.event.*; 

public class ThreePanelLayout { 

    private JComponent ui = null; 
    private CardLayout cardLayout = new CardLayout(); 
    String objectName; 

    ThreePanelLayout() { 
     initUI(); 
    } 

    public void initUI() { 
     if (ui!=null) return; 

     ui = new JPanel(new BorderLayout(4,4)); 
     ui.setBorder(new EmptyBorder(4,4,4,4)); 

     //create the 3 panels of the '3 panel layout'. 
     JPanel panel1 = new JPanel(new BorderLayout());//(); 
     panel1.setBackground(Color.RED); 
     panel1.setBorder(new TitledBorder("Choose Option")); 

     JPanel panel2 = new JPanel(new BorderLayout()); 
     panel2.setBackground(Color.GREEN); 
     panel2.setBorder(new TitledBorder("Choose Two Stops")); 

     JPanel panel3 = new JPanel(); 
     panel3.setBackground(Color.ORANGE); 
     panel3.setBorder(new TitledBorder("Click an Option")); 
     panel3.setLayout(cardLayout); 


     // add the buttons to 1st panel 
     JButton timeButton, priceButton, routeButton, adminButton, exitButton, inputRoute, saveRoute, retrieveRoute, backToMain; //DECLARING BUTTON 
     timeButton = new JButton("Time"); 
     priceButton = new JButton("Price"); 
     routeButton = new JButton("Route"); 
     adminButton = new JButton("Admin"); 
     exitButton = new JButton("Exit"); 
     inputRoute = new JButton("Input Route"); 
     saveRoute  = new JButton("Save Route"); 
     retrieveRoute = new JButton("Retrieve route"); 

     JPanel panelButtons = new JPanel(new GridLayout(5,1,5,5)); 
     panelButtons.add(timeButton); 
     panelButtons.add(priceButton); 
     panelButtons.add(routeButton); 
     panelButtons.add(adminButton); 
     panelButtons.add(exitButton);   
     panel1.add(panelButtons, BorderLayout.LINE_START); 

     JPanel panelAdmin = new JPanel(new GridLayout(5,1)); 
     JPanel panelAdminSize = new JPanel(); 
     panelAdminSize.add(inputRoute); 
     panelAdminSize.add(saveRoute); 
     panelAdminSize.add(retrieveRoute); 
     panelAdmin.add(panelAdminSize); 


     // adding the combos to the top of 2nd panel 

     String stops[] = {"Leicester","Loughborough","Nottingham","Derby","York"}; 

     JComboBox departingStop = new JComboBox(); 
     JComboBox finalStop = new JComboBox(); 
     for(int i = 0; i < stops.length; i++) { 
      departingStop.addItem(stops[i]); 
      finalStop.addItem(stops[i]); 
     } 

     JPanel panelCombo = new JPanel(new FlowLayout()); 
     panelCombo.add(departingStop); 
     panelCombo.add(finalStop); 
     panel2.add(panelCombo, BorderLayout.PAGE_START); 

     // adding options to panel 3   
     // panel for when time is clicked 
     JPanel panelTime = new JPanel(); //creating panel for time option 
     JLabel timeLabel = new JLabel("The time between x and y is"); 
     panelTime.add(timeLabel); 

     //panel for when price is clicked 
     JPanel panelPrice = new JPanel(); 
     JButton confirmPrice = new JButton("Confirm"); 
     JRadioButton singleRadio = new JRadioButton("Single"); 
     JRadioButton returnRadio = new JRadioButton("Return"); 
     ButtonGroup group = new ButtonGroup(); 
     group.add(singleRadio); 
     group.add(returnRadio); 
     panelPrice.add(singleRadio); 
     panelPrice.add(returnRadio); 
     panelPrice.add(confirmPrice); 

     // used for route button 
     JPanel panelRoute = new JPanel(); 
     JLabel routeLabel = new JLabel ("Stop between X and Y"); 
     panelRoute.add(routeLabel); 
     JButton sortButton = new JButton("Sort"); 
     panelRoute.add(sortButton); 

     panel3.add(panelTime,"1"); 
     panel3.add(panelPrice,"2"); 
     panel3.add(panelRoute,"3"); 
     panel3.add(panelAdmin,"4"); 

     timeButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       cardLayout.show(panel3, "1"); 

       Object comboValue = departingStop.getSelectedItem(); 
       Object combo2Value = finalStop.getSelectedItem(); 
       objectName = comboValue + "_" + combo2Value; 
       objectName = objectName.toLowerCase(); 
      } 
     }); 

     priceButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       cardLayout.show(panel3, "2"); 
      } 
     }); 

     routeButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       cardLayout.show(panel3, "3"); 
      } 
     }); 

     adminButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       cardLayout.show(panel3, "4"); 
      } 
     }); 

     exitButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       System.exit(0); 
      } 
     }); 

     // assembling panels 
     panel2.add(panel3); 
     panel1.add(panel2, BorderLayout.CENTER); 
     ui.add(panel1); 
    } 

    public JComponent getUI() { 
     return ui; 
    } 

    public static void main(String[] args) {   
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception useDefault) { 
       } 
       ThreePanelLayout o = new ThreePanelLayout(); 
       JFrame f = new JFrame(o.getClass().getSimpleName()); 
       f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       f.setLocationByPlatform(true); 
       f.setContentPane(o.getUI()); 
       f.setSize(600,400); 
       f.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 

     Journey leicester_loughborough = new Journey(); 
     leicester_loughborough.setSingleCost(2.5); 

     Journey leicester_nottingham = new Journey(); 
     leicester_nottingham.setSingleCost(3.5); 

     Journey leicester_derby = new Journey(); 
     leicester_derby.setSingleCost(3.7); 

     Journey leicester_york = new Journey(); 
     leicester_york.setSingleCost(23.5); 

     objectName.getSingleCost(); //error comes up here 

    } 


} 

之旅:

public class Journey 
{ 

    public double singleCost; 

    public void setSingleCost(double cost) { 
     singleCost = cost; 
    } 

    public double getSingleCost() { 
     return singleCost; 
    } 
} 

我不認爲這個問題是重複的。當使用解決方案objectName = this.objectName時,會出現同樣的問題。

+0

你不能這樣做。如果您想在處理程序之外使用它,則需要在處理程序之外創建變量。查找變量範圍。 – Carcigenicate

+0

爲什麼你在那裏添加[answer](http://stackoverflow.com/a/43784461/4391450)這一行?它處於不同的上下文中(靜態主要上下文)。你需要從'ThreePanelLayout'實例訪問它,所以'Runnable#run'或者這個類的一個方法。 – AxelH

+0

@AxelH我不知道我明白你的意思。如果我使用initUI()將它放在ThreeLayoutPanel()中,那麼在調用它的時候會告訴我這個變量不存在。 –

回答

0

您需要聲明:String objectName作爲面板問題類的成員變量!


旁註:

你需要閱讀對象的工作方式以及他們有什麼方法,會員和他們在幹什麼....爲我評論上述objectName.getSingleCost()是沒有意義的,並且沒有編制,其原因:對象名是一個字符串對象和字符串沒有叫getSingleCost

方法,因爲你做的事:

String objectName; 
Object comboValue = departingStop.getSelectedItem(); 
Object combo2Value = finalStop.getSelectedItem(); 
objectName = comboValue + "_" + combo2Value; 

dosnt意味着,現在從OBJECTNAME字符串突變成一個組合框...

同樣是無效的:

Car tata = new Car(); 
Robot kuka = new Robot(); 
String foo = tata.getName() + kuka.getName(); 

什麼現在是富?變壓器? NO,仍然是一個字符串...

你可以找到成千上萬的教程...去搜索,閱讀,學習和前一後走1步....

+0

更好地稱它爲一個成員變量,但答案是正確的,否則 – XtremeBaumer

+0

感謝您的答案。但是更多的問題。當在面板問題中聲明我的變量並在我的main中調用它時,我被告知非靜態變量可能不會在靜態上下文中調用。任何想法如何我可以補救這個? –

+0

@JonGoe,哼,你能不能更新代碼... –