Glasspane不工作,java
我一直在开发一个小型java应用程序,我想在应用程序根窗格的玻璃窗格上添加一个等待的图形,下面是类:Glasspane不工作,java,java,glasspane,Java,Glasspane,我一直在开发一个小型java应用程序,我想在应用程序根窗格的玻璃窗格上添加一个等待的图形,下面是类: public class WaitPanel extends JPanel { public WaitPanel() { this.setLayout(new BorderLayout()); JLabel label = new JLabel(new ImageIcon("spin.gif")); this.setLayout(new BorderLayout());
public class WaitPanel extends JPanel {
public WaitPanel() {
this.setLayout(new BorderLayout());
JLabel label = new JLabel(new ImageIcon("spin.gif"));
this.setLayout(new BorderLayout());
this.add(label, BorderLayout.CENTER);
this.setOpaque(false);
this.setLayout(new GridBagLayout());
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
me.consume();
Toolkit.getDefaultToolkit().beep();
}
});
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 0, 140));
g.fillRect(0, 0, getWidth(), getHeight());
}}
主要课程包括:
public class NewJFrame extends JFrame {
public NewJFrame() {
JButton button =new JButton("Click");
getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
}
});
}
但当我将按钮操作更改为:
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
Scanner sc=new Scanner(System.in);
String s=sc.next();
getRootPane().getGlassPane().setVisible(false);
它不起作用。您的问题(其中之一)是代码使用基于System.in的扫描仪冻结Swing事件线程,从而阻止GUI更新其图形,包括其玻璃窗格。解决方案——不要这样做。如果要阻止GUI或暂停它,请使用Swing计时器或JOptionPane
例如,你可以改变
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
Scanner sc=new Scanner(System.in);
String s=sc.next();
getRootPane().getGlassPane().setVisible(false);
对这样的事情:
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
int delay = 4 * 1000; // 4 second delay
new javax.swing.Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getRootPane().getGlassPane().setVisible(false);
((javax.swing.Timer) e).stop();
}
}).start();
“它不起作用。”这是不够的努力。请确切地告诉我们什么不起作用,并解释您到目前为止为解决问题所做的工作。首先,图形会出现,但在第二种情况下,当我单击它时,它不会出现,并且按钮仍然被阻止。切勿将控制台程序(即使用System.in的扫描仪)与GUI混合。这将使您的GUI陷入线程地狱。不要这样做。在执行自定义绘制之前,请确保您正在调用
super.paintComponent
。请参阅编辑以回答问题。