我正在尝试编写一个类似这样的应用程序:
- 显示一个对话框
- 当用户单击确定时,关闭对话框,转到主应用程序
以下是相关的代码片段:
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
发生的情况如下:
显示初始对话框:
我单击“确定”按钮。主窗口被调整到主应用程序的首选大小,但它没有被绘制,它只是透明的(这里以这个页面作为背景显示,呵呵):http:
//imgur.com/6Ssij.jpg
我可以说paintComponent 方法没有被调用,因为“绘画”没有打印到控制台。但是,“程序中的这一点”确实被打印出来了,所以程序没有挂起,它只是没有调用paintComponent。然后,当我启动客户端并连接时,应用程序最终被绘制,并且“绘制”和“获得客户端”被打印到控制台。稍后在应用程序中,对 repaint() 的调用也会延迟(即,在程序中实际调用paintComponent 的时间比调用 repaint() 的时间要晚)。
我还尝试使用以下内容替换初始对话框
public void main
frame.getRootPane.removeAll()
frame.setContentPane(this)
frame.getRootPane().revalidate()
frame.pack()
结果完全相同。
tl;当我想要它时没有调用dr paintcomponent,怎么办?
获取更多信息:对 repaint() 的调用是在调用 sever.accept() 之前完成的 那么为什么在挂起 server.accept() 调用之前它不 repaint() 呢?