I have a Java applet (developed in NetBeans 7.4 and using JMF) for taking pictures from a web camera, it initializes the webcam automatically at startup (by using JMF)...
(APPLET)
For making it run it's necessary to add the jmf.properties file inside same directory of JAR file like this:
I tried to show this component inside a HTML page for taking snapshots from a WebBrowser but the JMF doesn't work there, everytime I run it I get this message (trying to initialize the webCam with JMF):
then it just displays the applet
this is my HTML code (Generated by Netbeans)
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<!--
*** GENERATED applet HTML launcher - DO NOT EDIT IN 'BUILD' FOLDER ***
If you need to modify this HTML launcher file (e.g., to add applet parameters),
copy it to where your applet class is found in the SRC folder. If you do this,
the IDE will use it when you run or debug the applet.
Tip: To exclude an HTML launcher from the JAR file, use exclusion filters in
the Packaging page in the Project Properties dialog.
For more information see the online help.
-->
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="com/xxx/pantallas/CamaraApplet.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
and the directory from where I open my HTML
Any help for making the webCam running from the HTML as well I'll appreciate
Requirements:
Have installed JDK 32Bit version
Have installed JMF: Link to download page
Full project: Link to download page
**Libraries required***** : Link to download page
***libraries are required for using JMF on the project
For make this project running I use:
2 classes
1 applet (main)
1 HTML file
CameraApplet.java (Applet)
import java.lang.reflect.InvocationTargetException;
import javax.media.Player;
import javax.swing.JPanel;
import static com.sun.java.accessibility.util.AWTEventMonitor.addWindowListener;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CameraApplet extends javax.swing.JApplet {
private Player p1;
public Player getPlayer() {return p1;}
public void setPlayer(Player pin) {p1 = pin;}
public JPanel getCamera() {return panelCam;}
private void initComponents2() {
//Register all the listeners of the Events
AuxClass e = new AuxClass(this);
addWindowListener(e);
jmCArchivo.addActionListener(e);
//Loads in menu all detected devices
AuxClass.DevicesMenuApplet(this, jmDispositivos);
//applet size
setSize(680, 840);
//Autostarts camera
AuxClass.setCameraApplet(CameraApplet.this,
AuxClass.detectAvailableWebCameras().get(0),
0);
}
#Override
public void init() {
//Establecer los valores de look and feel del applet
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e){
AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
}
/* crea y muestra el applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
initComponents2();
}
});
}
catch (InterruptedException | InvocationTargetException e){
AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
}
}
/**
* This method is called from within the init() method 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() {
panelCam = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jmCapturar = new javax.swing.JMenu();
jmCArchivo = new javax.swing.JMenuItem();
jmDispositivos = new javax.swing.JMenu();
setPreferredSize(new java.awt.Dimension(640, 480));
panelCam.setBorder(javax.swing.BorderFactory.createTitledBorder("Camara Web"));
panelCam.setPreferredSize(new java.awt.Dimension(640, 480));
panelCam.setLayout(new java.awt.BorderLayout());
jmCapturar.setText("Capturar");
jmCArchivo.setText("En Archivo");
jmCapturar.add(jmCArchivo);
jMenuBar1.add(jmCapturar);
jmDispositivos.setText("Dispositivos");
jMenuBar1.add(jmDispositivos);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jmCArchivo;
private javax.swing.JMenu jmCapturar;
private javax.swing.JMenu jmDispositivos;
private javax.swing.JPanel panelCam;
// End of variables declaration
}
AuxClass.java
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.control.FormatControl;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;
import javax.media.format.YUVFormat;
import javax.media.util.BufferToImage;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
public class AuxClass implements WindowListener,ActionListener{
private final CameraApplet padreApplet;
public AuxClass(CameraApplet padreApplet){this.padreApplet = padreApplet;}
//Menu Actions
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("En Archivo")){
AuxClass.saveImageFile(AuxClass.capturePhoto(padreApplet.getPlayer()),
AuxClass.SaveFileAsDialog(padreApplet));
}
}
#Override
public void windowClosing(WindowEvent e) {AuxClass.stopPlayer(padreApplet.getPlayer());}
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
//This method handles the Saving image file as. Jpg
public static File SaveFileAsDialog(Component padre){
JFileChooser f;
File imageFile = null;
String imagePath = "";
f = new JFileChooser();
f.setDialogTitle("Save File As...");
f.showSaveDialog(padre);
if(f.getSelectedFile() != null){
imagePath = f.getSelectedFile().getAbsolutePath();
if (imagePath.lastIndexOf(".") > 0)
imagePath = imagePath.substring(0,imagePath.lastIndexOf("."));
imagePath = imagePath + ".jpg";
imageFile = new File(imagePath);
}
return imageFile;
}
public static void showErrorMessage(Component padre,String mensaje){
JOptionPane.showMessageDialog(padre,mensaje,"Captura Camara Web ",JOptionPane.ERROR_MESSAGE);
}
//This is the link between camera and the player class first time you turn the camera on
public static void setCameraApplet(CameraApplet camera,String device,int format){
Player player = AuxClass.createPlayer(device, format);
camera.setPlayer(player);
AuxClass.startPlayer(player);
camera.getCamera().add(player.getVisualComponent());
}
//----------------------------------------Player methods----------------------------------------
public static void startPlayer(Player p){
if(p!=null) p.start();
}
public static void stopPlayer(Player p){
if(p!=null){
p.stop();
p.deallocate();
p.close();
}
}
public static Image capturePhoto(Player p){
Image img = null;
if(p != null){
FrameGrabbingControl fgc = (FrameGrabbingControl)p.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = fgc.grabFrame();
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
}
else{
AuxClass.showErrorMessage(null, "¡Player has not started yet!");
}
return img;
}
public static void saveImageFile(Image img,File imagenArch){
String format = "JPG";
try {
if(img !=null && imagenArch!=null)
ImageIO.write((RenderedImage) img, format , imagenArch);
}
catch (IOException e) {
AuxClass.showErrorMessage(null, "Disk write error: " + e.toString());
}
}
//JDevices methods
//returns webCam's name selected
public static CaptureDeviceInfo returnDevice(String name){
return CaptureDeviceManager.getDevice(name);
}
//open webCamera selected
public static MediaLocator openDevice(CaptureDeviceInfo cdi){
return cdi.getLocator();
}
//Crea un Player a partir del nombre del dispositivo y del indice del formáto que se desea aplicar
public static Player createPlayer(String device,int f){
Player p = null;
try {
p = Manager.createRealizedPlayer(openDevice(returnDevice(device)));
Format []formats;
formats = getFormats(device);
FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
formatControl.setFormat (formats[f]);
}
catch (CannotRealizeException | IOException | NoPlayerException e) {
AuxClass.showErrorMessage(null, "Input-Output Error: \n" + e.toString());
}
return p;
}
//Returns available formats, passing device's name
public static Format[] getFormats(String name){
CaptureDeviceInfo cdi1 = returnDevice(name);
Format []formats = cdi1.getFormats();
return formats;
}
//Switches player's resolutions
public static void changeResolution(Player p,String device,int format){
if(p != null) p.stop();
Format []formats = getFormats(device);
FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
formatControl.setFormat (formats[format]);
p.start();
}
//Loads all the cameras detected and its actions within a JMenu object
public static void DevicesMenuApplet(CameraApplet camera, JMenu devices){
List<String> cameraList = detectAvailableWebCameras();
Format[] formatsArray;
for(int j= 0; j< cameraList.size(); j++){
JMenu menuFormato = new JMenu(cameraList.get(j));
JMenuFormato cameraRes = null;
CaptureDeviceInfo dev = CaptureDeviceManager.getDevice(cameraList.get(j));
formatsArray = dev.getFormats();
//get the formats/resolutions availables:
for(int i = 0; i < formatsArray.length; i++){
if(formatsArray[i].getEncoding().compareTo("yuv") == 0){
//this returns a menu element with label of the resolution and its actionlistener
cameraRes = new JMenuFormato(cameraList.get(j),
formatsArray[i].getEncoding()+" "+
((YUVFormat)formatsArray[i]).getSize().width + "x" +
((YUVFormat)formatsArray[i]).getSize().height,
i,
((YUVFormat)formatsArray[i]).getSize().width ,
((YUVFormat)formatsArray[i]).getSize().height ,
camera,
camera.getCamera());
}
else
if(formatsArray[i].getEncoding().compareTo("rgb") == 0){
cameraRes = new JMenuFormato(cameraList.get(j),
formatsArray[i].getEncoding()+" "+
((RGBFormat)formatsArray[i]).getSize().width+"x"+
((RGBFormat)formatsArray[i]).getSize().height,
i,
((RGBFormat)formatsArray[i]).getSize().width,
((RGBFormat)formatsArray[i]).getSize().height,
camera,
camera.getCamera());
}
menuFormato.add(cameraRes);//Adds the menu to JMenu list
}
devices.add(menuFormato);
}
}
//Detects all the camera devices detected inside a List
public static List<String> detectAvailableWebCameras(){
//make a reference to a JMF function for obtaining the devices
List<String> deviceList = CaptureDeviceManager.getDeviceList(null);
List<String> cameraList = new ArrayList<>();
Iterator it = deviceList.iterator();
String name = ""; //Stores all the names of the devices
while (it.hasNext()){ //Makes a cycle for listing all stored devices
CaptureDeviceInfo cdi = (CaptureDeviceInfo)it.next(); //Get device info
name = cdi.getName(); //Get detected device's name
//Filter only camera devices
if(name.indexOf("Image") != -1){cameraList.add(name);}
}
return cameraList;
}
}
JMenuFormato.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
//this class implements logic for obtaining menus and resolutions JFrame
public class JMenuFormato extends JMenuItem implements ActionListener{
private final int width;
private final int high;
private final int ordinal;
private final JPanel modifiable;
private final String device;
private final CameraApplet cameraApplet;
//Constructores (Version Applet y version JFrame)
public JMenuFormato(String device,String label,int ordinal,int width,int high,CameraApplet cameraApplet,JPanel modifiable){
super(label);
this.modifiable = modifiable;
this.width = width;
this.high = high;
this.cameraApplet = cameraApplet;
this.device = device;
this.ordinal = ordinal;
this.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
//Acciones para Applet (Class)
if(cameraApplet.getPlayer() == null){
AuxClass.setCameraApplet(cameraApplet, device, ordinal);
}
else{
AuxClass.changeResolution(cameraApplet.getPlayer(),device, ordinal);
}
cameraApplet.setSize(width+200, high+200);
}
}
index.html
<html>
<head>
<title>WebCam app</title>
</head>
<body>
<div><applet code="CameraApplet.class" archive="CapturaCamaraWeb.jar" width="680" height="840"></applet></div>
</body>
</html>
Related
I'd like to know if it is possible to make a progress bar displayed on the taskbar like Windows Explorer does when there's a file operation going on?
I saw many examples, but they all involved C#.
SWT won't cut it.
I found out that this feature is included in Java 9. It is part of AWT and it is quity simple too use.
Here is short example:
import java.awt.Taskbar;
import java.awt.Taskbar.State;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* #author fxl
*/
public class TaskbarSample {
public static void main(String[] args) {
// JavaDoc:
// https://docs.oracle.com/javase/9/docs/api/java/awt/Taskbar.html
// MSDNDoc:
// https://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx
if (Taskbar.isTaskbarSupported() == false) {
return;
}
JFrame dialog = new JFrame("Test - 50%");
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
Taskbar taskbar = Taskbar.getTaskbar();
taskbar.setWindowProgressState(dialog, State.ERROR);
taskbar.setWindowProgressValue(dialog, 50);
}
}
this is now possible using SWT please review the code example:
org.eclipse.swt.snippets.Snippet336
This example will do the job:
Task bar:
Code:
import org.bridj.Platform;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;
import org.bridj.jawt.JAWTUtils;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TaskBarListDemo extends JFrame implements ActionListener, ChangeListener
{
private ITaskbarList3 list;
private JSlider slider;
private Pointer<?> hwnd;
private TaskBarListDemo() throws ClassNotFoundException
{
super("TaskbarList Demo (" + (Platform.is64Bits() ? "64 bits" : "32 bits") + ")");
list = COMRuntime.newInstance(ITaskbarList3.class);
getContentPane().add("Center", new JLabel("Hello Native Windows 7 World !"));
Box box = Box.createVerticalBox();
int min = 0;
int max = 300;
int val = (min + max / 2);
slider = new JSlider(min, max, val);
slider.addChangeListener(this);
box.add(slider);
ButtonGroup group = new ButtonGroup();
for (ITaskbarList3.TbpFlag state : ITaskbarList3.TbpFlag.values())
{
JRadioButton cb = new JRadioButton(state.name());
group.add(cb);
cb.putClientProperty(ITaskbarList3.TbpFlag.class, state);
cb.setSelected(state == ITaskbarList3.TbpFlag.TBPF_NORMAL);
cb.addActionListener(this);
box.add(cb);
}
getContentPane().add("South", box);
}
#Override
protected void finalize() throws Throwable
{
super.finalize();
list.Release();
}
public void setVisible(boolean visible)
{
super.setVisible(visible);
long hwndVal = JAWTUtils.getNativePeerHandle(this);
hwnd = Pointer.pointerToAddress(hwndVal);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void stateChanged(ChangeEvent actionEvent)
{
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
JRadioButton button = ((JRadioButton) actionEvent.getSource());
if (button.isSelected())
{
ITaskbarList3.TbpFlag flag = (ITaskbarList3.TbpFlag) button.getClientProperty(ITaskbarList3.TbpFlag.class);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
list.SetProgressState((Pointer) hwnd, flag);
}
}
public static void main(String[] arguments) throws Exception
{
TaskBarListDemo f = new TaskBarListDemo();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
Maven dependencies:
<dependencies>
<dependency>
<groupId>com.nativelibs4java</groupId>
<artifactId>bridj</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
There is no standard facility in Java for doing so, yet.
Hence you need to talk to Windows directly to do that. So you need to locate the correct Windows routine, and use JNA (probably the easiest) to invoke that routine. I do not know of a vendor or a project who has done this already.
Edit: It appears that the http://code.google.com/p/nativelibs4java/ project may do what you want.
As Java9's java.awt.Taskbar only works for old swing frames (they somehow forgot to implement this for javafx.stage.Stage) and com.nativelibs4java bridj isn't working (anymore) (see https://github.com/nativelibs4java/BridJ/issues/94) I implemented a solution using JNA 4.1.0.
Please note:
Relies on calling internal javafx api (com.sun.javafx.stage.WindowHelper) - so it might break with the next java update
It only sets the "indeterminate" progress state - but normal progress state should be possible too with some adjustments
Hope this helps.
ITaskbarList3.java
package example;
import com.sun.jna.platform.win32.Guid.IID;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
public interface ITaskbarList3 {
IID IID_ITASKBARLIST3 = new IID("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"); // from ShObjIdl.h
int TBPF_NOPROGRESS = 0;
int TBPF_INDETERMINATE = 0x1;
int TBPF_NORMAL = 0x2;
int TBPF_ERROR = 0x4;
int TBPF_PAUSED = 0x8;
HRESULT SetProgressState(HWND hwnd, int tbpFlags);
}
TaskbarList3.java
package example;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import com.sun.jna.platform.win32.COM.COMInvoker;
public final class TaskbarList3 extends COMInvoker implements ITaskbarList3 {
public TaskbarList3(Pointer pointer) {
setPointer(pointer);
}
#Override
public HRESULT SetProgressState(HWND hwnd, int tbpFlags) {
return (HRESULT) this._invokeNativeObject(
10, // magic number (gathered by trial and error)
new Object[] { this.getPointer(), hwnd, tbpFlags },
HRESULT.class);
}
}
TaskbarPeer.java
package example;
import com.sun.javafx.stage.WindowHelper;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Guid.CLSID;
import com.sun.jna.platform.win32.Ole32;
import com.sun.jna.platform.win32.W32Errors;
import com.sun.jna.platform.win32.WTypes;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.ptr.PointerByReference;
import javafx.stage.Stage;
public final class TaskbarPeer {
public static void setIndeterminateProgress(Stage stage, boolean indeterminate) {
final var peer = WindowHelper.getPeer(stage);
final long windowHandle = peer.getRawHandle();
final var clsid = new CLSID("56FDF344-FD6D-11d0-958A-006097C9A090"); // from ShObjIdl.h
final var taskbarListPointerRef = new PointerByReference();
var hr = Ole32.INSTANCE.CoCreateInstance(clsid, null, WTypes.CLSCTX_SERVER,
ITaskbarList3.IID_ITASKBARLIST3, taskbarListPointerRef);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
final TaskbarList3 taskbarList = new TaskbarList3(taskbarListPointerRef.getValue());
final var hwnd = new HWND(new Pointer(windowHandle));
final int progressState = indeterminate ? ITaskbarList3.TBPF_INDETERMINATE : ITaskbarList3.TBPF_NOPROGRESS;
hr = taskbarList.SetProgressState(hwnd, progressState);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
}
}
Sample.java
package example;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public final class Sample extends Application {
private boolean indeterminateProgressState = false;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
final Button btn = new Button("Click me!");
primaryStage.setScene(new Scene(btn));
primaryStage.sizeToScene();
primaryStage.show();
btn.setOnAction(evt -> {
indeterminateProgressState = !indeterminateProgressState;
TaskbarPeer.setIndeterminateProgress(primaryStage, indeterminateProgressState);
});
}
}
Windows exposes this through COM. I am sure a "flat DLL" call would be easier for you, but if you can get to COM you can do this. The COM interface is ITaskbarList3 (there is also an ITaskbarList4 you can use that inherits from it.) http://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx documents it. SetProgressState and SetProgressValue are the methods you will want to invoke. State is normal (green), paused (yellow), error (red), indeterminate (swooshing green) and none. On the MSDN page some community people have added details of calling this COM component from VB and C# - that might help you figure out the setup and tear down required from Java.
I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
I created a JavaFX application that is nearly completed. I exported it as a runnable JAR. When opening this JAR I only see a blank window. i followed some other answers from stackoverflow but I did not get it working.
It works only in the Eclipse IDE!
My screens controller:
package gui;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
public class ScreensController extends StackPane {
private HashMap<String, Node> screens = new HashMap<>();
public static String sourcePath = "";
private CoreService coreService;
public ScreensController(){
super();
}
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public boolean loadScreen(String name, String resource) {
System.out.println("ID: "+name);
System.out.println("Resource: "+resource);
String file = System.getProperty("user.dir")+"\\bin\\"+resource;
// System.out.println(file);
try {
FXMLLoader myLoader = new FXMLLoader();
File f = new File(file);
URL url = f.toURI().toURL();
myLoader.setLocation(url);
// System.out.println("Location: "+myLoader.getLocation());
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenControler =
((ControlledScreen) myLoader.getController());
myScreenControler.setScreenParent(this);
addScreen(name, loadScreen);
System.out.println("Anzahl Screens: "+screens.size());
return true;
}catch(Exception e) {
System.out.println("Fehler beim Laden von "+file);
System.out.println(e.getMessage());
return false;
}
}
public boolean setScreen(final String name) {
#SuppressWarnings("unused")
Node screenToRemove;
if(screens.get(name) != null){ //screen loaded
if(!getChildren().isEmpty()){ //if there is more than one screen
getChildren().add(0, screens.get(name)); //add the screen
screenToRemove = getChildren().get(1);
getChildren().remove(1); //remove the displayed screen
}else{
getChildren().add(screens.get(name)); //no one else been displayed, then just show
}
return true;
}else {
System.out.println("Screen hasn't been loaded!!! \n");
return false;
}
}
public boolean unloadScreen(String name) {
if(screens.remove(name) == null) {
System.out.println("Screen didn't exist!!!");
return false;
} else {
return true;
}
}
public void print() {
Set<String> keys = screens.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()){
System.out.println("Key: "+it.next());
}
}
public CoreService getCoreService(){
return this.coreService;
}
public void setCoreService(CoreService coreService){
this.coreService = coreService;
}
}
And here I use it:
package gui;
import java.util.Optional;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class MainMenu extends Application {
private Stage mainStage;
private static CoreService coreService;
public static final String MAIN_SCREEN = "main";
public static final String MAIN_SCREEN_FXML = "gui\\MainMenu.fxml";
#Override
public void start(Stage primaryStage) {
this.mainStage = primaryStage;
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(MainMenu.MAIN_SCREEN, MainMenu.MAIN_SCREEN_FXML);
mainContainer.setCoreService(MainMenu.coreService);
mainContainer.setScreen(MainMenu.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest(confirmCloseEventHandler);
primaryStage.show();
}
private EventHandler<WindowEvent> confirmCloseEventHandler = event -> {
//Source: http://stackoverflow.com/questions/29710492/javafx-internal-close-request
Alert closeConfirmation = new Alert(
Alert.AlertType.CONFIRMATION,
"Are you sure you want to exit?"
);
Button exitButton = (Button) closeConfirmation.getDialogPane().lookupButton(
ButtonType.OK
);
exitButton.setText("Exit");
closeConfirmation.setHeaderText("Confirm Exit");
closeConfirmation.initModality(Modality.APPLICATION_MODAL);
closeConfirmation.initOwner(mainStage);
closeConfirmation.setX(mainStage.getX() + 150);
closeConfirmation.setY(mainStage.getY() - 300 + mainStage.getHeight());
Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
if (!ButtonType.OK.equals(closeResponse.get())) {
event.consume();
}
};
public static void main(String[] args, CoreService aService) {
// Weitergeben des CoreServices
coreService = aService;
launch(args);
}
}
I do not see where the error is.
When I start the program from command line it says that the MainMenu.fxml file could not been found.
In my application it is in the package gui. -> gui/MainMenu.fxml
Would be nice if someone find my error!
What the error message tells you, that the FXML file cannot be located.
You could try to:
Change this ...
public static final String MAIN_SCREEN_FXML = "gui\\MainMenu.fxml";
... to ...
public static final String MAIN_SCREEN_FXML = "/gui/MainMenu.fxml";
And to change this ...
FXMLLoader myLoader = new FXMLLoader();
File f = new File(file);
URL url = f.toURI().toURL();
myLoader.setLocation(url);
... to (and you don't need the variables file and f)...
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Some references:
I had an answer here on how to use getResource.
Also you can check the documentation of getResource()
And you can check this question about loading resources from a JAR
Hello i create the GUI code for simple Java editor
i create the menu but i need to match
File: New: Create a new file. asking for the name of the file (and therefore the public class) and the directory in which it will be stored. With the creation of the file is inserted into the structure of the public class, for example public class MyClass{ }.
Open: opens files with source code java ( .java).
Save : saves the current snippet on the same file with this established during the creation of.
Save as : displays the dialog box where you requested the name of the file, the format of the directory in which it will be stored. The format will be java file ( .java). The main part of the window will have the editor to be used by the user to edit a file source Java.
The main part of the window will have the editor to be used by the user to edit a file source Java. information which will be renewed during the processing of a snippet: Number lines Number reserved words in java source code
Formatting Text
Each file will open formatted and will formatted when processed in the following rules: The reserved words of java will appear with color blue.
The comments will appear in green
The String Literals with orange
All other with black
The Font will be Courier Font size 12pt
i will provide the GUI code can anyone help me with the above ?
Regards
Antonis
// ClassEEFrame
package editor.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class EEFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1709009137090877913L;
private GridBagLayout layout;
private GridBagConstraints constraints;
private EEMenuBar menuBar;
private EETextPane editor;
private EEConsole console;
private EEStatusBar statusBar;
private File file;
public EEFrame() throws HeadlessException {
super("Elearn Editor");
JScrollPane scrollPane;
layout = new GridBagLayout();
setLayout(layout);
constraints = new GridBagConstraints();
menuBar = new EEMenuBar();
setJMenuBar(menuBar);
editor = new EETextPane();
scrollPane = new JScrollPane(editor);
scrollPane.setBorder(new TitledBorder("Editor"));
setConstraints(1, 100, GridBagConstraints.BOTH);
addComponent(scrollPane, 0, 0, 1, 1);
console = new EEConsole();
scrollPane = new JScrollPane(console);
scrollPane.setBorder(new TitledBorder("Console"));
setConstraints(1, 40, GridBagConstraints.BOTH);
addComponent(scrollPane, 1 ,0 ,1, 1);
statusBar = new EEStatusBar();
setConstraints(1, 0, GridBagConstraints.BOTH);
addComponent(statusBar, 2, 0, 1, 1);
file = null;
}
public JTextPane getTextPane() {
return this.editor;
}
public void setLines(int lines) {
this.statusBar.setLines(lines);
}
public void setWords(int words) {
this.statusBar.setJavaWords(words);
}
private void setConstraints(int weightx, int weighty, int fill) {
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fill;
}
private void addComponent(Component component, int row, int column, int width, int height) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
add(component);
}
private class EEMenuBar extends JMenuBar {
/**
*
*/
private static final long serialVersionUID = -2176624051362992835L;
private JMenu fileMenu, compilationMenu;
private JMenuItem newItem, openItem, saveItem, saveAsItem, exportItem, compileProcessItem, compileClassItem;
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/* TODO Dispay dialog with inputs class name and file path */
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);
add(fileMenu);
compilationMenu = new JMenu("Compilation");
compileProcessItem = new JMenuItem("Compile with system jdk");
compileProcessItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Compile java source code and show results in teminal(inside editor)*/
}
});
compilationMenu.add(compileProcessItem);
compileClassItem = new JMenuItem("Compile with JavaCompiler Class");
compileClassItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Call system compiler for file*/
}
});
compilationMenu.add(compileClassItem);
add(compilationMenu);
}
}
private class EETextPane extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -7437561302249475096L;
public EETextPane() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("keyword", def);
StyleConstants.setForeground(keyword, Color.BLUE);
Style literal = addStyle("literal", def);
StyleConstants.setForeground(literal, Color.ORANGE);
Style comment = addStyle("comment", def);
StyleConstants.setForeground(comment, Color.GREEN);
}
}
private class EEConsole extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -5968199559991291905L;
public EEConsole() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("error", def);
StyleConstants.setForeground(keyword, Color.RED);
Style literal = addStyle("success", def);
StyleConstants.setForeground(literal, Color.GREEN);
}
}
private class EEStatusBar extends JPanel {
/**
*
*/
private static final long serialVersionUID = 185007911993347696L;
private BoxLayout layout;
private JLabel linesLabel, lines, wordsLabel, words;
public EEStatusBar() {
super();
layout = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(layout);
linesLabel = new JLabel("Lines : ");
linesLabel.setAlignmentX(LEFT_ALIGNMENT);
add(linesLabel);
lines = new JLabel("");
lines.setAlignmentX(LEFT_ALIGNMENT);
add(lines);
add(Box.createRigidArea(new Dimension(10,10)));
wordsLabel = new JLabel("Java Words : ");
wordsLabel.setAlignmentX(LEFT_ALIGNMENT);
add(wordsLabel);
words = new JLabel("");
words.setAlignmentX(LEFT_ALIGNMENT);
add(words);
}
public void setLines(int lines) {
/*TODO set line numbers */
}
public void setJavaWords(int words) {
/*TODO set java keyword numbers*/
}
}
}
//class Main
package editor.app;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import elearning.editor.gui.EEFrame;
import elearning.editor.util.EECodeFormater;
import elearning.editor.util.EEJavaWordCounter;
import elearning.editor.util.EELineCounter;
public class EEditor {
/**
* #param args
*/
public static void main(String[] args) {
try {
// Set cross-platform Java L&F (also called "Metal")
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
//Set Motif L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
//Set Nimbus L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
//Set System L&F
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//Set GTK L&F --> Same as System L&F on Linux and Solaris\
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//Set Windows L&F --> Same as System L&F on Windows
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
EEFrame frame = new EEFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/* TODO Instatiate Threads */
/*TODO Start Threads */
}
}
Also i provide a mockup of it:
Mockup
First you should have a look at the File class. It provides you methods to create, open, modify and save files. To read files you also might want to give BufferedReader or any other Reader a shot.
Creating a file: File has the method createNewFile(), use it in combination with exists().
To open and read a file use a try-with-resource (There's actually a nice tutorial about it in the Java Manuals).
To save a file you should check out the FileWriter, it can write strings or append them to files.
For your editor you might want to replace the before mentioned BufferedReader with a LineReader, which also provides methods to get the line number. Other than that you have to figure out yourself how to number the lines. (Actually it's just googling around a lot, there will be some ideas like this one - which I didn't check in detail but it might help).
Of course for the editor you should first read the file into a string, use a formatter for it and then you can present it and reformat it when needed.
Apart from these hints I can not provide you with more detailed answers, as you can also read in the comments it would be easier if you would provide more detailed questions. You now just gave us a GUI which has almost nothing to do with your actual problems.
Show us some of your (problematic) work and we can help you, but otherwise we can not do much more than giving you some hints as I just did. So try to think about your problems, try how to ask for more precise answers and open some new questions if you want.
But don't forget to check out the site for answers, for me almost all of my questions I'd like to ask are already asked somewhere in a similar manner.
Hello again lets split work into steps ,
firstly i would like to create the new,open,save ,save as , export into pdf menu and event
below is the code that i used ,the GUI frame open correctly with new ,open,save, save as ,export into pdf labels but as action nothing happened.
Could someone write to me the correct code for that? be in mind i am very java beginner.
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
//Create the New menu item
newItem = new JMenuItem("New");
newItem.setMnemonic(KeyEvent.VK_N);
newItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.setMnemonic(KeyEvent.VK_0);
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_S);
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic(KeyEvent.VK_A);
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.setMnemonic(KeyEvent.VK_E);
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);
I'd like to know if it is possible to make a progress bar displayed on the taskbar like Windows Explorer does when there's a file operation going on?
I saw many examples, but they all involved C#.
SWT won't cut it.
I found out that this feature is included in Java 9. It is part of AWT and it is quity simple too use.
Here is short example:
import java.awt.Taskbar;
import java.awt.Taskbar.State;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* #author fxl
*/
public class TaskbarSample {
public static void main(String[] args) {
// JavaDoc:
// https://docs.oracle.com/javase/9/docs/api/java/awt/Taskbar.html
// MSDNDoc:
// https://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx
if (Taskbar.isTaskbarSupported() == false) {
return;
}
JFrame dialog = new JFrame("Test - 50%");
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
Taskbar taskbar = Taskbar.getTaskbar();
taskbar.setWindowProgressState(dialog, State.ERROR);
taskbar.setWindowProgressValue(dialog, 50);
}
}
this is now possible using SWT please review the code example:
org.eclipse.swt.snippets.Snippet336
This example will do the job:
Task bar:
Code:
import org.bridj.Platform;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;
import org.bridj.jawt.JAWTUtils;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TaskBarListDemo extends JFrame implements ActionListener, ChangeListener
{
private ITaskbarList3 list;
private JSlider slider;
private Pointer<?> hwnd;
private TaskBarListDemo() throws ClassNotFoundException
{
super("TaskbarList Demo (" + (Platform.is64Bits() ? "64 bits" : "32 bits") + ")");
list = COMRuntime.newInstance(ITaskbarList3.class);
getContentPane().add("Center", new JLabel("Hello Native Windows 7 World !"));
Box box = Box.createVerticalBox();
int min = 0;
int max = 300;
int val = (min + max / 2);
slider = new JSlider(min, max, val);
slider.addChangeListener(this);
box.add(slider);
ButtonGroup group = new ButtonGroup();
for (ITaskbarList3.TbpFlag state : ITaskbarList3.TbpFlag.values())
{
JRadioButton cb = new JRadioButton(state.name());
group.add(cb);
cb.putClientProperty(ITaskbarList3.TbpFlag.class, state);
cb.setSelected(state == ITaskbarList3.TbpFlag.TBPF_NORMAL);
cb.addActionListener(this);
box.add(cb);
}
getContentPane().add("South", box);
}
#Override
protected void finalize() throws Throwable
{
super.finalize();
list.Release();
}
public void setVisible(boolean visible)
{
super.setVisible(visible);
long hwndVal = JAWTUtils.getNativePeerHandle(this);
hwnd = Pointer.pointerToAddress(hwndVal);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void stateChanged(ChangeEvent actionEvent)
{
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
JRadioButton button = ((JRadioButton) actionEvent.getSource());
if (button.isSelected())
{
ITaskbarList3.TbpFlag flag = (ITaskbarList3.TbpFlag) button.getClientProperty(ITaskbarList3.TbpFlag.class);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
list.SetProgressState((Pointer) hwnd, flag);
}
}
public static void main(String[] arguments) throws Exception
{
TaskBarListDemo f = new TaskBarListDemo();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
Maven dependencies:
<dependencies>
<dependency>
<groupId>com.nativelibs4java</groupId>
<artifactId>bridj</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
There is no standard facility in Java for doing so, yet.
Hence you need to talk to Windows directly to do that. So you need to locate the correct Windows routine, and use JNA (probably the easiest) to invoke that routine. I do not know of a vendor or a project who has done this already.
Edit: It appears that the http://code.google.com/p/nativelibs4java/ project may do what you want.
As Java9's java.awt.Taskbar only works for old swing frames (they somehow forgot to implement this for javafx.stage.Stage) and com.nativelibs4java bridj isn't working (anymore) (see https://github.com/nativelibs4java/BridJ/issues/94) I implemented a solution using JNA 4.1.0.
Please note:
Relies on calling internal javafx api (com.sun.javafx.stage.WindowHelper) - so it might break with the next java update
It only sets the "indeterminate" progress state - but normal progress state should be possible too with some adjustments
Hope this helps.
ITaskbarList3.java
package example;
import com.sun.jna.platform.win32.Guid.IID;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
public interface ITaskbarList3 {
IID IID_ITASKBARLIST3 = new IID("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"); // from ShObjIdl.h
int TBPF_NOPROGRESS = 0;
int TBPF_INDETERMINATE = 0x1;
int TBPF_NORMAL = 0x2;
int TBPF_ERROR = 0x4;
int TBPF_PAUSED = 0x8;
HRESULT SetProgressState(HWND hwnd, int tbpFlags);
}
TaskbarList3.java
package example;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import com.sun.jna.platform.win32.COM.COMInvoker;
public final class TaskbarList3 extends COMInvoker implements ITaskbarList3 {
public TaskbarList3(Pointer pointer) {
setPointer(pointer);
}
#Override
public HRESULT SetProgressState(HWND hwnd, int tbpFlags) {
return (HRESULT) this._invokeNativeObject(
10, // magic number (gathered by trial and error)
new Object[] { this.getPointer(), hwnd, tbpFlags },
HRESULT.class);
}
}
TaskbarPeer.java
package example;
import com.sun.javafx.stage.WindowHelper;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Guid.CLSID;
import com.sun.jna.platform.win32.Ole32;
import com.sun.jna.platform.win32.W32Errors;
import com.sun.jna.platform.win32.WTypes;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.ptr.PointerByReference;
import javafx.stage.Stage;
public final class TaskbarPeer {
public static void setIndeterminateProgress(Stage stage, boolean indeterminate) {
final var peer = WindowHelper.getPeer(stage);
final long windowHandle = peer.getRawHandle();
final var clsid = new CLSID("56FDF344-FD6D-11d0-958A-006097C9A090"); // from ShObjIdl.h
final var taskbarListPointerRef = new PointerByReference();
var hr = Ole32.INSTANCE.CoCreateInstance(clsid, null, WTypes.CLSCTX_SERVER,
ITaskbarList3.IID_ITASKBARLIST3, taskbarListPointerRef);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
final TaskbarList3 taskbarList = new TaskbarList3(taskbarListPointerRef.getValue());
final var hwnd = new HWND(new Pointer(windowHandle));
final int progressState = indeterminate ? ITaskbarList3.TBPF_INDETERMINATE : ITaskbarList3.TBPF_NOPROGRESS;
hr = taskbarList.SetProgressState(hwnd, progressState);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
}
}
Sample.java
package example;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public final class Sample extends Application {
private boolean indeterminateProgressState = false;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
final Button btn = new Button("Click me!");
primaryStage.setScene(new Scene(btn));
primaryStage.sizeToScene();
primaryStage.show();
btn.setOnAction(evt -> {
indeterminateProgressState = !indeterminateProgressState;
TaskbarPeer.setIndeterminateProgress(primaryStage, indeterminateProgressState);
});
}
}
Windows exposes this through COM. I am sure a "flat DLL" call would be easier for you, but if you can get to COM you can do this. The COM interface is ITaskbarList3 (there is also an ITaskbarList4 you can use that inherits from it.) http://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx documents it. SetProgressState and SetProgressValue are the methods you will want to invoke. State is normal (green), paused (yellow), error (red), indeterminate (swooshing green) and none. On the MSDN page some community people have added details of calling this COM component from VB and C# - that might help you figure out the setup and tear down required from Java.