所有的Swing组件必须由时间调度线程(event dispatch thread)进行配置,线程将鼠标点击和键盘敲击控制转移到用户接口组件。下面的代码片段是事件调度线程中的执行代码:
EventQueue.invokeLater(new Runnable(){
public void run(){
statements
}
});
注释:主线程中完成Swing程序初始化无法保证这种方式的安全性,虽然发生错误的概率非常小。
根据屏幕分辨率重置框架的大小
调用Toolkit类的静态方法getDefaultToolkit得到一个Toolkit对象(Toolkit类包含很多与本地窗口系统打交道的方法)。然后,调用getScreenSize方法,这个方法以Dimension对象的形势返回屏幕的大小。Dimension对象同时用公有实例变量width和height保存着屏幕的宽度和高度。下面是相关代码:
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
下面,将框架大小设定为上面取值的50%,然后告知窗口系统定位框架
setSize(screenWidth/2,screenHeight/2);
setLocationByPlatform(true);
绘制几何图形
import java.awt.EventQueue;
import javax.swing.JFrame;
public class DrawTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class DrawFrame extends JFrame {
public DrawFrame() {
setTitle("DrawTest");
// setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int screenWidth =screenSize.width;
int screenHeight = screenSize.height;
setSize(screenWidth/2, screenHeight/2);
setLocationByPlatform(true);
component = new DrawComponent();
add(component);
}
private Component component;
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
public class DrawComponent extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//根据屏幕分辨率设置框架大小
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
//根据屏幕分辨率设置组件位置
double leftX = screenWidth / 4 - 100;
double topY = screenHeight / 4 - 75;
double width = 200;
double height = 150;
//画一个矩形
Rectangle2D rec = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rec);
//画一个rec矩形的内切椭圆
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rec);
g2.draw(ellipse);
//画rec矩形的对角线
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
//画一个以rec矩形中心为圆心的圆
double centerX = rec.getCenterX();
double centerY = rec.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
}
以上内容根据《java核心技术卷I:基础知识》编写