当我点击按钮java
问题描述:
时,什么也没有发生我有一个应用程序,当你运行它时,你需要一个面板,以添加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
答
你应该做这样的事情:
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");
}
});
答
线
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更多信息
答
您既可以使用ActionListener使用这样的事情:
anyBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Your Code Here
}
});
或者你可以使用一个Lambda如下所示:
anyBtn.addActionListener(e ->
{
//Your Code Here
});
您不应该在该wa中使用MouseListener永远。这不是它的目的。
1.为正确的需要使用正确的侦听器,并且在这里从不以这种方式使用MouseListener,而在侦听JButton按下时使用ActionListener。 2.你有不寻常的现场参考建议可能过度使用静态字段 - 但我根据你迄今发布的内容无法判断。 3.为获得更好的帮助,请创建并发布有效的[mcve]。 –