Trying to get an applause sound to play when jframe opens - swing

First i will say i have my Jframe opening and staying open for 10 seconds.
I wrote some games for kids to display to them what a future in programming could be or computer science... anyway
Whomever wins I have another Jframe designed to pop up when it does i would like a sound clip to play. Currently the sound clip is in the source folder and i have a little method to play it but it is not working. Here is the code
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class HoorayWithTimer extends javax.swing.JFrame {
int counter;
public HoorayWithTimer() {
initComponents();
Clip click = clipOpen("applause3.wav");// should open the clip
clipStart(click);
}//end of public HorrayWithTimer()
/*
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
timerLabel = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(571, 410));
getContentPane().setLayout(null);
getContentPane().add(timerLabel);
timerLabel.setBounds(632, 411, 66, 29);
timerLabel.getAccessibleContext().setAccessibleName("timerLabel");
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/party_balloons_scaled.png"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 560, 540);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
HoorayWithTimer.this.setVisible(false);
HoorayWithTimer.this.dispose();
}
});
timer.start();
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
private Clip clipOpen(String name)// method to play clip
{
URL url = getClass().getResource(name);
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(stream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
}
return null;
}
private void clipStart(Clip clip) {
clip.start();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new HoorayWithTimer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel timerLabel;
// End of variables declaration
}

I think problem is here clipOpen("applause3.wav"). Try to use /applause3.wav. Also where is your wav file? For example it works for my path "/res/1.mp3", 1.mp3 file exists in res folder in folder src.
EDIT: Replace your code and watch exception, it's here not in clipStart method:
private Clip clipOpen(String name){
URL url = getClass().getResource(name);
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(stream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
ex.printStackTrace()
}
return null;
}

Related

how to change media in mediaplayer not mediaplayercomponent in vlcj?

I'm making desktop application using swing and vlcj. I had divided frame into two part one side webbrowser which is having url of several videos and in another panel vlcj to play that url in mediaplayer. The first url you choose works just fine and is displayed in the player. The thing is, after I choose another url I want the first one to be replaced with the second one. What is the correct way to dispose the first media and then play the second one? The second problem is I had set the vlcj in panel but its openning video in vlc direct 3d output can you tell me why it is not openning in panel canvas.
This is the code what I tried:
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.binding.LibVlcConst;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
/**
*
* #author biznis
*/
public class NewJFrame extends javax.swing.JFrame {
JScrollPane scrollableTextArea;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
//JFrame jFrame2 = new JFrame("vlcj Tutorial");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
canvas1.setBackground(Color.black);
jPanel2.setLayout(new BorderLayout());
jPanel2.setPreferredSize(new Dimension(200,300));
jPanel2.add(canvas1, BorderLayout.CENTER);
// frame.add(jPanel2, BorderLayout.NORTH);
// frame.add(p, BorderLayout.CENTER);
EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
//jPanel2.setLayout(new java.awt.CardLayout());
//jFrame2.setVisible(true);
//jFrame2.setLocation(100, 100);
JPanel p1 = new JPanel();
p1.setBounds(100, 900, 105, 200);
jPanel2.add(p1, BorderLayout.SOUTH);
JButton playbutton = new JButton();
playbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/play.png"));
// this.setSize(800,450);
playbutton.setBounds(50, 50, 150, 100);
playbutton.setToolTipText("Play");
p1.add(playbutton);
JButton pausebutton = new JButton();
pausebutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/pause.png"));
pausebutton.setToolTipText("pause");
pausebutton.setBounds(80, 50, 150, 100);
p1.add(pausebutton);
JButton previousbutton = new JButton();
previousbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/previous.png"));
previousbutton.setBounds(90, 50, 150, 100);
previousbutton.setToolTipText("Skip back");
p1.add(previousbutton);
JButton nextbutton = new JButton();
nextbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/next.png"));
nextbutton.setBounds(90, 50, 150, 100);
nextbutton.setToolTipText(" Skip forward");
p1.add(nextbutton);
JButton captureButton = new JButton();
captureButton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/icons8-unsplash-26.png"));
captureButton.setToolTipText("capture");
captureButton.setBounds(80, 50, 150, 100);
p1.add(captureButton);
JSlider volumeSlider = new JSlider();
volumeSlider.setMinimum(LibVlcConst.MIN_VOLUME);
volumeSlider.setMaximum(LibVlcConst.MAX_VOLUME);
volumeSlider.setPreferredSize(new Dimension(100, 40));
volumeSlider.setToolTipText("Change volume");
p1.add(volumeSlider);
JSlider js = new JSlider();
p1.add(js);
// mediaPlayer.playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");
js.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
mediaPlayer.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(mediaPlayer.getPosition() * 100));
}
});
timer.start();
pausebutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.pause();
// or mediaPlayer.pause() depending on what works.
final long time = mediaPlayer.getTime();
System.out.println(time);
}
});
playbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.play();
}
});
previousbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.skip(-10000);
}
});
nextbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayer.skip(1000);
}
});
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
mediaPlayer.setVolume(volumeSlider.getValue());
}
});
captureButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file3 = new File("C:/Test/");
mediaPlayer.saveSnapshot(file3);
try {
BufferedImage image3 = ImageIO.read(file3);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
JFXPanel jfxPanel = new JFXPanel();
jPanel1.add(jfxPanel);
// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
WebView webView = new WebView();
WebEngine wb1 = webView.getEngine();
jfxPanel.setScene(new Scene(webView));
wb1.load("");
wb1.getLoadWorker().stateProperty()
.addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SCHEDULED) {
frame.setTitle(wb1.getLocation());
String trgurl = wb1.getLocation();
System.out.println(trgurl);
if (trgurl.matches("(.*)video=(.*)")) {
int n = trgurl.indexOf("video=");
//String str1 = Integer.toString(n);
System.out.println(n + 6);
int len = trgurl.length();
System.out.println("string length is: " + trgurl.length());
System.out.println(trgurl.substring(n+6,len));
String find = "file:" +trgurl.substring(n+6,len);
System.out.println(find);
// mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
mediaPlayer.prepareMedia(find);
mediaPlayer.start();
JScrollPane scrollableTextArea = new JScrollPane(jPanel2);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
}
});
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel1.setPreferredSize(new Dimension(200, 300));
canvas1 = new java.awt.Canvas();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(500, 300));
getContentPane().setLayout(new java.awt.GridLayout());
getContentPane().add(jPanel2);
jPanel1.add(canvas1);
getContentPane().add(jPanel1);
// getContentPane().add(sp);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(final String[] args) {
/* Set the Nimbus look and feel */
new NativeDiscovery().discover();
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame = new NewJFrame();
frame.setVisible(true);
}
});
}
private static NewJFrame frame;
// Variables declaration - do not modify
private java.awt.Canvas canvas1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration
}
in jpanel1 im openning vlcj and jpanel2 webview. Please help. Thanks in advance.
This is exception log when i click on next link of video:
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: The video surface component must be displayable
at uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface.attach(CanvasVideoSurface.java:75)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.attachVideoSurface(DefaultEmbeddedMediaPlayer.java:156)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.onBeforePlay(DefaultEmbeddedMediaPlayer.java:315)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.play(DefaultMediaPlayer.java:705)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.playMedia(DefaultMediaPlayer.java:222)
at javaapplication6.NewJFrame$9.changed(NewJFrame.java:231)
at javaapplication6.NewJFrame$9.changed(NewJFrame.java:211)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.web.WebEngine$LoadWorker.updateState(WebEngine.java:1287)
at javafx.scene.web.WebEngine$LoadWorker.dispatchLoadEvent(WebEngine.java:1388)
at javafx.scene.web.WebEngine$LoadWorker.access$1200(WebEngine.java:1280)
at javafx.scene.web.WebEngine$PageLoadListener.dispatchLoadEvent(WebEngine.java:1267)
at com.sun.webkit.WebPage.fireLoadEvent(WebPage.java:2499)
at com.sun.webkit.WebPage.fwkFireLoadEvent(WebPage.java:2343)
at com.sun.webkit.WebPage.twkProcessMouseEvent(Native Method)
at com.sun.webkit.WebPage.dispatchMouseEvent(WebPage.java:807)
at javafx.scene.web.WebView.processMouseEvent(WebView.java:1045)
at javafx.scene.web.WebView.lambda$registerEventHandlers$32(WebView.java:1168)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$null$293(EmbeddedScene.java:256)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$mouseEvent$294(EmbeddedScene.java:244)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Thnx i had solved the problem by taking left and right panel with scroll pane.
import java.awt.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.*;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class MyTestClass extends JFrame {
EmbeddedMediaPlayerComponent playerCmpt;
public MyTestClass() {
new NativeDiscovery().discover();
EmbeddedMediaPlayerComponent playerCmpt = new EmbeddedMediaPlayerComponent();
playerCmpt.setPreferredSize(new Dimension(200, 100));
JPanel leftPane = new JPanel();
leftPane.setPreferredSize(new Dimension(100, 100));
JFXPanel jfxPanel = new JFXPanel();
leftPane.add(jfxPanel);
//jPanel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//jPanel1.setBorder(new EmptyBorder(20, 20, 20, 20));
// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
WebView webView = new WebView();
WebEngine wb1 = webView.getEngine();
jfxPanel.setScene(new Scene(webView));
wb1.load("");
wb1.getLoadWorker().stateProperty()
.addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SCHEDULED) {
// this.setTitle(wb1.getLocation());
String trgurl = wb1.getLocation();
System.out.println(trgurl);
if (trgurl.matches("(.*)video=(.*)")) {
int n = trgurl.indexOf("video=");
//String str1 = Integer.toString(n);
System.out.println(n + 6);
int len = trgurl.length();
System.out.println("string length is: " + trgurl.length());
System.out.println(trgurl.substring(n+6,len));
String find = "file:" +trgurl.substring(n+6,len);
System.out.println(find);
// mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
// mediaPlayer.release();
playerCmpt.getMediaPlayer().playMedia(find);
// mediaPlayer.stop();
// mediaPlayer.prepareMedia(find);
// mediaPlayer.stop();
//mediaPlayer.prepareMedia(find);
//JScrollPane scrollableTextArea = new JScrollPane(jPanel2);
//scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
}
});
});
JPanel playerPanel = new JPanel(new BorderLayout());
playerPanel.add(playerCmpt);
JSplitPane mainSplit = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftPane, playerPanel);
playerPanel.setMinimumSize(new Dimension(10, 10));
this.add(mainSplit);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//playerCmpt.getMediaPlayer().playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");
}
public static void main(String[] args) {
new MyTestClass();
}
}

Adding another movable image in Swing

I have stumpled upon a problem. What I'm trying to do is to add another movable image in JPanel, movable as in that one could drag it with the mouse. This program only can view one image at the time and drag it arround. So how could I do to have more than one picture in my program?
=)
Here is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class test2 {
public static void main(String[] args) {
new test2();
}
public test2() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
Bild bild = new Bild();
frame.add(new DragMyIcon("katt.gif"));
frame.setSize(640,460);
frame.setVisible(true);
}
});
}
protected class DragMyIcon extends JPanel {
public static final long serialVersionUID = 172L;
private JLabel label;
public DragMyIcon(String path) {
setLayout(null);
ImageIcon icon = null;
icon = new ImageIcon(path);
label = new JLabel(icon);
label.setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);
}
}
protected class MouseHandler extends MouseAdapter {
private boolean active = false;
private int xDisp;
private int yDisp;
#Override
public void mousePressed(MouseEvent e) {
active = true;
JLabel label = (JLabel) e.getComponent();
xDisp = e.getPoint().x - label.getLocation().x;
yDisp = e.getPoint().y - label.getLocation().y;
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
#Override
public void mouseReleased(MouseEvent e) {
active = false;
JLabel label = (JLabel) e.getComponent();
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
if (active) {
JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();
label.setLocation(point.x - xDisp, point.y - yDisp);
label.invalidate();
label.repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
}}
What I'm trying to do is to add another movable image in JPanel,
Where? I don't see any code?
You only add a single label to the panel. If you want to drag more than one then you need to add more than one label to the panel.
This program only can view one image at the time and drag it arround.
Well maybe you need a method like addImage(Image image, int x, int y). Then when you invoke this method you:
create a JLabel using the image for the Icon
set the bounds of the label using the x/y and the image size
add the listeners to the label
add the label to the panel

Moving JavaFX Nodes Between Stages

I'm rewriting a Swing application in JavaFX, where I allow users to present multiple workspaces as either windows or tabs. However, my FX code will not display the contents moved from more than one tab into a new stage; only the contents of the currently-selected tab appear in my new stages. I've distilled my code into a small example below. Can anyone clue me in as to what's gone wrong?
package scenes;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class StageSwapper extends Application {
static public void main(String[] args) {
launch(args);
}
private TabPane tabs = new TabPane();
public void start(Stage stage) {
stage.setTitle("Stage Swapper");
BorderPane p = new BorderPane();
p.setCenter(tabs);
tabs.getTabs().addAll(new Swapee("First").createTab(), new Swapee("Second").createTab());
Scene s = new Scene(p);
stage.setScene(s);
stage.show();
launchSwap();
}
private void launchSwap() {
new Thread() {
public void run() {
try {
sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
Platform.runLater(new Runnable() {
public void run() {
for (Swapee s : Swapee.list) {
createWindow(s);
}
}
});
}
}.start();
}
public void createWindow(Swapee s) {
Stage window = new Stage();
window.setTitle("New Window");
window.setY(200);
window.setX(200);
BorderPane p = new BorderPane();
p.setCenter(s);
window.setScene(new Scene(p));
window.show();
}
}
class Swapee extends Label {
static private int count;
static ArrayList<Swapee> list = new ArrayList<>();
String name;
Swapee(String name) {
super("Swappable Item " + ++count);
this.name = name;
list.add(this);
}
Tab createTab() {
Tab t = new Tab(name);
t.setContent(this);
return t;
}
}
You haven't specified the size of the windows that you're creating. Right now they have width and length equal to 0. You may use the following approach:
BorderPane p = new BorderPane();
p.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
p.setCenter(s);
BorderPane will be resized according to its content and the window will be resized as well.

Swing GUI Client Listeners not responding to update of Remote RMI Property

I am having some trouble with getting a JTree to redraw when an explicit call is made to its model (a call which I make once I have added some new nodes to it).
The code, which initially worked fine, fails now that the application is exported to RMI.
I store the DefaultTreeModel object in the Controller class, which is a Remote Object.
I add the DefaultTreeModel object to the JTree in my Client, using tree.addModel(controller.getModel());
I use an ActionListener subscribed to a button on the Client GUI to call a method in the Controller which performs the "Add new node" action.
I use a TreeModelListener to print a message to screen to prove that the Model Listener has fired.
Do Client side Swing listeners not work over RMI?
I have managed to reproduce the problem. I include the code for completeness but anticipate that someone will be able to reel off the answer based on experience.
Server Driver Class:
package server;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import client.controller.TestTreeControllerService;
import server.controller.TestTreeControllerImpl;
public class TestTreeServerStart {
/**
* #param args
*/
public static void main(String[] args) {
new TestTreeServerStart();
}
public TestTreeServerStart() {
try {
LocateRegistry.createRegistry(1099);
TestTreeControllerService c = new TestTreeControllerImpl();
Registry registry = LocateRegistry.getRegistry();
registry.rebind("TestTreeControllerService", c);
System.out.println("Started the RMI Server");
}
catch (RemoteException e) {
System.out.println(e.getMessage());
}
}
}
Server Controller Implementation Class:
package server.controller;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.controller.TestTreeControllerService;
#SuppressWarnings("serial")
public class TestTreeControllerImpl extends UnicastRemoteObject implements TestTreeControllerService {
/**
*
*/
//private static final long serialVersionUID = -8137864611400855504L;
private DefaultTreeModel m ;
public DefaultTreeModel getModel() {
return m;
}
public TestTreeControllerImpl() throws RemoteException {
super();
m = new DefaultTreeModel(new DefaultMutableTreeNode("Root"));
}
public void addNodeAction() throws RemoteException {
DefaultTreeModel m = (DefaultTreeModel) getModel();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
DefaultMutableTreeNode root = (DefaultMutableTreeNode) m.getRoot();
root.add(newNode);
//m.insertNodeInto(newNode, (DefaultMutableTreeNode) m.getRoot(), m.getChildCount(m.getRoot()));
m.nodeStructureChanged(root);
}
}
Client Driver Class:
package client;
import java.rmi.Naming;
import java.rmi.RemoteException;
import client.controller.TestTreeControllerService;
import client.view.TreeTestClient;
public class TreeTestClientStart {
/**
* #param args
*/
public static void main(String[] args) {
try {
TestTreeControllerService c = (TestTreeControllerService) Naming.lookup("rmi://localhost:1099/TestTreeControllerService");
new TreeTestClient(c);
}
catch(RemoteException e) {
System.out.println("Remote service not found: " + e.getLocalizedMessage());
}
catch (Exception e) {
System.out.println("Splat");
}
}
}
Client Controller Interface:
package client.controller;
import javax.swing.tree.DefaultTreeModel;
public interface TestTreeControllerService extends java.rmi.Remote {
public DefaultTreeModel getModel() throws java.rmi.RemoteException;
public void addNodeAction() throws java.rmi.RemoteException;
}
Client UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
*Client "Add Node" Action Listener (invokes Add Action in Controller) *
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.view.TreeTestClient;
public class AddNodeAction implements ActionListener {
private TreeTestClient treeTest;
public AddNodeAction(TreeTestClient treeTestIn) {
treeTest=treeTestIn;
}
#Override
public void actionPerformed(ActionEvent arg0) {
try {
treeTest.getController().addNodeAction();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client "Refresh Action" Tree Listener (Prints to Screen to prove that Listener fired)
package client.view.action;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import client.view.TreeTestClient;
public class RefreshTreeAction implements PropertyChangeListener, TreeModelListener {
private TreeTestClient treeTest;
public RefreshTreeAction(TreeTestClient treeTestIn) {
treeTest = treeTestIn;
}
private void refreshTree() {
System.out.println("Refresh tree fired");
}
#Override
public void treeNodesChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesInserted(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesRemoved(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeStructureChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void propertyChange(PropertyChangeEvent arg0) {
refreshTree();
}
}
The TreeModel exported by the server is serialized to the client as the client's own copy. The server doesn't know anything about what happens to the client's copy, and the client doesn't know anything about what happens to the server's copy. They are not the same object.
By adding the following code to an ActionListener subscribed to a new button on the GUI, I have been able to examine the contents of the Model at the click of a button:
//Loop contents of model attached to Client Tree
for (int i=0; i<t.getModel().getChildCount(t.getModel().getRoot()); i++) {
System.out.println("From Tree: Row #" + i + ": " + t.getModel().getChild(t.getModel().getRoot(), i));
}
//Loop contents of model object stored in Controller
try {
for (int i=0; i<c.getModel().getChildCount(c.getModel().getRoot()); i++) {
System.out.println("From Controller: Row #" + i + ": " + c.getModel().getChild(c.getModel().getRoot(), i));
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I found that the reference to the Client's Model was a different version to the state being maintained in the Controller's model object. There was no output in the Client loop, but the Controller's loop gave the correct state.
I have subsequently added a Swing Timer to the GUI to refresh the tree's model to match that of the Constructor. An updated GUI Class and GUI Refresh Action follow, which work:
Updated UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.Timer;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.GUIRefreshAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a listener that doesn't use the Remote object
t.addTreeSelectionListener(new RefreshTreeAction(this));
//Try a property change listener on the TreeModel
t.addPropertyChangeListener("treeModel", new RefreshTreeAction(this));
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
//Add a GUI redraw timer
Timer timer = new Timer(1000, new GUIRefreshAction(this));
timer.setInitialDelay(1);
timer.start();
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
GUI Refresh Listener Class
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import client.view.TreeTestClient;
public class GUIRefreshAction implements ActionListener {
private TreeTestClient client;
public GUIRefreshAction(TreeTestClient clientIn) {
client = clientIn;
}
#Override
public void actionPerformed(ActionEvent e) {
//Update the Tree's Model to match latest on Server
try {
client.getTree().setModel(client.getController().getModel());
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
}
I hope this helps someone who has the same requirements for a RMI Client Swing GUI to update in reaction to changes on the Server.

documentFilter.insert never called

I'm trying to set a documentFilter for my JTextArea. Having overriden the insert(...) method I admitted that it is never called. What's wrong? A piece of code:
package jaba;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640, 480);
setLayout(new FlowLayout());
add(txt);
Document doc = txt.getDocument();
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).setDocumentFilter(new DocumentFilter() {
#Override
public void insertString(DocumentFilter.FilterBypass fb,
int offset, String string, AttributeSet att)
throws BadLocationException {
if (string.toLowerCase().contains("ass")) {
super.insertString(fb, offset, "###", att);
} else {
super.insertString(fb, offset, string, att);
}
}
});
} else {
txt.setText("error setting filter");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().setVisible(true);
}
});
}
private JTextArea txt = new JTextArea(40, 40);
}
Having overriden the insert(...) method I admitted that it is never called.
Changes to the text in Swing components ultimately invoke the replace(...) method of the DocumentFilter.
The insertString(...) method is only invoked when you update the Document directly by using code like:
textField.getDocument().insertString(...);
So you need to make sure that you also override the replace() method in the DocumentFilter.