下面列出了怎么用sun.awt.SunToolkit的API类实例代码及写法,或者点击链接到github查看源代码。
private static MouseEvent newMouseEvent(
Component source, Point point, MouseEvent template )
{
MouseEvent e = template;
MouseEvent nme = new MouseEvent(
source,
e.getID(), e.getWhen(),
e.getModifiersEx() | e.getModifiers(),
point.x, point.y,
e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(), e.getButton() );
// Because these MouseEvents are dispatched directly to
// their target, we need to mark them as being
// system-generated here
SunToolkit.setSystemGenerated(nme);
return nme;
}
public static final void main(String args[])
{
final Frame frame = new Frame();
final List list = new List();
list.add(" item 0 ");
list.add(" item 1 ");
frame.add(list);
frame.setLayout(new FlowLayout());
frame.setBounds(100,100,300,300);
frame.setVisible(true);
list.select(0);
list.deselect(1);
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
if (list.getSelectedIndex() != 0){
throw new RuntimeException("Test failed: List.getSelectedIndex() returns "+list.getSelectedIndex());
}
}
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);
}
}
boolean isWindowPerpixelTranslucencySupported() {
/*
* Per-pixel alpha is supported if all the conditions are TRUE:
* 1. The toolkit is a sort of SunToolkit
* 2. The toolkit supports translucency in general
* (isWindowTranslucencySupported())
* 3. There's at least one translucency-capable
* GraphicsConfiguration
*/
Toolkit curToolkit = Toolkit.getDefaultToolkit();
if (!(curToolkit instanceof SunToolkit)) {
return false;
}
if (!((SunToolkit)curToolkit).isWindowTranslucencySupported()) {
return false;
}
// TODO: cache translucency capable GC
return getTranslucencyCapableGC() != null;
}
private static void initRoughColor(){
Canvas canvas = new Canvas();
canvas.setBackground(color);
frame.add(canvas, BorderLayout.CENTER);
frame.validate();
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
Point loc = canvas.getLocationOnScreen();
Color robotColor = robot.getPixelColor(loc.x + canvas.getWidth()/2, loc.y + canvas.getHeight()/2);
roughColor = robotColor;
Sysout.println(" --- init rough color ... ");
Sysout.println(" color = "+color);
Sysout.println(" roughColor = "+roughColor);
frame.remove(canvas);
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
}
private boolean repostIfFollowsKeyEvents(WindowEvent e) {
if (!(e instanceof TimedWindowEvent)) {
return false;
}
TimedWindowEvent we = (TimedWindowEvent)e;
long time = we.getWhen();
synchronized (this) {
KeyEvent ke = enqueuedKeyEvents.isEmpty() ? null : enqueuedKeyEvents.getFirst();
if (ke != null && time >= ke.getWhen()) {
TypeAheadMarker marker = typeAheadMarkers.isEmpty() ? null : typeAheadMarkers.getFirst();
if (marker != null) {
Window toplevel = marker.untilFocused.getContainingWindow();
// Check that the component awaiting focus belongs to
// the current focused window. See 8015454.
if (toplevel != null && toplevel.isFocused()) {
SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e));
return true;
}
}
}
}
return false;
}
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();
}
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();
}
private void stopLWModal() {
synchronized (getTreeLock()) {
if (modalAppContext != null) {
Container nativeContainer = getHeavyweightContainer();
if(nativeContainer != null) {
if (this.modalComp != null) {
nativeContainer.modalComp = this.modalComp;
this.modalComp = null;
return;
}
else {
nativeContainer.modalComp = null;
}
}
// Wake up event dispatch thread on which the dialog was
// initially shown
SunToolkit.postEvent(modalAppContext,
new PeerEvent(this,
new WakingRunnable(),
PeerEvent.PRIORITY_EVENT));
}
EventQueue.invokeLater(new WakingRunnable());
getTreeLock().notifyAll();
}
}
boolean isWindowPerpixelTranslucencySupported() {
/*
* Per-pixel alpha is supported if all the conditions are TRUE:
* 1. The toolkit is a sort of SunToolkit
* 2. The toolkit supports translucency in general
* (isWindowTranslucencySupported())
* 3. There's at least one translucency-capable
* GraphicsConfiguration
*/
Toolkit curToolkit = Toolkit.getDefaultToolkit();
if (!(curToolkit instanceof SunToolkit)) {
return false;
}
if (!((SunToolkit)curToolkit).isWindowTranslucencySupported()) {
return false;
}
// TODO: cache translucency capable GC
return getTranslucencyCapableGC() != null;
}
@Override
protected void eventPosted(final SunDropTargetEvent e) {
if (e.getID() != SunDropTargetEvent.MOUSE_DROPPED) {
Runnable runnable = new Runnable() {
@Override
public void run() {
e.getDispatcher().unregisterAllEvents();
}
};
// NOTE: this PeerEvent must be a NORM_PRIORITY event to be
// dispatched after this SunDropTargetEvent, but before the next
// one, so we should pass zero flags.
PeerEvent peerEvent = new PeerEvent(e.getSource(), runnable, 0);
SunToolkit.executeOnEventHandlerThread(peerEvent);
}
}
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);
}
}
private static void test() {
if (!isXAWT){
Sysout.println(" this is XAWT-only test. ");
return;
}
frame = new Frame();
frame.setBounds(400,400,200,200);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
try{
robot = new Robot();
}catch(AWTException e){
throw new RuntimeException(e.getMessage());
}
initRoughColor();
Component[] components = new Component[] {
new Button(), new Checkbox(), new Label(), new List(3, false),
new TextArea(), new TextField(), new Choice()
};
for (Component component : components) {
testComponent(new Panel(), component, color);
}
frame.dispose();
}
public void handleConfigureNotifyEvent(XEvent xev)
{
assert (SunToolkit.isAWTLockHeldByCurrentThread());
XConfigureEvent xe = xev.get_xconfigure();
if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
xembedLog.fine(xe.toString());
}
// fix for 5063031
// if we use super.handleConfigureNotifyEvent() we would get wrong
// size and position because embedded frame really is NOT a decorated one
checkIfOnNewScreen(toGlobal(new Rectangle(xe.get_x(),
xe.get_y(),
xe.get_width(),
xe.get_height())));
Rectangle oldBounds = getBounds();
synchronized (getStateLock()) {
x = xe.get_x();
y = xe.get_y();
width = xe.get_width();
height = xe.get_height();
dimensions.setClientSize(width, height);
dimensions.setLocation(x, y);
}
if (!getLocation().equals(oldBounds.getLocation())) {
handleMoved(dimensions);
}
reconfigureContentWindow(dimensions);
}
public void drawPolyline(SunGraphics2D sg2d,
int xpoints[], int ypoints[],
int npoints)
{
SunToolkit.awtLock();
try {
long xgc = validate(sg2d);
XDrawPoly(sg2d.surfaceData.getNativeOps(), xgc,
sg2d.transX, sg2d.transY,
xpoints, ypoints, npoints, false);
} finally {
SunToolkit.awtUnlock();
}
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(20);
final JFrame frame = new JFrame();
frame.setUndecorated(true);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTableHeader th = new JTableHeader();
th.setColumnModel(new JTable(20, 5).getColumnModel());
th.setUI(new MyTableHeaderUI());
frame.add(th);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
toolkit.realSync();
Point point = frame.getLocationOnScreen();
int shift = 10;
int x = point.x;
int y = point.y + frame.getHeight()/2;
for(int i = -shift; i < frame.getWidth() + 2*shift; i++) {
robot.mouseMove(x++, y);
}
toolkit.realSync();
// 9 is a magic test number
if (MyTableHeaderUI.getTestValue() != 9) {
throw new RuntimeException("Unexpected test number "
+ MyTableHeaderUI.getTestValue());
}
System.out.println("ok");
}
public static void main(String[] args) throws Throwable {
EventQueue q = Toolkit.getDefaultToolkit().getSystemEventQueue();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
q.postEvent(new PostActionEvent());
for (int k = 0; k < 10; k++) {
SunToolkit.postEvent(AppContext.getAppContext(), new PostActionEvent());
}
}
for (int k = 0; k < 100; k++) {
SunToolkit.postEvent(AppContext.getAppContext(), new PostActionEvent());
}
}
for (;;) {
Thread.currentThread().sleep(100);
if (q.peekEvent() == null) {
Thread.currentThread().sleep(100);
if (q.peekEvent() == null)
break;
}
}
if (!testPassed) {
throw new Exception("PostEventOrderingTest FAILED -- events dispatched out of order.");
} else {
System.out.println("PostEventOrderingTest passed!");
}
}
private static void sleep() {
try {
((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
Thread.sleep(1000);
} catch (final InterruptedException ignored) {
}
}
public void Scale(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int sx1, int sy1, int sx2, int sy2, double dx1, double dy1,
double dx2, double dy2) {
{
int w = sx2 - sx1;
int h = sy2 - sy1;
try {
SunToolkit.awtLock();
XRSurfaceData vImgSurface = XRPMBlitLoops.cacheToTmpSurface(src, (XRSurfaceData) dst, w, h, sx1, sy1);
pmToSurfaceBlit.Scale(vImgSurface, dst, comp, clip, 0, 0, w, h, dx1, dy1, dx2, dy2);
} finally {
SunToolkit.awtUnlock();
}
}
}
/**
* Get the most recent event time in the {@code EventQueue} which the {@code source}
* belongs to.
*
* @param source the source of the event
* @exception IllegalArgumentException if source is null.
* @return most recent event time in the {@code EventQueue}
*/
private static long getMostRecentEventTimeForSource(Object source) {
if (source == null) {
// throw the IllegalArgumentException to conform to EventObject spec
throw new IllegalArgumentException("null source");
}
AppContext appContext = SunToolkit.targetToAppContext(source);
EventQueue eventQueue = SunToolkit.getSystemEventQueueImplPP(appContext);
return AWTAccessor.getEventQueueAccessor().getMostRecentEventTime(eventQueue);
}
public void fillArc(SunGraphics2D sg2d,
int x, int y, int width, int height,
int startAngle, int arcAngle)
{
SunToolkit.awtLock();
try {
long xgc = validate(sg2d);
XFillArc(sg2d.surfaceData.getNativeOps(), xgc,
x+sg2d.transX, y+sg2d.transY, width, height,
startAngle, arcAngle);
} finally {
SunToolkit.awtUnlock();
}
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absoluteX,
int absoluteY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaMouseModifiers(buttonNumber,
modifierFlags);
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absoluteX, absoluteY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
public static void main(String... args) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(20);
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
new bug4743225().setVisible(true);
}
});
toolkit.realSync();
// calling this method from main thread is ok
Point point = cb.getLocationOnScreen();
robot.mouseMove(point.x + 10, point.y + 10);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
if(getPopup().getList().getLastVisibleIndex() == 3) {
flag = true;
}
}
});
if (!flag) {
throw new RuntimeException("The ComboBox popup wasn't correctly updated");
}
}
public void dispatch() {
try {
if (nested != null) {
Toolkit.getEventQueue().dispatchEvent(nested);
}
} finally {
dispatched = true;
if (toNotify != null) {
SunToolkit.postEvent(toNotify, new SentEvent());
}
synchronized (this) {
notifyAll();
}
}
}
private static void sleep() {
((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {
}
}
private static void setLayersOpaque(Component component, boolean isOpaque) {
// Shouldn't use instanceof to avoid loading Swing classes
// if it's a pure AWT application.
if (SunToolkit.isInstanceOf(component, "javax.swing.RootPaneContainer")) {
javax.swing.RootPaneContainer rpc = (javax.swing.RootPaneContainer)component;
javax.swing.JRootPane root = rpc.getRootPane();
javax.swing.JLayeredPane lp = root.getLayeredPane();
Container c = root.getContentPane();
javax.swing.JComponent content =
(c instanceof javax.swing.JComponent) ? (javax.swing.JComponent)c : null;
lp.setOpaque(isOpaque);
root.setOpaque(isOpaque);
if (content != null) {
content.setOpaque(isOpaque);
// Iterate down one level to see whether we have a JApplet
// (which is also a RootPaneContainer) which requires processing
int numChildren = content.getComponentCount();
if (numChildren > 0) {
Component child = content.getComponent(0);
// It's OK to use instanceof here because we've
// already loaded the RootPaneContainer class by now
if (child instanceof javax.swing.RootPaneContainer) {
setLayersOpaque(child, isOpaque);
}
}
}
}
}
/**
* Return a volatile offscreen buffer that should be used as a
* double buffer with the specified component <code>c</code>.
* The image returned will be an instance of VolatileImage, or null
* if a VolatileImage object could not be instantiated.
* This buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>.
* This happens when the maximum double buffer size has been set for this
* repaint manager.
*
* @see java.awt.image.VolatileImage
* @since 1.4
*/
public Image getVolatileOffscreenBuffer(Component c,
int proposedWidth,int proposedHeight) {
RepaintManager delegate = getDelegate(c);
if (delegate != null) {
return delegate.getVolatileOffscreenBuffer(c, proposedWidth,
proposedHeight);
}
// If the window is non-opaque, it's double-buffered at peer's level
Window w = (c instanceof Window) ? (Window)c : SwingUtilities.getWindowAncestor(c);
if (!w.isOpaque()) {
Toolkit tk = Toolkit.getDefaultToolkit();
if ((tk instanceof SunToolkit) && (((SunToolkit)tk).needUpdateWindow())) {
return null;
}
}
GraphicsConfiguration config = c.getGraphicsConfiguration();
if (config == null) {
config = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
}
Dimension maxSize = getDoubleBufferMaximumSize();
int width = proposedWidth < 1 ? 1 :
(proposedWidth > maxSize.width? maxSize.width : proposedWidth);
int height = proposedHeight < 1 ? 1 :
(proposedHeight > maxSize.height? maxSize.height : proposedHeight);
VolatileImage image = volatileMap.get(config);
if (image == null || image.getWidth() < width ||
image.getHeight() < height) {
if (image != null) {
image.flush();
}
image = config.createCompatibleVolatileImage(width, height,
volatileBufferType);
volatileMap.put(config, image);
}
return image;
}
public static void main(String args[]) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
table.getRowSorter().toggleSortOrder(0);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.setRowSelectionInterval(1, 2);
}
});
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
for (int i = 0; i < ROW_COUNT; i++) {
tableModel.remove(0);
table.getRowSorter().toggleSortOrder(0);
}
}
});
}
void paintDamagedAreaImmediately() {
// force Windows to send any pending WM_PAINT events so
// the damage area is updated on the Java side
updateWindow();
// make sure paint events are transferred to main event queue
// for coalescing
SunToolkit.flushPendingEvents();
// paint the damaged area
paintArea.paint(target, shouldClearRectBeforePaint());
}
public void drawPolygon(SunGraphics2D sg2d,
int xpoints[], int ypoints[],
int npoints)
{
SunToolkit.awtLock();
try {
long xgc = validate(sg2d);
XDrawPoly(sg2d.surfaceData.getNativeOps(), xgc,
sg2d.transX, sg2d.transY,
xpoints, ypoints, npoints, true);
} finally {
SunToolkit.awtUnlock();
}
}