Programowanie obiektowe - JAVA
Informacje ogólne > Laboratorium 3 > Ćwiczenie 3

Ćwiczenie 3

Dodać do programu 3 komponenty klasy JRadioButton w taki sposób, aby pozwalały one na dynamiczną zmianę stylu (LookAndFeel) okna.

Można wykorzystać fragmenty z poniższego przykładu:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Ch06_04 extends JFrame {

   JRadioButton b1 = new JRadioButton("Metal"), b2 = new JRadioButton("Motif"), b3 = new JRadioButton("Windows");

  public Ch06_04() {
     
super("Aplikacja Swing 2");
      Container contentPane = getContentPane();
      contentPane.add(
new Panel(), BorderLayout.CENTER);
   }

   public static void main(String args[]) {
       
final JFrame f = new Ch06_04();
        f.setBounds(100, 100, 300, 300);
        f.setVisible(
true);
        f.setDefaultCloseOperation(
DISPOSE_ON_CLOSE);
        f.addWindowListener(
new WindowAdapter() {
                        
public void windowClosing(WindowEvent e) {
                                     System.exit(0);
                         }
         });
    }

class Panel extends JPanel implements ActionListener{

   public Panel()  {
      add(
new JButton("JButton"));
      add(
new JTextField("JTextField"));
      add(
new JCheckBox("JCheckBox"));
      add(
new JRadioButton("JRadioButton"));
      add(
new JLabel("JLabel"));
      add(
new JList(new String[] {"JList, poz. 1", "JList, poz. 2", "JList, poz. 3"}));
      add(
new JScrollBar(SwingConstants.HORIZONTAL));
      ButtonGroup group =
new ButtonGroup();
      group.add(
b1);
      group.add(
b2);
      group.add(
b3);
     
b1.addActionListener(this);
     
b2.addActionListener(this);
     
b3.addActionListener(this);
      add(
b1);
      add(
b2);
      add(
b3);
  }

  public void actionPerformed(ActionEvent e) {
    JRadioButton src = (JRadioButton)e.getSource();
    
try {
       
if((JRadioButton)e.getSource() == b1) UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
      
else if((JRadioButton)e.getSource() == b2)UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
       
else if((JRadioButton)e.getSource() == b3)UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
     } 
catch(Exception ex) {}

     SwingUtilities.updateComponentTreeUI(getContentPane());
    }
  }
}