I can't seem to figure how to get this to work. Many times I have created a application using a JFrame and have a need to dynamically add/remove/resize components in that JFrame. Sometimes the total size of the controls is now smaller than the original and sometimes they are larger (either by adding or deleting a component or by resizing a component.)
What I want to do is cause the application to resize itself to fit the new configuration of its components. I basically want the application to "re"-pack() itself. But no matter what I try, I can't get it to work.
I have included an example. I found code to display mpg on the net and wanted to modify the code to display the mpg in a JPanel. The JPanel is added as an component on the main JFrame. Once the mpg is loaded its window is resized to preferred size of the video it is attempting to display. What I want to happen is to have the new size of the JPanel to communicate this to the main JFrame and have the JFrame to resize itself to fit the new dimensions.
Any help is greatly appreciated.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.net.URL;
import java.net.MalformedURLException;
public class MediaTemplate extends JFrame implements ActionListener {
private final static long serialVersionUID = 1L;
private static JFrame jFrame;
private JButton jbNew;
private JButton jbOpen;
private JButton jbSave;
private JButton jbCopy;
private JButton jbCut;
private JButton jbPaste;
private JButton jbQuestion;
private JToolBar jtbToolBar;
private static JMenu menuFile;
private static JMenu menuEdit;
private static JMenu menuHelp;
private static JMenuItem menuitemNewFile;
private static JMenuItem menuitemOpenFile;
private static JMenuItem menuitemSaveFile;
private static JMenuItem menuitemExit;
private static JMenuItem menuitemCut;
private static JMenuItem menuitemCopy;
private static JMenuItem menuitemPaste;
private static JMenuItem menuitemAbout;
MyItemActionListener myItemActionListener = new MyItemActionListener();
private static MediaTemplateListResourceBundle listResourceBundle;
MediaPanel mediaPanel;
public void init () {
new MediaTemplate();
}
public static void main (String args[]) {
new MediaTemplate();
}
public MediaTemplate() {
setTitle("MediaTemplate");
GridBagLayout gridBagLayout = new GridBagLayout ();
GridBagConstraints gridBagConstraints = new GridBagConstraints ();
setLayout(gridBagLayout);
listResourceBundle = new MediaTemplateListResourceBundle();
// Create menu bar
createMenuBar();
// Create tool bar
jtbToolBar = createToolBar();
addWindowListener (new windowListener());
jFrame = this;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagLayout.setConstraints (jtbToolBar, gridBagConstraints);
add(jtbToolBar);
try {
mediaPanel = new MediaPanel();
gridBagConstraints.gridy = 1;
gridBagLayout.setConstraints (mediaPanel, gridBagConstraints);
add(mediaPanel);
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
pack();
setVisible(true);
}
public JToolBar createToolBar() {
JToolBar jtb = new JToolBar();
jbNew = new JButton(new ImageIcon("new.gif"));
jbOpen = new JButton(new ImageIcon("open.gif"));
jbSave = new JButton(new ImageIcon("save.gif"));
jbCut = new JButton(new ImageIcon("cut.gif"));
jbCopy = new JButton(new ImageIcon("copy.gif"));
jbPaste = new JButton(new ImageIcon("paste.gif"));
jbQuestion = new JButton(new ImageIcon("question.gif"));
jbNew.setActionCommand("new");
jbOpen.setActionCommand("open");
jbSave.setActionCommand("save");
jbCut.setActionCommand("cut");
jbCopy.setActionCommand("copy");
jbPaste.setActionCommand("paste");
jbQuestion.setActionCommand("question");
jbNew.addActionListener(this);
jbOpen.addActionListener(this);
jbSave.addActionListener(this);
jbCut.addActionListener(this);
jbCopy.addActionListener(this);
jbPaste.addActionListener(this);
jbQuestion.addActionListener(this);
jbNew.setMargin(new Insets(0, 0, 0, 0));
jbOpen.setMargin(new Insets(0, 0, 0, 0));
jbSave.setMargin(new Insets(0, 0, 0, 0));
jbCut.setMargin(new Insets(0, 0, 0, 0));
jbCopy.setMargin(new Insets(0, 0, 0, 0));
jbPaste.setMargin(new Insets(0, 0, 0, 0));
jbQuestion.setMargin(new Insets(0, 0, 0, 0));
jtb.add(jbNew);
jtb.add(jbOpen);
jtb.add(jbSave);
jtb.addSeparator();
jtb.add(jbCut);
jtb.add(jbCopy);
jtb.add(jbPaste);
jtb.addSeparator();
jtb.add(jbQuestion);
return jtb;
}
protected void createMenuBar () {
menuListener ml = new menuListener ();
JMenuBar menuBar = new JMenuBar();
// Build the File Menu
menuFile = new JMenu(listResourceBundle.getString("fileMenuText"));
menuitemNewFile = new JMenuItem(listResourceBundle.getString("newFileMenuText"));
menuitemNewFile.addActionListener(ml);
menuFile.add(menuitemNewFile);
menuitemOpenFile = new JMenuItem(listResourceBundle.getString("openFileMenuText"));
menuitemOpenFile.addActionListener(ml);
menuFile.add(menuitemOpenFile);
menuitemSaveFile = new JMenuItem(listResourceBundle.getString("saveFileMenuText"));
menuitemSaveFile.addActionListener(ml);
menuFile.add(menuitemSaveFile);
menuFile.addSeparator();
menuitemExit = new JMenuItem(listResourceBundle.getString("exitMenuText"));
menuitemExit.addActionListener(ml);
menuFile.add(menuitemExit);
// Build the Edit Menu
menuEdit = new JMenu(listResourceBundle.getString("editMenuText"));
menuitemCut = new JMenuItem(listResourceBundle.getString("cutMenuText"));
menuitemCut.addActionListener(ml);
menuEdit.add(menuitemCut);
menuitemCopy = new JMenuItem(listResourceBundle.getString("copyMenuText"));
menuitemCopy.addActionListener(ml);
menuEdit.add(menuitemCopy);
menuitemPaste = new JMenuItem(listResourceBundle.getString("pasteMenuText"));
menuitemPaste.addActionListener(ml);
menuEdit.add(menuitemPaste);
// Build the Help Menu
JMenu menuHelp = new JMenu(listResourceBundle.getString("helpMenuText"));
menuitemAbout = new JMenuItem(listResourceBundle.getString("aboutMenuText"));
menuitemAbout.addActionListener(ml);
menuHelp.add(menuitemAbout);
menuBar.add(menuFile);
menuBar.add(menuEdit);
menuBar.add(menuHelp);
setJMenuBar(menuBar);
}
class windowListener extends java.awt.event.WindowAdapter {
public void windowClosing (WindowEvent evt) {
exit ();
}
}
private void exit () {
setVisible (false);
dispose ();
System.exit (0);
}
class menuListener implements ActionListener {
public void actionPerformed (ActionEvent evt) {
Object src = evt.getSource ();
if (src == menuitemAbout) {
JOptionPane.showMessageDialog (JOptionPane.getRootFrame (),
listResourceBundle.getString("aboutText"),
listResourceBundle.getString("aboutTitleText"),
JOptionPane.INFORMATION_MESSAGE);
} else if (src == menuitemOpenFile) {
} else if (src == menuitemExit) {
exit();
}
}
}
public void actionPerformed(ActionEvent e) {
if ("stop".equals(e.getActionCommand())) {
mediaPanel.stop();
} else if ("new".equals(e.getActionCommand())) {
} else if ("open".equals(e.getActionCommand())) {
FileDialog fd = new FileDialog(new Frame());
fd.setVisible(true);
String fullpath = fd.getDirectory() + fd.getFile();
fd.dispose();
try {
mediaPanel.removePreviousPlayer();
mediaPanel.setModel(new URL("file:/" + fullpath));
mediaPanel.start();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
} else if ("save".equals(e.getActionCommand())) {
} else if ("cut".equals(e.getActionCommand())) {
} else if ("copy".equals(e.getActionCommand())) {
} else if ("paste".equals(e.getActionCommand())) {
} else if ("question".equals(e.getActionCommand())) {
} else if ("exit".equals(e.getActionCommand())) {
exit();
}
}
class MyItemActionListener implements ItemListener {
public void itemStateChanged(ItemEvent itemEvent) {
Object obj = itemEvent.getSource();
}
}
}
Here is the JPanel code
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import javax.media.*;
import javax.swing.*;
import javax.swing.JPanel;
import javax.media.bean.playerbean.MediaPlayer;
import javax.media.protocol.DataSource;
public class MediaPanel extends JPanel implements ControllerListener {
private URL mediaURL;
private Player mediaPlayer;
private Component visualComponent = null;
private Component controlComponent = null;
private Component progressBar = null;
private boolean firstTime = true;
private long CachingSize = 0L;
private int controlPanelHeight = 0;
private int videoWidth = 0;
private int videoHeight = 0;
public MediaPanel() {
setLayout(new BorderLayout()); // use a BorderLayout
// Use lightweight components for Swing compatibility
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
this.mediaURL = null;
}
public MediaPanel(URL mediaURL) {
setLayout(new BorderLayout()); // use a BorderLayout
// Use lightweight components for Swing compatibility
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
this.mediaURL = mediaURL;
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.deallocate();
}
}
public void start() {
try {
mediaPlayer.start(); // start playing the media clip
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
public void setModel(URL mediaURL) {
this.mediaURL = mediaURL;
try {
if (mediaPlayer == null) {
mediaPlayer = Manager.createPlayer(this.mediaURL);
mediaPlayer.addControllerListener(this);
} else {
mediaPlayer = Manager.createPlayer(this.mediaURL);
mediaPlayer.addControllerListener(this);
}
} catch (NoPlayerException noPlayerException) {
System.err.println("No media player found");
} catch (IOException iOException) {
System.err.println("Error reading from the source");
}
}
public void removePreviousPlayer() {
if (mediaPlayer == null) {
return;
}
mediaPlayer.close();
}
/**
* This controllerUpdate function must be defined in order to
* implement a ControllerListener interface. This
* function will be called whenever there is a media event
*/
public synchronized void controllerUpdate(ControllerEvent event) {
// If we're getting messages from a dead player,
// just leave
if (mediaPlayer == null) {
return;
}
// When the player is Realized, get the visual
// and control components and add them to the Applet
if (event instanceof RealizeCompleteEvent) {
if (progressBar != null) {
remove(progressBar);
progressBar = null;
}
int width = 1024;
int height = 0;
if (controlComponent == null) {
if ((controlComponent = mediaPlayer.getControlPanelComponent()) != null) {
controlPanelHeight = controlComponent.getPreferredSize().height;
add(controlComponent, BorderLayout.SOUTH);
height += controlPanelHeight;
}
}
if (visualComponent == null) {
if ((visualComponent = mediaPlayer.getVisualComponent())!= null) {
add(visualComponent, BorderLayout.NORTH);
Dimension videoSize = visualComponent.getPreferredSize();
videoWidth = videoSize.width;
videoHeight = videoSize.height;
width = videoWidth;
height += videoHeight;
visualComponent.setSize(videoWidth, videoHeight);
}
}
setSize(width, height);
if (controlComponent != null) {
controlComponent.setBounds(0,
videoHeight,
width,
controlPanelHeight);
controlComponent.invalidate();
}
} else if (event instanceof CachingControlEvent) {
if (mediaPlayer.getState() > Controller.Realizing) {
return;
}
// Put a progress bar up when downloading starts,
// take it down when downloading ends.
CachingControlEvent e = (CachingControlEvent) event;
CachingControl cc = e.getCachingControl();
// Add the bar if not already there ...
if (progressBar == null) {
if ((progressBar = cc.getControlComponent()) != null) {
System.out.println("adding progressBar...");
add(progressBar);
setSize(progressBar.getPreferredSize());
validate();
}
}
} else if (event instanceof EndOfMediaEvent) {
// We've reached the end of the media; rewind and
// start over
mediaPlayer.setMediaTime(new Time(0));
mediaPlayer.start();
} else if (event instanceof ControllerErrorEvent) {
// Tell TypicalPlayerApplet.start() to call it a day
mediaPlayer = null;
Fatal(((ControllerErrorEvent)event).getMessage());
} else if (event instanceof ControllerClosedEvent) {
if (controlComponent != null) {
remove(controlComponent);
controlComponent = null;
}
if (visualComponent != null) {
remove(visualComponent);
visualComponent = null;
}
}
}
void Fatal(String s) {
// Applications will make various choices about what
// to do here. We print a message
System.err.println("FATAL ERROR: " + s);
throw new Error(s); // Invoke the uncaught exception
// handler System.exit() is another
// choice.
}
}