public void closeFrame ()
{
jPanel.removeAll ();
String x = "";
JLabel exit = new JLabel ("Click Anywhere To Close!", JLabel.CENTER);
exit.setPreferredSize (new Dimension (700, 100));
jPanel.add (exit);
jPanel.revalidate ();
MouseListener ml = new MouseAdapter ()
{
public void mouseClicked (MouseEvent event)
{
//Put JFrame close code here
dispose ();
System.exit (0);
}
}
;
addMouseListener (ml);
validate (); //This hasn't made a difference :(
}
该类扩展了JFrame,并且DOESNT实现了MouseListener。尽管如此,代码不起作用。
这就是JFrame初始化的样子(希望它有帮助)......
public void createFrame ()
{
new JFrame (":) :)");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
//Some Initialization for jPanel variable
getContentPane().add(jPanel);
pack();
}
如何使此代码正常工作?如果我不能,是否有另一种方法可以关闭鼠标点击?
--- --- EDIT
感谢Hovercraft Full Of Eels
必须将MouseListener添加到JPanel
//WORKING CODE
public void closeFrame ()
{
jPanel.removeAll ();
String x = "";
JLabel exit = new JLabel ("Click Anywhere To Close!", JLabel.CENTER);
exit.setPreferredSize (new Dimension (700, 100));
jPanel.add (exit);
//jPanel.revalidate ();
MouseListener ml = new MouseAdapter ()
{
public void mouseClicked (MouseEvent event)
{
//Put JFrame close code here
dispose ();
System.exit (0);
}
}
;
jPanel.addMouseListener (ml);
jPanel.revalidate ();
}
答案 0 :(得分:2)
我不得不想知道你添加MouseListener的JFrame contentPane是否与正在显示的JFrame不同,特别是因为我看到你在createFrame方法中创建了一个新的JFrame。您了解MouseListener仅在添加到可视化组件时才起作用,对吗?
建议:
答案 1 :(得分:1)
这就是我的所作所为。
btnClose = new JButton("Close");
btnClose.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
dispose();
}
});
btnClose.setBounds(253, 190, 75, 25);
contentPane.add(btnClose);
}