Java:使用按钮

时间:2018-01-16 12:12:25

标签: java nimbus

我正试图通过按下按钮使用Nimbus Look and Feel更改面板背景。当我第一次按下按钮时,面板颜色会发生变化,但是它会停止工作并需要重新启动才能使其再次工作。

public class JavaApplication30 extends  JPanel
{
    JFrame frame = new JFrame("Button Demo");

    public JavaApplication30() 
    {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300,300));
        frame.add(this);

        JButton b1 = new JButton("BLACK");
        b1.setPreferredSize(new Dimension(150,50));
        b1.setFocusPainted(false); // get rid of border around text
        add(b1);
        b1.addActionListener((java.awt.event.ActionEvent evt) -> 
        {
            try
                {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");


                    UIManager.getLookAndFeelDefaults().put("Panel.background", Color.BLACK);

                    SwingUtilities.updateComponentTreeUI(frame);
                    this.revalidate();
                    this.repaint();
                    frame.invalidate();
                    frame.validate();
                    frame.repaint();
                    frame.pack();
                }
                catch ( ClassNotFoundException | 
                        InstantiationException | 
                        IllegalAccessException | 
                        UnsupportedLookAndFeelException ex) 
                {

                }
        });

        JButton b2 = new JButton("RED");
        b2.setPreferredSize(new Dimension(150,50));
        b2.setFocusPainted(false); // get rid of border around text
        add(b2);

        b2.addActionListener((java.awt.event.ActionEvent evt) -> 
        {
            try
                {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");


                    UIManager.getLookAndFeelDefaults().put("Panel.background", Color.RED);

                    SwingUtilities.updateComponentTreeUI(frame);
                    this.revalidate();
                    this.repaint();
                    frame.invalidate();
                    frame.validate();
                    frame.repaint();
                    frame.pack();
                }
                catch ( ClassNotFoundException | 
                        InstantiationException | 
                        IllegalAccessException | 
                        UnsupportedLookAndFeelException ex) 
                {

                }
        });

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }


    public static void main(String[] args) 
    {
       new JavaApplication30();
   }

}

上述代码中是否有罪魁祸首?我非常感谢别人的帮助!

0 个答案:

没有答案