Swing 是一个单线程框架。也就是说,它使用单个线程将它的所有事件分派给它的所有相关方。
如果有任何东西阻塞了这个线程(例如 infinate while-loop
),那么线程就无法处理任何进入应用程序的新事件,包括重绘请求。这将使您的应用程序看起来像挂起(在您的情况下,它实际上已经挂起)。
查看Swing 中的并发以获取更多详细信息。
以下示例允许用户在窗口表面单击/拖动,它将呈现一个表示拖动过程的矩形。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawRectangle {
public static void main(String[] args) {
new DrawRectangle();
}
public DrawRectangle() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Rectangle dragRect;
public TestPane() {
MouseHandler handler = new MouseHandler();
addMouseListener(handler);
addMouseMotionListener(handler);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (dragRect != null) {
g2d.setColor(Color.DARK_GRAY);
g2d.draw(dragRect);
}
g2d.dispose();
}
public class MouseHandler extends MouseAdapter {
private Point clicked;
@Override
public void mousePressed(MouseEvent e) {
clicked = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
int x = Math.min(p.x, clicked.x);
int y = Math.min(p.y, clicked.y);
int width = Math.max(p.x, clicked.x) - x;
int height = Math.max(p.y, clicked.y) - y;
dragRect = new Rectangle(x, y, width, height);
repaint();
}
}
}
}