我在名为test2的包中名为Test2.java的文件中具有以下代码;使用throw/catch(java)的鼠标侦听器
package test2;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test2 {
public static void main(String[] args) {
int k = 7;
while(true) {
try {
JFrame mainWindow = new HtmlWindow(k);
} catch(UnsupportedOperationException numberChosen) {
JOptionPane.showInternalMessageDialog(null, "information",
"You clicked on number " + numberChosen,
JOptionPane.INFORMATION_MESSAGE);
Integer l = new Integer("0" + numberChosen);
}
}
}
}
我在同一个包中的一个名为HtmlWindow的文件中有以下代码;
package test2;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
class HtmlWindow extends JFrame implements MouseListener {
public HtmlWindow(int k) throws UnsupportedOperationException {
super("blah");
setSize(150, 200);
Container content = getContentPane();
content.setLayout(new FlowLayout());
JLabel[] coloredLabel = new JLabel[k];
String[] labelText = new String[k];
for(int i=0; i<=k-1; i++) {
labelText[i] = "<html><img src = "
+ "\"http://images.nycsubway.org/bullets/lines/"
+ (i+1)
+ ".GIF\">"
+ "</html>";
coloredLabel[i] = new JLabel(labelText[i]);
coloredLabel[i].setName((i + 1) + " ");
coloredLabel[i].addMouseListener(this);
addMouseListener(this);
content.add(coloredLabel[i]);
}
this.setVisible(true);
while(true) {
}
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
@Override
public void mouseClicked(MouseEvent me) {
throw new UnsupportedOperationException(me.getComponent().getName());
}
}
当我运行这一点,因为在它的数字图片预计将出现一个窗口,但是当我点击其中任何一个抛出的异常没有被捕获。为什么是这样?指针应该绕过HTMLWindow构造函数中的“while”部分,因此仍然位于“try”部分,因此应该被捕获。我的猜测是,这是因为mouseClicked部分不在HTMLWindow构造函数内,异常以某种方式抛出try块之外?
如果这不是从GUI获取信息回到原始程序的最佳方式,那是什么?我不认为这是通过使用“回报”,因为
- 构造函数没有返回类型
- 的mouseClicked不是构造函数中的任何方式
除了 - 我不是特别当我移动数字等时,希望程序做任何事情,只需点击它们即可。那么为什么我需要mousePressed模块等?没有它们,程序将不会编译。把它们留空就可以了吗?