【发布时间】:2017-01-12 13:43:14
【问题描述】:
我正在尝试添加一些代码,这些代码将在鼠标移动一定次数时启动计时器,下面的代码用于鼠标移动。我希望计时器持续 10 秒,并提醒用户计时器已经开始和结束。
public class MouseMotionEvent extends JPanel
implements MouseMotionListener {
BlankArea blankArea;
JTextArea textArea;
static final String NEWLINE = System.getProperty("line.separator");
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MouseMotionEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new MouseMotionEvent();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public MouseMotionEvent() {
super(new GridLayout(0,1));
blankArea = new BlankArea(Color.YELLOW);
add(blankArea);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(200, 75));
add(scrollPane);
blankArea.addMouseMotionListener(this);
addMouseMotionListener(this);
setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
void eventOutput(String eventDescription, MouseEvent e) {
textArea.append(eventDescription
+ " (" + e.getX() + "," + e.getY() + ")"
+ " detected on "
+ e.getComponent().getClass().getName()
+ NEWLINE);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public void mouseMoved(MouseEvent e) {
eventOutput("Mouse moved", e);
}
public void mouseDragged(MouseEvent e) {
eventOutput("Mouse dragged", e);
}
}
【问题讨论】:
-
小注:JTextAreas 总是使用
\n作为行分隔符,而不是系统的行分隔符。