2016-02-13 195 views
0

時,什麼也沒有發生我有一個應用程序,當你運行它時,你需要一個面板,以添加3個值,然後你需要按OK按鈕才能繼續。當我點擊按鈕java

我把一個Click()方法,但是當我按下確定什麼都沒有發生。

另外要提到當我正在工作,但是當我將它作爲可執行jar導出時不是。

JFrame frame = new JFrame(); 
JLabel mlabel = new JLabel("Please provide xxxx",JLabel.CENTER); 
JLabel uLabel = new JLabel("User ID:",JLabel.LEFT); 
JPanel buttonField = new JPanel(new GridLayout (1,3)); 
JPanel userArea = new JPanel(new GridLayout (0,3)); 


frame.setLayout(new GridLayout (0,1)); 
buttonField.setLayout(new FlowLayout()); 
JButton confirm =new JButton("OK"); 
confirm.addMouseListener((MouseListener) new mouseClick()); 
buttonField.add(confirm); 

App.insertText = new JTextField(20); 
frame.add(mlabel); 
userArea.add(uLabel); 
userArea.add(insertText); 
frame.add(buttonField); 
frame.setSize(300,600); 
App.credGet = false; 
frame.setVisible(true); 

和點擊:

public void mouseClicked(MouseEvent e) { 
    App.un = App.insertText.getText(); 
    App.project = ((JTextComponent) App.insertProject).getText(); 
    //App.pw = char[] App.insertPass.getPassword(); 
    char[] input = App.insertPass.getPassword(); 
    App.pw = ""; 
    for (int i1 = 0; i1 < input.length; i1++){ 
     App.pw = App.pw + input[i1]; 
    } 
} 

public void mouseEntered(MouseEvent arg0) { 
    // TODO Auto-generated method stub 

} 

public void mouseExited(MouseEvent arg0) { 
    // TODO Auto-generated method stub 

} 

public void mousePressed(MouseEvent arg0) { 
    // TODO Auto-generated method stub 
+4

1.爲正確的需要使用正確的偵聽器,並且在這裏從不以這種方式使用MouseListener,而在偵聽JButton按下時使用ActionListener。 2.你有不尋常的現場參考建議可能過度使用靜態字段 - 但我根據你迄今發佈的內容無法判斷。 3.爲獲得更好的幫助,請創建併發布有效的[mcve]。 –

回答

1

你應該做這樣的事情:

JButton button = new JButton("ButtonName"); 
//add button to frame 
frame.add(button);  
//Add action listener to button 
    button.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) 
     { 
      //Execute when button is pressed 
      System.out.println("You clicked the button"); 
     } 
    });   
2

confirm.addMouseListener((MouseListener) new mouseClick()); 

我想mouseClick是您在貼類下面的例子。你爲什麼把它投到MouseListener?它不執行MouseListener

無論如何,你最好用ActionListener來代替它(匿名課程在這裏可以很好地工作),例如,

confirm.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     ...   
    } 
}); 

閱讀Pros and cons of using ActionListener vs. MouseListener for capturing clicks on a JButton更多信息

1

您既可以使用ActionListener使用這樣的事情:

anyBtn.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     //Your Code Here 
    } 
}); 

或者你可以使用一個Lambda如下所示:

anyBtn.addActionListener(e -> 
{ 
    //Your Code Here 
}); 

您不應該在該wa中使用MouseListener永遠。這不是它的目的。

+0

我使用了ActionListener和Lambda,但是出現錯誤。 – ChristosV

+0

@ChristosV將您的問題發佈爲新問題並將其鏈接至該問題。 – Jonah