how to change media in mediaplayer not mediaplayercomponent in vlcj? - swing

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();
}
}

Related

Unable to Switch JPanels after loading jcef browser window

I am trying to use jcef browser inside my swing application but getting problems.
First of all i unable to add jcef browser as JPanel component on jFrame. Then i try to add directly on jframe
[code]getContentPane().add(browser.getUIComponent(), BorderLayout.CENTER);[/code]
Now when browser window load inside JFrame, and If i want to switch with other Jpanel then it is not working working in any way
I cant switch the screen after loading CEF browser. Can any one point out what i need to do. Here is my test jframe.
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class CardLayoutTst extends JFrame {
static CefBrowser browser = null;
static CefClient client = null;
private static final long serialVersionUID = 1L;
private JPanel cardPanel, jp1, jp2, buttonPanel;
private JLabel jl1, jl2;
private JButton btn1, btn2;
private CardLayout cardLayout = new CardLayout();
public CardLayoutTst() {
setTitle("Test med CardLayout");
setSize(400, 300);
cardPanel = new JPanel();
buttonPanel = new JPanel();
cardPanel.setLayout(cardLayout);
jp1 = new JPanel();
jp2 = new JPanel();
jl1 = new JLabel("Card 1");
jl2 = new JLabel("Card 2");
jp1.add(jl1);
jp2.add(jl2);
cardPanel.add(jp1, "1");
cardPanel.add(browser.getUIComponent(), "2");
btn1 = new JButton("Show Card 1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "1");
}
});
btn2 = new JButton("Show Card 2");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "2");
}
});
buttonPanel.add(btn1);
buttonPanel.add(btn2);
add(cardPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
CefApp.getInstance().dispose();
dispose();
}
});
}
public static void main(String[] args) {
client = CefApp.getInstance().createClient();
browser = client.createBrowser("http://www.google.com", false, false);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CardLayoutTst frame = new CardLayoutTst();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
It is a bit late but I had just the same problem. A friend of mine solved the issue.
You have to create CefSettings, set the windowless_rendering_enabled to false and pass this settings object to the getInstance call:
CefSettings settings = new CefSettings();
settings.windowless_rendering_enabled = false;
client = CefApp.getInstance(settings).createClient();

How to stop JLabel.seticon from constantly repainting on top of everything else

I am trying to keep a JInternalFrame called GUIWindow.SpecialOptionsPopUp stay on top of a another JInternalFrame with a JLabel called 'label' in it. The problem occurs when label constantly updates an image within it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JInternalFrame;
public class ForumQuestion extends JFrame {
private JPanel contentPane;
private JLabel label;
private JInternalFrame internalFrame;
private JInternalFrame internalFrame_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ForumQuestion frame = new ForumQuestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ForumQuestion() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
internalFrame_1 = new JInternalFrame("New JInternalFrame");
internalFrame_1.setBounds(0, 0, 424, 250);
contentPane.add(internalFrame_1);
label = new JLabel("");
internalFrame_1.getContentPane().add(label, BorderLayout.NORTH);
internalFrame_1.setVisible(true);
internalFrame = new JInternalFrame("New JInternalFrame");
internalFrame.setBounds(145, 25, 171, 195);
contentPane.add(internalFrame);
internalFrame.setVisible(true);
UpdateImage updateimage = new UpdateImage();
updateimage.start();
}
private class UpdateImage extends Thread{
public UpdateImage(){
}
public void run(){
while(true){
label.setIcon(new ImageIcon("C:/Users/Ali/EclipseWorkspace/ForumQuestion/testimage.png"));
internalFrame.repaint();
contentPane.setComponentZOrder(internalFrame, 0);
}
}
}
}

Getting null / empty JtextArea

I crated a Frame which have a panel inside it and the panel have a textarea inside it. Now i created a constructor which makes the frame visible for some time and after that it is set as invisible. Time for which it is visible it shows some massage.
When i run the constructor code inside the main method of outputDisplay class it shows the text massage
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class OutputDisplay {
static JFrame frame;
JPanel panel;
JTextArea area;
Font font;
public void timer(int time){
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
}
});
timer.start();
timer.setRepeats(false);
}
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue,String path,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.MAGENTA);
area.setSize(200, 200);
int j=0;
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(500, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue) throws InterruptedException{
frame = new JFrame("Report");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.BLUE);
area.setSize(200, 200);
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
frame.setResizable(false);
}//constructor
public OutputDisplay() {
}//no arg
public void dialogue (String massage) throws InterruptedException{
frame = new JFrame("Massage");
frame.setLocation(400, 220);
JPanel panel = new JPanel();
JTextArea area = new JTextArea();
Font font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.GREEN);
area.setSize(200, 200);
int j=0;
String[] t = {massage};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(400, 100);
frame.setVisible(true);
Thread.sleep(8*1000);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//dialogue
static void warningPopUp (String massage){
JOptionPane.showMessageDialog(null, massage);
}//dialogue
public static void main(String[] args){
new OutputDisplay("We are checking for account validation"+"\n"
+ "If user id and password matches then we will goto websites for updation. " +"\n"
+ "You will get a complete report once we are done", 4*1000);
}//main
}//OutputDisplay
Don't call Thread.sleep(...) on the Swing EDT as that just puts your whole GUI to sleep.
Do use a Swing Timer instead.
Do Google and search this site for similar questions.
Please check out Lesson: Concurrency in Swing
Also check out the Swing Tutorials
Edit
You're still using Thread.sleep, again you shouldn't use it, but instead should use a Timer. Also, never set a JTextArea's size or preferred size ever. Do this and the scrollbars of your JScrollPane won't work. Instead, set its rows and columns.
import java.awt.Color;
import java.awt.Font;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TimeLimitedDialogTester {
private static final int EB_GAP = 25;
private JPanel mainPanel = new JPanel();
public TimeLimitedDialogTester() {
mainPanel.add(new JButton(new ShowDialogAction("Show Dialog")));
mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, 2 * EB_GAP, 2 * EB_GAP, 2 * EB_GAP));
}
public JPanel getMainPanel() {
return mainPanel;
}
#SuppressWarnings("serial")
private class ShowDialogAction extends AbstractAction {
public ShowDialogAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Window mainWin = SwingUtilities.getWindowAncestor(mainPanel);
int seconds = 5;
String dialogTitle = "WARNING";
String text = "We are checking for account validation. If user id and password matches then we"
+ " will go to websites for updating. You will get a complete report once we are done.";
TimeLimitedDialog timeLimitedDialog = new TimeLimitedDialog(mainWin, seconds, dialogTitle, text);
timeLimitedDialog.dialogShow();
}
}
private static void createAndShowGui() {
TimeLimitedDialogTester timeLimitedDialog = new TimeLimitedDialogTester();
JFrame frame = new JFrame("TimeLimitedDialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(timeLimitedDialog.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TimeLimitedDialog {
private static final int ROWS = 6;
private static final int COLS = 30;
private static final Color FG = Color.green.darker().darker();
private JDialog dialog;
private JTextArea displayArea = new JTextArea(ROWS, COLS);
private int seconds;
public TimeLimitedDialog(Window mainWin, int seconds, String dialogTitle, String text) {
displayArea.setWrapStyleWord(true);
displayArea.setLineWrap(true);
displayArea.setFocusable(false);
displayArea.setText(text);
displayArea.setForeground(FG);
displayArea.setFont(displayArea.getFont().deriveFont(Font.BOLD));
this.seconds = seconds;
dialog = new JDialog(mainWin, dialogTitle, ModalityType.APPLICATION_MODAL);
dialog.add(new JScrollPane(displayArea));
dialog.pack();
dialog.setLocationRelativeTo(mainWin);
}
public void dialogShow() {
new Timer(seconds * 1000, new TimerListener()).start();
dialog.setVisible(true);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (dialog != null && dialog.isVisible()) {
dialog.dispose();
}
((Timer) e.getSource()).stop();
}
}
}

Updating Layout of Panel after changing label icon

I have created a project that will download the thumbnails of the images from a ftp server and display it in a panel using JLabel.
The images are being displayed but the layout of the panel only works if i call the panel once more (i.e using a button on the frame) then the layout corrects itself automatically. What am i doing wrong? Here is the code
EDIT- Updated the code with sscce
1. sscce.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* #author Rohn
*/
public class Sscce implements Interface{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setVisible(true);
//frame.add(sci.);
Container c=frame.getContentPane();
JButton button=new JButton("Recall ShowCategoryImagesFunction");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
sci.ShowCategoryImagesFunction("\\Nature\\Black And White"); //for testing purpose only
// if button is pressed then we get right layout and image load
}
});
c.setLayout(new FlowLayout());
c.add(button);
c.add(sci.ShowCategoryImagesFunction("\\Nature\\Black And White")); // default path for image load for first time
// problem in correctly loading images and text with layout
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
2. ShowCategoryImages.java
package sscce;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ShowCategoryImages{
//FTPClient client=null;
JPanel panel=new JPanel();
JLabel label=new JLabel();
FTPClient client=new FTPConnection().FTPConnection();
FTPFile[] list;
File thumbnails;
File[] files;
ImageIcon icon;
public JPanel ShowCategoryImagesFunction(String path){
// delete all the components on reload
if(panel.getComponents().length>0){
System.out.println(panel.getComponents().length);
panel.removeAll();
panel.revalidate();
panel.repaint();
}
//panel.setLayout(new GridLayout(0,4,2,2));
//panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
panel.setLayout(new FlowLayout());
panel.revalidate();
panel.repaint();
panel.updateUI();
try{
//images in /wallpapers/nature/black and white/thumb
client.changeDirectory("\\Wallpapers"+path+"\\thumb"); //path of thumbnails
//temporary folder for holding images
thumbnails=new File("Thumbnails");
list=client.list();
if(thumbnails.exists()){
files = thumbnails.listFiles();
if(files!=null) { //some JVMs return null for empty dirs
for(File f: files) {
f.delete();
}
}
}
else
thumbnails.mkdir();
for(int i=0;i<list.length;i++){
System.out.println("running");
icon=new ImageIcon(thumbnails.getAbsolutePath()+"\\"+list[i].getName());
icon.getImage().flush();
client.download(client.currentDirectory()+"\\"+list[i].getName(), new java.io.File(thumbnails.getAbsolutePath()+"\\"+list[i].getName()));
label=new JLabel(list[i].getName());
label.setIcon(icon);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
panel.add(label);
panel.revalidate();
panel.repaint();
label.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JLabel la=(JLabel)e.getSource();
System.out.println(la.getIcon());
}
});
}
//client.disconnect(true);
}catch(Exception e){
System.out.println(e.getMessage());
}
return panel;
}
}
3. FTPConnection.java
import it.sauronsoftware.ftp4j.FTPClient;
public class FTPConnection {
//ftp connection on local host
public static FTPClient FTPConnection(){
String ftphost="127.0.0.1";
String ftpuser="newuser";
String ftppassword="wampp";
int ftpport=21;
FTPClient client=new FTPClient();
try{
if(client.isConnected()==true){
client.disconnect(true);
};
client.connect(ftphost, ftpport);
client.login(ftpuser, ftppassword);
}
catch(Exception e){
System.out.println(e.getMessage());
}
return client;
}
}
not entirely sure what you mean with not layout, but your code is missing a revalidate/repaint after adding the labels:
// adding all labels
forEach (thumb....) {
JLabel label = new JLabel(thumb);
panel.add(label);
}
panel.revalidate();
panel.repaint();

trouble executing actionlistener in swing applet embedded in html

Following is the applet code below:
import javax.swing.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ui extends JApplet implements ActionListener{
public static JPanel panel2;
private JTextField subnetField =null;
public static JPanel panel3;
public static Font fc;
public static String[] subn;
public static String searchnet;
boolean flag=false;
public void init()
{
String hostname = null;
String hostaddress=null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
hostaddress=addr.getHostAddress();
// Get hostname
hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
subn= hostaddress.split("\\.");
System.out.println(subn[2]);
searchnet=subn[2];
//WindowDestroyer listener=new WindowDestroyer();
//addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new GridLayout(3,0));
JPanel panel1 =new JPanel();
panel2 =new JPanel();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
JLabel lb2 = new JLabel("You are at: "+hostname+" "+hostaddress+" ");
lb2.setFont(new Font("sans-serif",Font.BOLD,15));
lb2.setForeground(Color.RED);
JPanel panel1_1 =new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
panel1_1.setBackground(Color.WHITE);
panel1_1.add(lb2, c);
//lb2.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel1_1.add(lb2, BorderLayout.EAST);
panel1_1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(panel1_1);
panel3=new JPanel();
panel3.setLayout(new GridLayout(2,0));
panel3.setBackground(Color.WHITE);
panel1.add(panel3);
UIManager.put("Button.background", Color.white);
UIManager.put("Button.foreground", Color.red);
fc = new Font("sans-serif",Font.BOLD,15);
UIManager.put("Button.font", fc);
JButton searchButton= new JButton("Search");
//Border b = new SoftBevelBorder(BevelBorder.LOWERED) ;
//searchButton.setBorder(b);
searchButton.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(searchButton);
searchButton.addActionListener(this);
contentPane.add(panel1);
panel2.setBackground(Color.WHITE);
contentPane.add(panel2);
//contentPane.add(searchButton);
//JButton closeButton=new JButton("Close");
//contentPane.add(closeButton);
//closeButton.addActionListener(this);
contentPane.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand ().equals ("Close"))
{
System.exit(0);
}
if (e.getActionCommand ().equals ("Search"))
{
panel2.setVisible(false);
panel2.removeAll();
panel2.revalidate();
panel3.setVisible(false);
panel3.removeAll();
panel3.revalidate();
if(flag){
searchnet=subnetField.getText();
}
result(panel2);//puts panel 2&panel 3 in the ui
panel2.setVisible(true);
panel3.setVisible(true);
}
}
public boolean complete;
public JPanel call(){
return null;
}
public void result(JPanel pn){
.
.
.
}
}
}
private void addColumnName(JPanel pn) {
// TODO Auto-generated method stub
}
public void addDataToTable(JPanel p, String element, int type){
......
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (Exception e) {
// TODO: error handling
}
} else {
// TODO: error handling
}
}
public static void main(String[] args){
ui start=new ui();
start.setVisible(true);
JFrame f = new JFrame("Find Device");
ui applet=new ui();
applet.init();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,450);
f.setVisible(true);
}
}
then the html file looks like this:
<html>
<applet code=ui.class
archive="webapplet.jar"
width=800 height=450>
</applet>
</body>
</html>
when i run the program via eclipse as an applet it runs fine, but when i put it in the html file, the init() seems to show up but the actionlistener on the button never seems to work
Any help would be really appreciated. Thanks!!
ps: will be happy to share any additional details if required
Emm... you mean the code never works as
System.exit(0);
?
If you mean "Close" button inactivity so it shouldn't close Internet Browser ... so that's OK :)
And this one as
InetAddress addr = InetAddress.getLocalHost();
Hmm... As for applet, I guess you should use getCodeBase() instead
Good luck :)