我在为学校做项目时遇到了一些问题。 JDialog渲染速度非常慢。让我告诉你。
这是GUI:
当我点击“提前时间”时,打开JDialog大约需要3秒钟。当它打开时,我得到这个(这很好):
但是当我拖动JDialog时,我得到了这个(这不行):
关闭JDialog也需要很长时间。它关闭了,但你仍然可以看到它:
这是我认为问题所在的代码片段,它是菜单栏的代码:
private JMenu editMenu()
{
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
JMenuItem advanceTimeMenuItem = new JMenuItem("Advance time");
advanceTimeMenuItem.setMnemonic(KeyEvent.VK_A);
advanceTimeMenuItem.setToolTipText("Advance the internal clock");
advanceTimeMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
//We first create panel to add to the dialog.
JPanel panel = new JPanel();
//Calendar
AdvanceTimePanel calendar = new AdvanceTimePanel(internalClockController);
//Button that will be used to confirm the system time change.
JButton btnSave = new JButton("Save");
//Add actionlistener to the save button
btnSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e)
{
Date selectedDate = calendar.getDate();
try
{
internalClockController.updateDateTime(selectedDate);
} catch (InvalidInternalClockException e1)
{
System.out.println("InvalidInternalClockException: " + e1.getMessage());
}
}
});
//Add the components to the panel.
panel.add(btnSave);
//This is the calendar added to the panel.
panel.add(calendar);
//Create the dialog and add the panel to it.
JDialog jDialog = new JDialog();
jDialog.add(panel);
jDialog.setBounds(100, 100, 400, 200);
jDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jDialog.setVisible(true);
}
});
editMenu.add(advanceTimeMenuItem);
有人知道如何加快速度吗? 提前谢谢。
答案 0 :(得分:1)
事件在一个线程上处理。 (还重绘事件。)保留应用程序
响应,稍后使用invokeLater
执行更长时间的操作,如下所示:
@Override
public void actionPerformed(ActionEvent event)
{
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
... // All code here
}
});
}
这很罗嗦; Java 8允许:
advanceTimeMenuItem.addActionListener(
(event) -> {
EventQueue.invokeLater(
() -> {
... // All code
});
});