下面列出了怎么用javax.swing.Timer的API类实例代码及写法,或者点击链接到github查看源代码。
/** Preset. */
public MapRenderer() {
setOpaque(true);
addMouseListener(ma);
addMouseMotionListener(ma);
addMouseListener(sma);
addMouseMotionListener(sma);
animationTimer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//wrap animation index
if (animation == Integer.MAX_VALUE) {
animation = -1;
}
animation++;
if (surface != null && surface.buildings.size() > 0) {
boolean blink0 = blink;
blink = (animation % 10) >= 5;
if (blink0 != blink || (animation % 3 == 0)) {
repaint();
}
}
}
});
animationTimer.start();
}
RepaintFilter(final ProcessRendererView view) {
ActionListener repaintListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
if (repaintRequested.get() && counter >= COUNTER_BARRIER) {
counter = 0;
repaintRequested.set(false);
view.doRepaint();
}
}
};
Timer timer = new Timer(TIMER_INTERVAL, repaintListener);
timer.start();
}
public RotatingIcon(Icon icon) {
delegateIcon = icon;
rotatingTimer = new Timer( 200, new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
angleInDegrees = angleInDegrees + 40;
if ( angleInDegrees == 360 ){
angleInDegrees = 0;
}
for(DefaultTableModel model : cells.keySet()) {
for(Point c : cells.get(model))
model.fireTableCellUpdated(c.x, c.y);
}
}
} );
rotatingTimer.setRepeats( false );
rotatingTimer.start();
}
TestWindow(final int num) {
super("Test Window [" + num + "]");
setMinimumSize(new Dimension(300, 200));
setLocation(100 + 400 * (num - 1), 100);
setLayout(new BorderLayout());
JLabel textBlock = new JLabel("Lorem ipsum dolor sit amet...");
add(textBlock);
btn = new JButton("TEST");
add(btn, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
t = new Timer(INTERVAL, this);
t.setRepeats(false);
}
@Override
public void layoutContainer(Container parent) {
JComponent jc = (JComponent) parent;
install(jc);
Timer timer = (Timer) jc.getClientProperty(PROPERTY_TIMER);
Boolean layoutImmediately = (Boolean) jc
.getClientProperty(PROPERTY_LAYOUT_IMMEDIATELY);
if (layoutImmediately == null)
layoutImmediately = false;
if (layoutImmediately) {
layoutContainerImmediately(jc);
if (parent.isShowing())
jc.putClientProperty(PROPERTY_LAYOUT_IMMEDIATELY, false);
} else {
if (!timer.isRunning())
timer.start();
}
}
public BranchSelector (File repository) {
this.repository = repository;
panel = new BranchSelectorPanel();
panel.branchList.setCellRenderer(new RevisionRenderer());
filterTimer = new Timer(300, new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
filterTimer.stop();
applyFilter();
}
});
panel.txtFilter.getDocument().addDocumentListener(this);
panel.branchList.addListSelectionListener(this);
panel.jPanel1.setVisible(false);
cancelButton = new JButton();
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(BranchSelector.class, "CTL_BranchSelector_Action_Cancel")); // NOI18N
cancelButton.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(BranchSelector.class, "ACSD_BranchSelector_Action_Cancel")); // NOI18N
cancelButton.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(BranchSelector.class, "ACSN_BranchSelector_Action_Cancel")); // NOI18N
}
public CursorBlinker(FieldPanel panel) {
this.fieldPanel = panel;
timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (paintBounds != null) {
showCursor = !showCursor;
fieldPanel.paintImmediately(paintBounds);
}
else {
timer.stop();
}
}
});
// the initial painting is laggy for some reason, so shorten the delay
timer.setInitialDelay(100);
timer.start();
}
public void fadeOut() {
final Timer timer = new Timer(FADE_REFRESH_RATE, null);
timer.setRepeats(true);
timer.addActionListener(new ActionListener() {
private float opacity = MAX_OPACITY;
@Override
public void actionPerformed(ActionEvent e) {
opacity -= OPACITY_INCREMENT;
setOpacity(Math.max(opacity, 0));
if (opacity <= 0) {
timer.stop();
setVisible(false);
dispose();
}
}
});
setOpacity(MAX_OPACITY);
timer.start();
}
public RTStatsTimer(){
// We call the constructer of the parent-class
super();
// We get the configuration of GUI_REFRESH_INTERVAL
double interval = Config.getConfigByName("tester.properties").getDouble("stats.GUI_REFRESH_INTERVAL", 1);
// We create a new timer with this config value as interval
clock = new Timer((int)(interval * 1000), this);
// We want an action repeating
clock.setRepeats(true);
// We start the timer
clock.start();
// We record this in the logger
GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE, "Refresh interval for real-times statistics is ", interval, "s");
}
/** Creates new TextGridBox */
public TextGrid(AbstractBox parent, JComponent container, double setX, double setY, int setNcw, int setNch,
double setCellW, double setCellH, BoxBase boxBase, boolean setBorder) {
super(parent, container, boxBase);
x = setX;
y = setY;
nCols = Math.max(1, setNcw);
nRows = Math.max(1, setNch);
cellWidth = Math.max(setCellW, MIN_CELL_SIZE);
cellHeight = Math.max(setCellH, MIN_CELL_SIZE);
width = cellWidth * nCols;
height = cellHeight * nRows;
chars = new char[nRows][nCols];
attributes = new int[nRows][nCols];
preferredBounds.setRect(getBounds());
setBorder(setBorder);
cursorTimer = new Timer(500, this);
cursorTimer.setRepeats(true);
cursorEnabled = false;
useCursor = false;
wildTransparent = false;
answers = null;
}
public void startRecording() {
recordAudioButton.setSelected(true);
recording = true;
// getItems().add(pb);
getItems().add(recordingPathTextField);
recordAudioButton.setText("Recording...");
recordAudioButton.setSelected(true);
recordingsHandler = new RecordButtonHandler();
recordingsHandler.passVariables("rec", pb, recordingPathTextField, recordAudioButton);
final int interval = 1000; // 1000 ms
recCount = new Timer(interval, (java.awt.event.ActionEvent e) -> {
recTime += interval;
setTime(recTime, recordAudioButton);
});
recCount.start();
}
/**
* Initialize timers and handle their ticks.
*/
private void initTimer() {
timer = new Timer(0, new java.awt.event.ActionListener() {
// we are called from the AWT thread so put itno other one
public void actionPerformed(java.awt.event.ActionEvent e) {
if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug("$$ TextEditorSupport::initTimer::actionPerformed: event = " + e);
RequestProcessor.postRequest( new Runnable() {
public void run() {
syncDocument(false);
}
});
}
});
timer.setInitialDelay(getAutoParsingDelay());
timer.setRepeats(false);
}
TestWindow(final int num) {
super("Test Window [" + num + "]");
setMinimumSize(new Dimension(300, 200));
setLocation(100 + 400 * (num - 1), 100);
setLayout(new BorderLayout());
JLabel textBlock = new JLabel("Lorem ipsum dolor sit amet...");
add(textBlock);
btn = new JButton("TEST");
add(btn, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
t = new Timer(INTERVAL, this);
t.setRepeats(false);
}
/**
* Initializes the Form
*/
public MemoryView() {
initComponents();
setTitle(bundle.getString("TXT_TITLE"));
doGarbage.setText(bundle.getString("TXT_GARBAGE"));
doRefresh.setText(bundle.getString("TXT_REFRESH"));
doClose.setText(bundle.getString("TXT_CLOSE"));
txtTime.setText(bundle.getString("TXT_TIME"));
doTime.setText(bundle.getString("TXT_SET_TIME"));
time.setText(String.valueOf(UPDATE_TIME));
time.selectAll();
time.requestFocus();
updateStatus();
timer = new Timer(UPDATE_TIME, new ActionListener() {
public void actionPerformed(ActionEvent ev) {
updateStatus();
}
});
timer.setRepeats(true);
pack();
}
@Override
public void hierarchyChanged(HierarchyEvent event) {
if ((event.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (isDisplayable()) {
// for (Tile tile: dimension.getTiles()) {
// threeDeeRenderManager.renderTile(tile);
// }
timer = new Timer(250, this);
timer.start();
} else {
timer.stop();
timer = null;
threeDeeRenderManager.stop();
for (Tile tile : dimension.getTiles()) {
tile.removeListener(this);
}
dimension.removeDimensionListener(this);
}
}
}
private void updateSettings(boolean valid) {
start.setEnabled(valid);
boolean _configure = features.getActivated().isEmpty();
start.setVisible(!_configure);
stop.setVisible(!_configure);
configure.setVisible(_configure);
new Timer(0, null) {
{
setRepeats(false);
setInitialDelay(50);
}
protected void fireActionPerformed(ActionEvent e) {
updateFocus();
}
}.start();
if (session.inProgress()) session.doModify(features.getSettings());
}
public void animate(Notification note, Location loc, double delay, double slideDelta, boolean slideIn) {
m_note = note;
m_x = note.getX();
m_y = note.getY();
m_delta = Math.abs(slideDelta);
m_slideIn = slideIn;
m_startLocation = loc;
if (m_slideIn) {
m_stopX = m_standardScreen.getX(m_startLocation, note);
m_stopY = m_standardScreen.getY(m_startLocation, note);
} else {
m_stopX = m_noPaddingScreen.getX(m_startLocation, note);
m_stopY = m_noPaddingScreen.getY(m_startLocation, note);
}
Timer timer = new Timer((int) delay, this);
timer.start();
}
private Timer createInitialEffect() {
final Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if( contentAlpha < 1.0f ) {
contentAlpha += ALPHA_INCREMENT;
} else {
timer.stop();
}
if( contentAlpha > 1.0f )
contentAlpha = 1.0f;
repaintImageBuffer();
repaint();
}
});
timer.setInitialDelay(0);
return timer;
}
private Timer createNoDropEffect() {
final Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if( contentAlpha > NO_DROP_ALPHA ) {
contentAlpha -= ALPHA_INCREMENT;
} else {
timer.stop();
}
if( contentAlpha < NO_DROP_ALPHA )
contentAlpha = NO_DROP_ALPHA;
repaintImageBuffer();
repaint();
}
});
timer.setInitialDelay(0);
return timer;
}
@Override
public void start() {
monitoringTimer = new Timer(1000, e -> {
if (uploadMonitor == null || downloadMonitor == null)
return;
try {
frame.setRates(downloadMonitor.getAverageRate(), uploadMonitor.getAverageRate());
Date minAge = new Date(System.currentTimeMillis() - 2000);
downloadMonitor.removeOldSamples(minAge);
uploadMonitor.removeOldSamples(minAge);
} catch (Exception ex) {
LOGGER.warn("Can't upload monitoring!", ex);
}
});
monitoringTimer.setRepeats(true);
monitoringTimer.start();
super.start();
}
public FadeInFadeOutHelper() {
componentToHighlightTimer = new Timer(50, e -> {
if (componentToHighlightFadeOut) {
if (componentToHighlightPosition > 0) {
componentToHighlightPosition -= 40;
} else {
componentToHighlightFadeOut = false;
componentToHighlight = componentToHighlightNext;
}
} else {
if (componentToHighlightNext != null) {
componentToHighlight = componentToHighlightNext;
componentToHighlightNext = null;
}
if (componentToHighlight != null) {
Dimension theSize = componentToHighlight.getSize();
if (componentToHighlightPosition < theSize.width + 10) {
int theStep = theSize.width + 10 - componentToHighlightPosition;
if (theStep > 40) {
theStep = 40;
}
componentToHighlightPosition += theStep;
} else {
componentToHighlightTimer.stop();
}
} else {
componentToHighlightTimer.stop();
}
}
doRepaint();
});
componentToHighlightWaitTimer = new Timer(1000, e -> componentToHighlightTimer.start());
componentToHighlightWaitTimer.setRepeats(false);
}
/**
* Handles the ProgressEvent triggered from the history when processing
* a query.
* @param evt the <tt>ProgressEvent</tt> that notified us
*/
public void progressChanged(ProgressEvent evt)
{
int progress = evt.getProgress();
if((lastProgress != progress)
&& evt.getStartDate() == null
|| evt.getStartDate() != ignoreProgressDate)
{
this.progressBar.setValue(progress);
if(progressBar.getPercentComplete() == 1.0)
{
// Wait 1 sec and remove the progress bar from the main panel.
Timer progressBarTimer = new Timer(1 * 1000, null);
progressBarTimer.setRepeats(false);
progressBarTimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainPanel.remove(progressBar);
mainPanel.add(readyLabel, BorderLayout.SOUTH);
mainPanel.revalidate();
mainPanel.repaint();
progressBar.setValue(0);
}
});
progressBarTimer.start();
}
lastProgress = progress;
}
}
protected void installListeners() {
fTrackListener = createTrackListener();
fModelListener = createModelListener();
fPropertyChangeListener = createPropertyChangeListener();
fScrollBar.addMouseListener(fTrackListener);
fScrollBar.addMouseMotionListener(fTrackListener);
fScrollBar.getModel().addChangeListener(fModelListener);
fScrollBar.addPropertyChangeListener(fPropertyChangeListener);
fScrollListener = createScrollListener();
fScrollTimer = new Timer(kNormalDelay, fScrollListener);
fScrollTimer.setInitialDelay(kInitialDelay); // default InitialDelay?
}
public void actionPerformed(final ActionEvent e) {
if (fUseBlockIncrement) {
Hit newPart = getPartHit(fTrackListener.fCurrentMouseX, fTrackListener.fCurrentMouseY);
if (newPart == ScrollBarHit.TRACK_MIN || newPart == ScrollBarHit.TRACK_MAX) {
final int newDirection = (newPart == ScrollBarHit.TRACK_MAX ? 1 : -1);
if (fDirection != newDirection) {
fDirection = newDirection;
}
}
scrollByBlock(fDirection);
newPart = getPartHit(fTrackListener.fCurrentMouseX, fTrackListener.fCurrentMouseY);
if (newPart == ScrollBarHit.THUMB) {
((Timer)e.getSource()).stop();
}
} else {
scrollByUnit(fDirection);
}
if (fDirection > 0 && fScrollBar.getValue() + fScrollBar.getVisibleAmount() >= fScrollBar.getMaximum()) {
((Timer)e.getSource()).stop();
} else if (fDirection < 0 && fScrollBar.getValue() <= fScrollBar.getMinimum()) {
((Timer)e.getSource()).stop();
}
}
public Toast(int delay, String message, Point p)
{
// super(parent);
initGUI();
// init datas
timer = new Timer(delay, this);
toastPane.setMessage(message);
this.showPossition = p;
}
public Clock() {
super();
CLOCK_TIMER = new Timer(1000, this);
INNER_BOUNDS = new Rectangle(200, 200);
init(getInnerBounds().width, getInnerBounds().height);
setPointerColor(ColorDef.BLACK);
horizontalAlignment = SwingConstants.CENTER;
verticalAlignment = SwingConstants.CENTER;
//CLOCK_TIMER.start();
}
@Override
public void actionPerformed(final ActionEvent event) {
if (m_model.hasData(m_startAddress, m_numberOfBytes)) {
JStackPanel.this.setEnabled(true);
setDefinitionStatus(DefinitionStatus.DEFINED);
((Timer) event.getSource()).stop();
} else if (!m_model.keepTrying()) {
((Timer) event.getSource()).stop();
}
}
private JComponent createDebugPanel() {
BufferedImage img = (BufferedImage) getClientProperty("debug.ghost.image");
if (img == null)
return this;
final CardLayout cardLayout = new CardLayout();
final JPanel panel = new JPanel(cardLayout);
JPanel imagePanel = new JPanel();
imagePanel.setUI(new PanelImageUI(img));
JPanel paneWrapper = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
paneWrapper.add(this, c);
panel.add(paneWrapper, "real");
panel.add(imagePanel, "debug");
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String mode = (System.currentTimeMillis() % 4000) > 2000 ? "real"
: "debug";
cardLayout.show(panel, mode);
}
});
timer.start();
return panel;
}
private void createUIComponents() {
userAccountPanel = new UserAccountPanel();
refreshButton = new JButton(AllIcons.Actions.Refresh);
// Create timer for filtering the list
timer = new Timer(400, null);
timer.setInitialDelay(400);
timer.setActionCommand(CMD_PROJECT_FILTER_CHANGED);
timer.setRepeats(false);
}
public void run() {
Timer timer = new Timer(1000, this);
timer.setRepeats(false);
timer.start();
JColorChooser chooser = new JColorChooser();
setEnabledRecursive(chooser, false);
this.dialog = new JDialog();
this.dialog.add(chooser);
this.dialog.setVisible(true);
}