直接绘制到JFrame
. 更好的方法是覆盖paintComponent()
aJPanel
并将其添加JPanel
到JFrame
:
测试.java:
public class Test extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test().createUI();
}
});
}
void createUI() {
setSize(500,500);
getContentPane().add(new MyPanel());
setVisible(true);
}
}
MyPanel.java:
class MyPanel extends JPanel {
@override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//paint what you want here
g.drawString("Hello world",250,250);
}
}
但是,如果必须,我建议添加一个 Window并在它成为焦点时FocusListener
调用实例:http: //docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.htmlrepaint()
JFrame
通过方法windowGainedFocus(WindowEvent e)
或windowStateChanged(WindowEvent e)
或windowActivated(WindowEvent e)
调用repaint()
这些方法之一然后将调用该paint()
方法。