下面列出了怎么用java.awt.Toolkit的API类实例代码及写法,或者点击链接到github查看源代码。
/** Creates and initializes the members of the {@link cursors} array. */
protected void createCursors() {
try {
Toolkit tk = Toolkit.getDefaultToolkit();
cursors[HAND_CURSOR] = tk.createCustomCursor(ResourceManager.getImageIcon("cursors/hand.gif").getImage(),
new Point(8, 0), "hand");
cursors[OK_CURSOR] = tk.createCustomCursor(ResourceManager.getImageIcon("cursors/ok.gif").getImage(),
new Point(0, 0), "ok");
cursors[REC_CURSOR] = tk.createCustomCursor(ResourceManager.getImageIcon("cursors/micro.gif").getImage(),
new Point(15, 3), "record");
} catch (Exception e) {
System.err.println("Error creating cursor:\n" + e);
}
}
private void adjustWindow() {
if (!parentFrame.isVisible()) {
return;
}
Point mainWindowLocation = parentFrame.getLocationOnScreen();
int x = (int)mainWindowLocation.getX() + parentFrame.getWidth();
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = getWidth();
if (width == 0) {
width = preferredWidth;
}
if ((int)screenSize.getWidth() - width < x) {
x = (int)mainWindowLocation.getX() - width;
}
setSize(preferredWidth, (int)parentFrame.getHeight());
setLocation(x, (int)mainWindowLocation.getY());
}
@Override
public JDialog getDialog(ApplicationFrame frame) {
JDialog dialog = new JDialog(frame, "About Opt4J", true);
dialog.setBackground(Color.WHITE);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setResizable(false);
Opt4JAbout content = new Opt4JAbout();
content.startup();
dialog.add(content);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Dimension window = dialog.getPreferredSize();
dialog.setLocation((screen.width - window.width) / 2, (screen.height - window.height) / 2);
return dialog;
}
public static void main(String[] args) throws IOException {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
RemoteControlFrame rcm = new RemoteControlFrame();
rcm.setVisible(true);
new Thread(new Runnable() {
public void run() {
while (true) {
BufferedImage img = ScreenCapture.getScreen(0, 0, (int) d.getWidth(), (int) d.getHeight());
rcm.setIcon(new ImageIcon(img));
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
if (isRVObserver()) {
isRVObserverCalled = true;
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Image resolutionVariant = getResolutionVariant(img);
int rvFlags = toolkit.checkImage(resolutionVariant, width, height,
new IdleImageObserver());
if (rvFlags < infoflags) {
throw new RuntimeException("Info flags are greater than"
+ " resolution varint info flags");
}
} else if ((infoflags & ALLBITS) != 0) {
isImageLoaded = true;
}
return (infoflags & ALLBITS) == 0;
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
toolkit.realSync();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_DELETE);
toolkit.realSync();
frame.dispose();
if (eventsCount != 3) {
throw new RuntimeException("Wrong number of key events: " + eventsCount);
}
}
/**
* Sets the location of the specified window so that it is centered on
* screen.
*
* @param window
* The window to be centered.
*/
public static void centerWindowOnScreen(Window window) {
final Dimension screenSize = Toolkit.getDefaultToolkit()
.getScreenSize();
final Dimension size = window.getSize();
if (size.height > screenSize.height) {
size.height = screenSize.height;
}
if (size.width > screenSize.width) {
size.width = screenSize.width;
}
window.setLocation((screenSize.width - size.width) / 2,
(screenSize.height - size.height) / 2);
}
@Override
public void tearDown() throws Exception {
Waiter waiter = new Waiter(new Waitable() {
@Override
public Object actionProduced(Object obj) {
Object clipboard2 = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
return clipboard1 != clipboard2 ? Boolean.TRUE : null;
}
@Override
public String getDescription() {
return ("Wait clipboard contains data");
}
});
waiter.waitAction(null);
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(50);
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
}
});
toolkit.realSync();
if (OSInfo.OSType.MACOSX.equals(OSInfo.getOSType())) {
Util.hitKeys(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_L);
} else {
Util.hitKeys(robot, KeyEvent.VK_ALT, KeyEvent.VK_L);
}
checkFocus();
}
/**
* Shows a dialog and verifies user entry of the password.
*
* @param password the password
* @param filename the name of the password-protected file (may be null).
* @return true if password is null, "", or correctly verified
*/
public static boolean verify(String password, String fileName) {
if((password==null)||password.equals("")) {//$NON-NLS-1$
return true;
}
Password dialog = new Password();
dialog.password = password;
if((fileName==null)||fileName.equals("")) { //$NON-NLS-1$
dialog.messageLabel.setText(ControlsRes.getString("Password.Message.Short")); //$NON-NLS-1$
} else {
dialog.messageLabel.setText(ControlsRes.getString("Password.Message.File") //$NON-NLS-1$
+" \""+XML.getName(fileName)+"\"."); //$NON-NLS-1$ //$NON-NLS-2$
}
dialog.pack();
// center on screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dim.width-dialog.getBounds().width)/2;
int y = (dim.height-dialog.getBounds().height)/2;
dialog.setLocation(x, y);
dialog.pass = false;
dialog.passwordField.setText(""); //$NON-NLS-1$
dialog.setVisible(true);
dialog.dispose();
return dialog.pass;
}
public void handleFocusEvent(boolean focused) {
synchronized (classLock) {
// In some cases an applet may not receive the focus lost event
// from the parent window (see 8012330)
globalFocusedWindow = (focused) ? this
: ((globalFocusedWindow == this) ? null : globalFocusedWindow);
}
if (globalFocusedWindow == this) {
// see bug 8010925
// we can't put this to handleWindowFocusEvent because
// it won't be invoced if focuse is moved to a html element
// on the same page.
CClipboard clipboard = (CClipboard) Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.checkPasteboardAndNotify();
}
if (parentWindowActive) {
responder.handleWindowFocusEvent(focused, null);
}
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
toolkit.realSync();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_DELETE);
toolkit.realSync();
frame.dispose();
if (eventsCount != 3) {
throw new RuntimeException("Wrong number of key events: " + eventsCount);
}
}
/**
* Creates a new Recorder.
*/
public Recorder() {
super( "Mouse Print Recorder" );
WhatToSave whatToSave_;
try {
whatToSave_ = WhatToSave.values()[ Settings.getInt( Settings.KEY_SETTINGS_MISC_MOUSE_PRINT_WHAT_TO_SAVE ) ];
} catch ( final IllegalArgumentException iae ) {
whatToSave_ = WhatToSave.values()[ Settings.getDefaultInt( Settings.KEY_SETTINGS_MISC_MOUSE_PRINT_WHAT_TO_SAVE ) ];
}
whatToSave = whatToSave_;
samplingTime = Settings.getInt( Settings.KEY_SETTINGS_MISC_MOUSE_PRINT_SAMPLING_TIME );
final Toolkit toolkit = Toolkit.getDefaultToolkit();
screenResolution = toolkit.getScreenResolution();
final Dimension screenSize = toolkit.getScreenSize();
buffer = new BufferedImage( screenSize.width, screenSize.height, BufferedImage.TYPE_INT_RGB );
dataStream = whatToSave.saveBinaryData ? new ByteArrayOutputStream( 100000 ) : null;
setRecorderFrameRefreshRate( RECORDER_REFRESH_RATES[ Settings.getInt( Settings.KEY_MOUSE_PRINT_REFRESH_RATE ) ] );
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Frame frame = new Frame();
frame.setSize(300, 200);
TextField textField = new TextField();
frame.add(textField);
frame.setVisible(true);
toolkit.realSync();
textField.requestFocus();
toolkit.realSync();
// Check that the system assertion dialog does not block Java
Robot robot = new Robot();
robot.setAutoDelay(50);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
toolkit.realSync();
frame.setVisible(false);
frame.dispose();
}
public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
Toolkit.getDefaultToolkit().setDynamicLayout(true);
System.setProperty("sun.awt.noerasebackground", "true");
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
System.out.println(
"Metal Look & Feel not supported on this platform. \n"
+ "Program Terminated");
System.exit(0);
}
JFrame frame = new MetalworksFrame();
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
final SunToolkit toolkit = ((SunToolkit) Toolkit.getDefaultToolkit());
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
setup();
}
});
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
verifySingleDefaultButtonModelListener();
doTest();
verifySingleDefaultButtonModelListener();
} finally {
frame.dispose();
}
}
});
}
@Override
public void run() {
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
JFileChooser fileopen = new JFileChooser();
fileopen.setFileFilter(new OpenFileFilter("bsh", "BSH files (*.bsh)"));
fileopen.setAcceptAllFileFilterUsed(false);
fileopen.setMultiSelectionEnabled(false);
fileopen.setPreferredSize(new Dimension(scr.width - 350, scr.height - 350));
if (fileopen.showOpenDialog(null) == 0) {
DebugMe.scriptFile = fileopen.getSelectedFile();
} else {
DebugMe.scriptFile = null;
}
dialogOpened.set(false);
}
/**
* Construct action.
*
* @param kseFrame
* KeyStore Explorer frame
*/
public RenameKeyAction(KseFrame kseFrame) {
super(kseFrame);
putValue(LONG_DESCRIPTION, res.getString("RenameKeyAction.statusbar"));
putValue(NAME, res.getString("RenameKeyAction.text"));
putValue(SHORT_DESCRIPTION, res.getString("RenameKeyAction.tooltip"));
putValue(
SMALL_ICON,
new ImageIcon(Toolkit.getDefaultToolkit().createImage(
getClass().getResource("images/rename.png"))));
}
private static void sleep() {
try {
((SunToolkit) (Toolkit.getDefaultToolkit())).realSync();
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
private static void sleep() {
try {
((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
Thread.sleep(1000);
} catch (final InterruptedException ignored) {
}
}
static String startHierarchyListener() {
if (hierarchyListener == null) {
hierarchyListener = new RemoteAWTHierarchyListener();
try {
Toolkit.getDefaultToolkit().addAWTEventListener(hierarchyListener, AWTEvent.HIERARCHY_EVENT_MASK);
} catch (SecurityException se) {
hierarchyListener = null;
return "Toolkit.addAWTEventListener() threw "+se.toString();
}
}
return null;
}
/**
* Constructs the Inspector.
*/
public Inspector() {
super(frame, !(frame instanceof org.opensourcephysics.display.OSPFrame));
setTitle(MediaRes.getString("Filter.DarkGhost.Title")); //$NON-NLS-1$
setResizable(false);
createGUI();
refresh();
pack();
// center on screen
Rectangle rect = getBounds();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dim.width-rect.width)/2;
int y = (dim.height-rect.height)/2;
setLocation(x, y);
}
public static void main(String[] args) throws Exception {
Frame frame = new Frame();
frame.setSize(300, 200);
TextField textField = new TextField(TEXT + LAST_WORD, 30);
Panel panel = new Panel(new FlowLayout());
panel.add(textField);
frame.add(panel);
frame.setVisible(true);
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
toolkit.realSync();
Robot robot = new Robot();
robot.setAutoDelay(50);
Point point = textField.getLocationOnScreen();
int x = point.x + textField.getWidth() / 2;
int y = point.y + textField.getHeight() / 2;
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
robot.mousePress(InputEvent.BUTTON1_MASK);
int N = 10;
int dx = textField.getWidth() / N;
for (int i = 0; i < N; i++) {
x += dx;
robot.mouseMove(x, y);
}
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
if (!textField.getSelectedText().endsWith(LAST_WORD)) {
throw new RuntimeException("Last word is not selected!");
}
}
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(50);
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
EventQueue.invokeAndWait(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComboBox<String> comboBox = new JComboBox<>(new String[]{"one", "two"});
comboBox.setEditable(true);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ("comboBoxEdited".equals(e.getActionCommand())) {
isComboBoxEdited = true;
}
}
});
frame.add(comboBox);
frame.pack();
frame.setVisible(true);
comboBox.requestFocusInWindow();
});
toolkit.realSync();
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
toolkit.realSync();
if(!isComboBoxEdited){
throw new RuntimeException("ComboBoxEdited event is not fired!");
}
}
@SuppressWarnings("deprecation")
@Override
public void addNotify() {
if (getPeer() == null) {
LWToolkit toolkit = (LWToolkit) Toolkit.getDefaultToolkit();
setPeer(toolkit.createEmbeddedFrame(this));
}
super.addNotify();
}
@Override
public void printFiles(PrintFilesEvent e) {
final List<File> files = e.getFiles();
for (final File file : files) { // legacy ApplicationListeners only understood one file at a time
final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit(), file.getAbsolutePath());
sendEventToEachListenerUntilHandled(ae, new EventDispatcher() {
public void dispatchEvent(final ApplicationListener listener) {
listener.handlePrintFile(ae);
}
});
}
}
private static void sleep() {
try {
((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
Thread.sleep(1000);
} catch (final InterruptedException ignored) {
}
}
public static Graphics2D prepareGraphics(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Map rhints = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
if( rhints == null && Boolean.getBoolean("swing.aatext") ) { //NOI18N
g2.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
} else if( rhints != null ) {
g2.addRenderingHints( rhints );
}
return g2;
}
/**
* Construct action.
*
* @param kseFrame
* KeyStore Explorer frame
*/
public KeyPairCertificateChainDetailsAction(KseFrame kseFrame) {
super(kseFrame);
putValue(LONG_DESCRIPTION, res.getString("KeyPairCertificateChainDetailsAction.statusbar"));
putValue(NAME, res.getString("KeyPairCertificateChainDetailsAction.text"));
putValue(SHORT_DESCRIPTION, res.getString("KeyPairCertificateChainDetailsAction.tooltip"));
putValue(
SMALL_ICON,
new ImageIcon(Toolkit.getDefaultToolkit().createImage(
getClass().getResource("images/certdetails.png"))));
}
public void sync() {
if (comp == null) {
Toolkit.getDefaultToolkit().sync();
} else {
comp.getToolkit().sync();
}
}