Изменение внешнего вида Java без закрытия окна

Я хочу знать, как изменить внешний вид моих java-приложений, не заставляя пользователя покидать его или даже закрывать окно. Я знаю, что это возможно, поскольку я видел, как это делается. Я попытался реализовать его, код показан ниже, но он работает только тогда, когда я вызываю свой метод setLookAndFeel() ДО отображения окна.

Вопрос


Что я делаю неправильно?

Код


package lookandfeeltester;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainJFrame extends javax.swing.JFrame
{
  public MainJFrame()
  {
    setDefaultLookAndFeelDecorated(true);
    initComponents();
  }

  @SuppressWarnings("unchecked")
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    buttonGroup = new javax.swing.ButtonGroup();
    metalRadioButton = new javax.swing.JRadioButton();
    nimbusRadioButton = new javax.swing.JRadioButton();
    motifRadioButton = new javax.swing.JRadioButton();
    windowsRadioButton = new javax.swing.JRadioButton();
    windowsClassicRadioButton = new javax.swing.JRadioButton();
    menuBar = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    exitMenuItem = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new java.awt.GridBagLayout());

    buttonGroup.add(metalRadioButton);
    metalRadioButton.setText("Metal");
    metalRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        metalRadioButtonActionPerformed(evt);
      }
    });
    getContentPane().add(metalRadioButton, new java.awt.GridBagConstraints());

    buttonGroup.add(nimbusRadioButton);
    nimbusRadioButton.setSelected(true);
    nimbusRadioButton.setText("Nimbus");
    nimbusRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        nimbusRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    getContentPane().add(nimbusRadioButton, gridBagConstraints);

    buttonGroup.add(motifRadioButton);
    motifRadioButton.setText("CDE/Motif");
    motifRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        motifRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    getContentPane().add(motifRadioButton, gridBagConstraints);

    buttonGroup.add(windowsRadioButton);
    windowsRadioButton.setText("Windows");
    windowsRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        windowsRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    getContentPane().add(windowsRadioButton, gridBagConstraints);

    buttonGroup.add(windowsClassicRadioButton);
    windowsClassicRadioButton.setText("Windows Classic");
    windowsClassicRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        windowsClassicRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    getContentPane().add(windowsClassicRadioButton, gridBagConstraints);

    fileMenu.setText("File");

    exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
    exitMenuItem.setText("Exit");
    exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        exitMenuItemActionPerformed(evt);
      }
    });
    fileMenu.add(exitMenuItem);

    menuBar.add(fileMenu);

    setJMenuBar(menuBar);

    pack();
  }

    private void metalRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    }

    private void nimbusRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      setLookAndFeel(com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel.class.getCanonicalName());
    }

    private void motifRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      setLookAndFeel(com.sun.java.swing.plaf.motif.MotifLookAndFeel.class.getCanonicalName());
    }

    private void windowsRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsLookAndFeel.class.getCanonicalName());
    }

    private void windowsClassicRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel.class.getCanonicalName());
    }

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt)
    {
      System.exit(0);
    }

  public static void main(String args[])
  {
    java.awt.EventQueue.invokeLater(new Runnable() 
    {
      public void run()
      {
        new MainJFrame().setVisible(true);
      }
    });
  }

  private void setLookAndFeel(String laf)
  {
    try
    {
      System.out.println("Setting LAF to " + laf + "...");
      UIManager.setLookAndFeel(laf);
    }
    catch (ClassNotFoundException ex){}
    catch (InstantiationException ex){}
    catch (IllegalAccessException ex){}
    catch (UnsupportedLookAndFeelException ex){}
  }

  private javax.swing.ButtonGroup buttonGroup;
  private javax.swing.JMenuItem exitMenuItem;
  private javax.swing.JMenu fileMenu;
  private javax.swing.JMenuBar menuBar;
  private javax.swing.JRadioButton metalRadioButton;
  private javax.swing.JRadioButton motifRadioButton;
  private javax.swing.JRadioButton nimbusRadioButton;
  private javax.swing.JRadioButton windowsClassicRadioButton;
  private javax.swing.JRadioButton windowsRadioButton;
}

Отвечать


package lookandfeeltester;

import java.awt.Color;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainJFrame extends javax.swing.JFrame
{
  public MainJFrame()
  {
    setDefaultLookAndFeelDecorated(true);
    initComponents();

  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    buttonGroup = new javax.swing.ButtonGroup();
    jPanel1 = new javax.swing.JPanel();
    metalRadioButton = new javax.swing.JRadioButton();
    nimbusRadioButton = new javax.swing.JRadioButton();
    motifRadioButton = new javax.swing.JRadioButton();
    windowsRadioButton = new javax.swing.JRadioButton();
    windowsClassicRadioButton = new javax.swing.JRadioButton();
    jButton1 = new javax.swing.JButton();
    menuBar = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    exitMenuItem = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setLayout(new java.awt.GridBagLayout());

    buttonGroup.add(metalRadioButton);
    metalRadioButton.setSelected(true);
    metalRadioButton.setText("Metal");
    metalRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        metalRadioButtonActionPerformed(evt);
      }
    });
    jPanel1.add(metalRadioButton, new java.awt.GridBagConstraints());

    buttonGroup.add(nimbusRadioButton);
    nimbusRadioButton.setText("Nimbus");
    nimbusRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        nimbusRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    jPanel1.add(nimbusRadioButton, gridBagConstraints);

    buttonGroup.add(motifRadioButton);
    motifRadioButton.setText("CDE/Motif");
    motifRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        motifRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    jPanel1.add(motifRadioButton, gridBagConstraints);

    buttonGroup.add(windowsRadioButton);
    windowsRadioButton.setText("Windows");
    windowsRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        windowsRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    jPanel1.add(windowsRadioButton, gridBagConstraints);

    buttonGroup.add(windowsClassicRadioButton);
    windowsClassicRadioButton.setText("Windows Classic");
    windowsClassicRadioButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        windowsClassicRadioButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    jPanel1.add(windowsClassicRadioButton, gridBagConstraints);

    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new java.awt.GridBagConstraints());

    getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

    fileMenu.setText("File");

    exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
    exitMenuItem.setText("Exit");
    exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        exitMenuItemActionPerformed(evt);
      }
    });
    fileMenu.add(exitMenuItem);

    menuBar.add(fileMenu);

    setJMenuBar(menuBar);

    pack();
  }// </editor-fold>

    private void metalRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      new LAFActionListener(new javax.swing.plaf.metal.MetalLookAndFeel()).actionPerformed(evt);
    }

    private void nimbusRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      new LAFActionListener(new com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel()).actionPerformed(evt);
    }

    private void motifRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      new LAFActionListener(new com.sun.java.swing.plaf.motif.MotifLookAndFeel()).actionPerformed(evt);
    }

    private void windowsRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
            new LAFActionListener(new com.sun.java.swing.plaf.windows.WindowsLookAndFeel()).actionPerformed(evt);
    }

    private void windowsClassicRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
      new LAFActionListener(new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel()).actionPerformed(evt);
    }

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt)
    {
      System.exit(0);
    }

  public static void main(String args[])
  {
    java.awt.EventQueue.invokeLater(new Runnable() 

    {
      public void run()
      {
        new MainJFrame().setVisible(true);
      }
    });
  }

  private void setLookAndFeel(LookAndFeel laf)
  {
    try
    {
      System.out.println("Setting LAF to " + laf + "...");
      UIManager.setLookAndFeel(laf);
    }
    catch (UnsupportedLookAndFeelException ex)
    {
    }
  }
  // Variables declaration - do not modify
  private javax.swing.ButtonGroup buttonGroup;
  private javax.swing.JMenuItem exitMenuItem;
  private javax.swing.JMenu fileMenu;
  private javax.swing.JButton jButton1;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JMenuBar menuBar;
  private javax.swing.JRadioButton metalRadioButton;
  private javax.swing.JRadioButton motifRadioButton;
  private javax.swing.JRadioButton nimbusRadioButton;
  private javax.swing.JRadioButton windowsClassicRadioButton;
  private javax.swing.JRadioButton windowsRadioButton;
  // End of variables declaration

  public class LAFActionListener implements java.awt.event.ActionListener
  {
    LookAndFeel laf;

    public LAFActionListener(LookAndFeel l)
    {
      this.laf = l;
    }

    public void actionPerformed(java.awt.event.ActionEvent e)
    {
      try
      {
        UIManager.setLookAndFeel(this.laf);
        javax.swing.SwingUtilities.updateComponentTreeUI(MainJFrame.this);
        pack();
      }
      catch (Exception ex)
      {
        ((java.awt.Component) e.getSource()).setEnabled(false);
        ((java.awt.Component) e.getSource()).setBackground(java.awt.Color.RED);
      }
    }
  }
}

person Ky Leggiero    schedule 28.02.2011    source источник


Ответы (2)


После UIManager.setLookAndFeel(laf); следует позвонить:

SwingUtilities.updateComponentTreeUI( this );
person Sergii Pozharov    schedule 28.02.2011

Похоже, вы не перерисовываете после того, как изменили внешний вид.

person corsiKa    schedule 28.02.2011
comment
Итак, ему нужно вызвать repaint() на самом JFrame? Я не очень хорошо знаком с графическими интерфейсами Swing/AWT, поэтому я не уверен, перерисовывает ли это всех дочерних элементов или нет. - person Powerlord; 01.03.2011