Java Swing How to - Share Models between Buttons








Question

We would like to know how to share Models between Buttons.

Answer

//  w w  w  .  j  av  a  2  s . c  o m
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

  public static void main(String args[]) {
    JFrame f = new JFrame();
    JButton jb1 = new JButton("Hello");
    ButtonModel bm = jb1.getModel();
    JButton jb2 = new JButton("World");
    jb2.setModel(bm);
    Container c = f.getContentPane();
    c.add(jb1, BorderLayout.NORTH);
    c.add(jb2, BorderLayout.SOUTH);
    jb1.addActionListener(new MessageActionListener("Selected One"));
    jb2.addActionListener(new MessageActionListener("Selected Two"));
    f.pack();
    f.show();
  }
}

class MessageActionListener implements ActionListener {
  String message;

  public MessageActionListener(String msg) {
    message = msg;
  }

  public void actionPerformed(ActionEvent e) {
    System.out.println(message);
  }
}