Swing与AWT
From now on, we say “Swing” when we mean the “painted” user interface classes, and we say“AWT”(Abstract Window Toolkit) when we mean the underlying mechanisms of the windowing toolkit, such as event handling.
获取系统可用字体
String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (String fontName : fontNames)
System.out.println(fontName);
}
窗体大小的设置
If your frame contains only standard components such as buttons and text fields, you can simply call thepack method to set the frame size. The frame will be set to the smallest size that contains all components. It is quite common to set the main frame of a program to themaximum size. As of Java SE 1.4, you can simply maximize a frame by calling
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
float f = 1.2; // Error
float f = 1.2F; //Ok
读取图片文件
String filename = "...";
Image image = ImageIO.read(new File(filename));
String urlname = "...";
Image image = ImageIO.read(new URL(urlname));
g.drawImage(image, x, y, null);
给按钮加监听
you can use an anonymous inner class:
loadButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
frame.loadData();
}
});
But the EventHandler class can create such a listener automatically, with the call
(好混乱,还是上面那个好)
EventHandler.create(ActionListener.class, frame, "loadData")
action为接口而不是类
给面板添加键盘事件
InputMap imap = panel.getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
ActionMap amap = panel.getActionMap();
amap.put("panel.yellow", yellowAction);
It is customary to use the string "none" for a do-nothing action. That makes it easy to deactivate a key:
imap.put(KeyStroke.getKeyStroke("ctrl C"), "none");
完整示例1-3楼
更改系统鼠标形状
public void mouseMoved(MouseEvent event)
{
if (find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
NOTE: You can also define your own cursor types through the use of the createCustomCursor method in the Toolkit class:
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = tk.getImage("dynamite.gif");
Cursor dynamiteCursor = tk.createCustomCursor(img, new Point(10, 10), "dynamite stick");
Mouse Events
You do not need to handle mouse events explicitly if you just want the user to be able to click on a button or menu. These mouse operations are handled internally by the various components in the user interface. However, if you want to enable the user to draw with the mouse, you will need to trap mouse move, click, and drag events.
键盘+鼠标
You use bit masks to test which modifiers have been set. In the original API, two of the button masks equal two keyboard modifier masks, namely
if ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)
. . . // code for right click