paintcomponent在正确的时间不被调用
-
10-10-2019 - |
题
我正在尝试编写一个这样的应用程序:
- 显示对话框
- 当用户单击确定时,关闭对话框,转到主应用
这是相关代码段:
public class Owari extends JPanel implements ActionListener, MouseListener, Runnable {
// FIELDS
JFrame frame;
JTextField IP;
String IPAddress;
static final int SERVER_MODE = 0;
static final int CLIENT_MODE = 1;
int mode;
OwariBoard board;
public static void main( String[] args ) {
SwingUtilities.invokeLater( new Owari() );
}
Owari() {
setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
board = new OwariBoard();
}
void main() {
this.addMouseListener( this );
frame.dispose();
frame = new JFrame( "Owari" );
frame.setContentPane( this );
frame.pack();
frame.setVisible(true);
if ( mode == SERVER_MODE ) {
server();
}
if ( mode == CLIENT_MODE ) {
client();
}
}
public void run() {
frame = new JFrame( "Owari" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel init = new JPanel( new GridBagLayout() );
frame.setContentPane( init );
add some components to the init panel including a button with
this as its actionListener and OK as its command.
frame.pack();
frame.setVisible( true );
}
public void actionPerformed( ActionEvent e ) {
if ( e.getActionCommand().equals( "Client" ) ) {
mode = CLIENT_MODE;
IP.setVisible( true );
}
else if ( e.getActionCommand().equals( "Server" ) ) {
mode = SERVER_MODE;
IP.setVisible( false );
}
else {
IPAddress = IP.getText();
main();
}
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
System.out.println( "painting" );
do some paintin
}
void server() {
frame.setTitle( "Owari Server" );
try {
server = new ServerSocket( 666 );
socket = server.accept();
initIO();
} catch ( IOException e ) {}
yourTurn = true;
System.out.println( "Got to end of server()" ); // At this point, the window
DOES get painted
发生的事情是以下内容:
最初的对话框显示:
我单击“确定”按钮。主窗口调整到主应用的首选尺寸,但不会涂漆,它只是透明的(在此处以此页面作为背景显示,heh):
http://imgur.com/6ssij.jpg
我可以说没有称呼PaintComponent方法,因为“绘画”未印刷到控制台上。但是,“在程序中达到这一点”确实被打印了,因此该程序没有悬挂,只是没有调用PaintComponent。然后,当我启动客户端并连接时,该应用程序最终被绘制,“绘画”和“ Got a Got a”将被打印到控制台上。同样在该应用程序中,延迟到RepaInt()的呼叫(即在程序中实际上是在稍后调用),而不是拨打RepAlt()的调用)。
我还尝试使用沿着线条的插入来替换初始对话框
public void main
frame.getRootPane.removeAll()
frame.setContentPane(this)
frame.getRootPane().revalidate()
frame.pack()
完全相同的结果。
当我想要的时候,TL; dr PaintComponent不会被调用,该怎么办?
碰撞以获取更多信息:呼叫repaint()是在致电sever.accept()之前完成的。 前 悬挂在server.accept()调用?
解决方案
OpenAsocketAndWaitForacLient
在事件调度线程中,您的代码正在执行,因此阻止插座阻止GUI自身重新粉刷。
您需要为套接字使用单独的线程。阅读《摇摆教程》的部分 并发 用于解释和解决方案。
其他提示
您的代码似乎可以正常工作,也许您应该尝试在调整此帧大小后尝试调用框架的重新涂片()。
安海因
不隶属于 StackOverflow