Open FileDialog
Hi all,
I'ld like to open the windows file explorer dialog to select a specific file like in the attachements system.
However, I don't want to copy the selected file in the Attachement folder.
I just want to get the path of the file.
Is there a solution to do that?
Thanks.
Ok thanks,
This code from William Burgos Posted Apr 22, 2008 9:40 PM works fine!
Re: Why the open file dialog form goes to SAP background.
Similar Messages
-
FileDialog in Applet throwing security exception.
I am trying to create a simple applet that a user can select a file from and then upload that file to a server somewhere. I am able to accomplish this using the JApplet class and the JFileChooser class. Everything works fine with the signed applet. However I am going to need to make it compliant with the Microsoft VM since it is for a corporate settings and those people won't have admin rights on their machines to toggle between the VM. So JApplet has been changed to Applet, JFileChooser has been changed to FileDailog and now I am getting this error:
com.ms.security.SecurityExceptionEx[com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed]: FileDialog creation denied.
at com/ms/security/permissions/UIPermission.check
at com/ms/security/PolicyEngine.deepCheck
at com/ms/security/PolicyEngine.checkPermission
at com/ms/security/StandardSecurityManager.chk
at com/ms/security/StandardSecurityManager.checkFileDialog
at java/awt/FileDialog.<init>
at com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed
at java/awt/Button.processActionEvent
at java/awt/Button.processEvent
at java/awt/Component.dispatchEventImpl
at java/awt/Component.dispatchEvent
at java/awt/EventDispatchThread.run
com.ms.security.SecurityExceptionEx[com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed]: FileDialog creation denied.
This line of code is where it blows up:
FileDialog fileDialog = new FileDialog(new Frame(), "Please choose the file to open:", FileDialog.LOAD);The jar is signed, however something of interest to note: there isn't a pop-up asking me if I would like to trust this applet when I use the Microsoft VM?
jar.exe -cvf k:\applet\lib\Importer.jar com.java.applet.il.AimsImporter/*.class
jarsigner k:\applet\lib\Importer.jar mykey
jarsigner -verify Importer.jar
Is there something that is different when doing this with the Microsoft VM?????
Help! :)I am trying to create a simple applet that a user can select a file from and then upload that file to a server somewhere. I am able to accomplish this using the JApplet class and the JFileChooser class. Everything works fine with the signed applet. However I am going to need to make it compliant with the Microsoft VM since it is for a corporate settings and those people won't have admin rights on their machines to toggle between the VM. So JApplet has been changed to Applet, JFileChooser has been changed to FileDailog and now I am getting this error:
com.ms.security.SecurityExceptionEx[com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed]: FileDialog creation denied.
at com/ms/security/permissions/UIPermission.check
at com/ms/security/PolicyEngine.deepCheck
at com/ms/security/PolicyEngine.checkPermission
at com/ms/security/StandardSecurityManager.chk
at com/ms/security/StandardSecurityManager.checkFileDialog
at java/awt/FileDialog.<init>
at com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed
at java/awt/Button.processActionEvent
at java/awt/Button.processEvent
at java/awt/Component.dispatchEventImpl
at java/awt/Component.dispatchEvent
at java/awt/EventDispatchThread.run
com.ms.security.SecurityExceptionEx[com/java/applet/il/AimsImporter/AimsImportApplet.actionPerformed]: FileDialog creation denied.
This line of code is where it blows up:
FileDialog fileDialog = new FileDialog(new Frame(), "Please choose the file to open:", FileDialog.LOAD);The jar is signed, however something of interest to note: there isn't a pop-up asking me if I would like to trust this applet when I use the Microsoft VM?
jar.exe -cvf k:\applet\lib\Importer.jar com.java.applet.il.AimsImporter/*.class
jarsigner k:\applet\lib\Importer.jar mykey
jarsigner -verify Importer.jar
Is there something that is different when doing this with the Microsoft VM?????
Help! :) -
FileDialog error :o(
Can someone please help me? I'm not sure why the class "OpenDialogFile" below is not working. I really appreciate your help.
I got this following error:
ChatClient.java:66: cannot resolve symbol
symbol : constructor FileDialog (ChatClient.OpenDialogFile,java.lang.String,int
location: class java.awt.FileDialog
fd = new FileDialog(this, "OPEN", FileDialog.LOAD);
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ChatClient {
private TextArea output;
private TextField input;
private Button sendButton;
private Button quitButton;
private Button openFileButton;
public FileDialog fd;
public ChatClient() {
output = new TextArea(10,50);
input = new TextField(50);
sendButton = new Button("Send");
quitButton = new Button("Quit");
openFileButton = new Button("Open File");
public void launchFrame() {
Frame frame = new Frame("Chat Room");
frame.setLayout(new BorderLayout());
frame.add(output,BorderLayout.WEST);
frame.add(input,BorderLayout.SOUTH);
Panel p1 = new Panel();
p1.add(sendButton);
p1.add(quitButton);
p1.add(openFileButton);
frame.add(p1,BorderLayout.CENTER);
// Attach listener to the appropriate components
sendButton.addActionListener(new SendHandler());
frame.addWindowListener(new CloseHandler());
input.addActionListener(new InputHandler());
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
openFileButton.addActionListener(new OpenDialogFile());
frame.pack();
frame.setVisible(true);
private void copyText() {
String text = input.getText();
output.setText(output.getText()+text+"\n");
input.setText("");
private class SendHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
copyText();
private class OpenDialogFile implements ActionListener {
public void actionPerformed(ActionEvent e) {
fd = new FileDialog(this, "OPEN", FileDialog.LOAD);
fd.show();
private class CloseHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
copyText();
public static void main(String[] args) {
ChatClient c = new ChatClient();
c.launchFrame();
}All constructors for FileDialog require an instance of Frame as a parent. ChatClient.OpenFileDialog apparently doesn't meet this requirement hence compiler is complaining.
DB -
Hi,
I have an applet with menu options for Opening and saving a file. Is there any way to create a file dialog for opening and saving through AWT without any usage of SWING?
Any response will be greatly appreciated!!/* <applet code="FileApplet" width="400" height="400"></applet>
* use: >appletviewer FielApplet.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileApplet extends Applet
public void init()
final TextArea textArea = new TextArea();
final FileDialog
openDialog = new FileDialog(new Frame(), "open", FileDialog.LOAD),
saveDialog = new FileDialog(new Frame(), "save", FileDialog.SAVE);
openDialog.setDirectory(".");
saveDialog.setDirectory(".");
final Button
open = new Button("open"),
save = new Button("save");
ActionListener l = new ActionListener()
String newLine = System.getProperty("line.separator");
public void actionPerformed(ActionEvent e)
Button button = (Button)e.getSource();
if(button == open)
openDialog.show();
if(openDialog.getFile() == null)
return;
File file = new File(openDialog.getFile());
BufferedReader br = null;
try
br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
textArea.setText("");
String line = "";
while((line = br.readLine()) != null)
textArea.append(line + newLine);
br.close();
catch(FileNotFoundException fnfe)
System.out.println(fnfe.getMessage());
catch(IOException ioe)
System.out.println(ioe.getMessage());
if(button == save)
saveDialog.show();
if(saveDialog.getFile() == null)
return;
File file = new File(saveDialog.getFile());
// write to file...
open.addActionListener(l);
save.addActionListener(l);
Panel northPanel = new Panel();
northPanel.add(open);
northPanel.add(save);
setLayout(new BorderLayout());
add(northPanel, "North");
add(textArea);
public static void main(String[] args)
Applet applet = new FileApplet();
Frame f = new Frame();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
f.add(applet);
f.setSize(400,400);
f.setLocation(200,200);
applet.init();
applet.start();
f.setVisible(true);
} -
Hi,
I need to save path which was last using by SaveFileDialog to saving file. But I can't find this path.
I checked all items in Environment, Application, Configuration and I not finded that.
Is there any solution to find this path?This has been previously answered
http://social.msdn.microsoft.com/Forums/vstudio/en-US/c43ddefb-1274-4ceb-9cda-c78d860b687c/how-to-get-the-last-directory-after-open-filedialog
also try this link
http://stackoverflow.com/questions/9821344/how-to-remember-the-last-path-when-insert-files-into-listbox
and you can try this
public static string GetLastOpenSaveFile(string extention)
RegistryKey regKey = Registry.CurrentUser;
string lastUsedFolder = string.Empty;
regKey = regKey.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU");
if (string.IsNullOrEmpty(extention))
extention = "html";
RegistryKey myKey = regKey.OpenSubKey(extention);
if (myKey == null && regKey.GetSubKeyNames().Length > 0)
myKey = regKey.OpenSubKey(regKey.GetSubKeyNames()[regKey.GetSubKeyNames().Length - 2]);
if (myKey != null)
string[] names = myKey.GetValueNames();
if (names != null && names.Length > 0)
lastUsedFolder = (string)myKey.GetValue(names[names.Length - 2]);
return lastUsedFolder; -
Hi.
I am trying to place image on canvas.
However the image doesn't show!!!!!!!!!!!!! :(
no error and compiles well....
private void AddTile(String image, int startx, int starty, int endx, int endy)
try{
tiles = ImageIO.read(new File(image));
catch(Exception e)
System.out.println("Image not Found");
Graphics2D a =(Graphics2D)tiles.getGraphics();
a.drawImage(tiles, 20,20,20,20,TileCanvas);
if the above function is called the image should be placed on canvas right?
TileCanvas is a canvas, and tiles is BufferedImage.
just in case I'll put my source code followed by this
* MapEditor.java
* Created on 2006�� 7�� 20�� (��), ���� 11:48
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
import java.io.*;
* @author SeiKwon
public class EditorComponent extends javax.swing.JFrame
private java.awt.Button AddTile;
private java.awt.Button DeleteTile;
private javax.swing.JMenu FileMenu;
private javax.swing.JMenuItem LoadFile;
private javax.swing.JPanel ManageTilePanel;
private java.awt.Canvas MapCanvas;
private javax.swing.JMenuBar MenuBar;
private javax.swing.JMenuItem SaveFile;
private javax.swing.JScrollPane ShowMapScroll;
private java.awt.Canvas TileCanvas;
private javax.swing.JScrollPane TileScroll;
private BufferedImage tiles;
private int tilecount = 0;
/** Creates new form MapEditor */
public EditorComponent()
initComponents();
AddTile("test.jpg", 0, 0, 10, 10);
private void initComponents()
ManageTilePanel = new javax.swing.JPanel();
TileScroll = new javax.swing.JScrollPane();
TileCanvas = new java.awt.Canvas();
AddTile = new java.awt.Button();
DeleteTile = new java.awt.Button();
ShowMapScroll = new javax.swing.JScrollPane();
MapCanvas = new java.awt.Canvas();
MenuBar = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
SaveFile = new javax.swing.JMenuItem();
LoadFile = new javax.swing.JMenuItem();
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ManageTilePanel.setLayout(null);
ManageTilePanel.setBorder(new javax.swing.border.TitledBorder("Tiles"));
TileCanvas.setBackground(new java.awt.Color(255, 255, 255));
TileScroll.setViewportView(TileCanvas);
ManageTilePanel.add(TileScroll);
TileScroll.setBounds(10, 22, 100, 230);
AddTile.setLabel("Add");
ManageTilePanel.add(AddTile);
AddTile.setBounds(10, 260, 50, 26);
DeleteTile.setLabel("Delete");
ManageTilePanel.add(DeleteTile);
DeleteTile.setBounds(60, 260, 50, 26);
getContentPane().add(ManageTilePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 10, 119, 290));
ManageTilePanel.getAccessibleContext().setAccessibleName("TilesPanel");
MapCanvas.setBackground(new java.awt.Color(255, 255, 255));
MapCanvas.addMouseListener(new java.awt.event.MouseAdapter()
public void mouseEntered(java.awt.event.MouseEvent evt)
MapCanvasMouseEntered(evt);
ShowMapScroll.setViewportView(MapCanvas);
getContentPane().add(ShowMapScroll, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 10, 290, 290));
FileMenu.setText("File");
FileMenu.setContentAreaFilled(false);
SaveFile.setIcon(new javax.swing.ImageIcon("D:\\java\\MapEditor\\Image\\Save16.gif"));
SaveFile.setText("Save");
SaveFile.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
SaveFileActionPerformed(evt);
FileMenu.add(SaveFile);
LoadFile.setIcon(new javax.swing.ImageIcon("D:\\java\\MapEditor\\Image\\Open16.gif"));
LoadFile.setText("Load");
LoadFile.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
LoadFileActionPerformed(evt);
FileMenu.add(LoadFile);
MenuBar.add(FileMenu);
setJMenuBar(MenuBar);
pack();
private void MapCanvasMouseEntered(java.awt.event.MouseEvent evt)
Cursor cursorshape = MapCanvas.getCursor();
MapCanvas.setCursor(cursorshape.getPredefinedCursor(CROSSHAIR_CURSOR));
private void AddTile(String image, int startx, int starty, int endx, int endy)
try{
tiles = ImageIO.read(new File(image));
catch(Exception e)
System.out.println("Image not Found");
Graphics2D a =(Graphics2D)tiles.getGraphics();
a.drawImage(tiles, 20,20,20,20,TileCanvas);
private void LoadFileActionPerformed(java.awt.event.ActionEvent evt)
FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
//fd.setFile("*.map");
fd.setDirectory(".");
fd.setVisible(true);
String filename = fd.getFile();
System.out.println(filename);
private void SaveFileActionPerformed(java.awt.event.ActionEvent evt)
FileDialog fd = new FileDialog(this, "Save", FileDialog.SAVE);
//fd.setFile("*.map");
//fd.setFilenameFilter("*.map"); // HOW TO USE?????????????
fd.setDirectory(".");
fd.setVisible(true);
String filename = fd.getFile();
System.out.println(filename);
public static void main(String args[])
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
new EditorComponent().setVisible(true);
}You have at least two problems.
1) You are mixing AWT and Swing. Instead of using a Canvas you should use either a JComponent or a JPanel.
2) In Swing, drawing such are you are doing should be done within the paintComponent(Graphics g) method using the Graphics provided as an argument to the method.
P.S. I can't test you code because for some reason you feal the need to use a NetBeans specific layout manager. -
Executing UNIX command in Java
I am having problems executing a command in Java. Here's the code I have for executing:
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((display = input.readLine()) != null)
num_1 = Double.parseDouble(display);
percent = (num_1 * 100) / (50000000);
flip = 1;
catch(IOException e)
e.printStackTrace();
System.exit(1);
Now, when I run the script, I receive the following errors:
Exception occurred during event dispatching:
java.security.AccessControlException: access denied (java.io.FilePermission /Netadmin/UCDSNMP/bin/snmpdelta execute)
at java.lang.Throwable.fillInStackTrace(Native Method)
at java.lang.Throwable.fillInStackTrace(Compiled Code)
at java.lang.Throwable.<init>(Compiled Code)
at java.lang.Exception.<init>(Compiled Code)
at java.lang.RuntimeException.<init>(RuntimeException.java:47)
at java.lang.SecurityException.<init>(SecurityException.java:39)
at java.security.AccessControlException.<init>(AccessControlException.java:57)
at java.security.AccessControlContext.checkPermission(Compiled Code)
at java.security.AccessController.checkPermission(Compiled Code)
at java.lang.SecurityManager.checkPermission(Compiled Code)
at java.lang.SecurityManager.checkExec(SecurityManager.java:789)
at java.lang.Runtime.exec(Compiled Code)
at java.lang.Runtime.exec(Compiled Code)
at java.lang.Runtime.exec(Runtime.java:152)
at snmp.actionPerformed(Compiled Code)
at java.awt.Button.processActionEvent(Button.java:308)
at java.awt.Button.processEvent(Button.java:281)
at java.awt.Component.dispatchEventImpl(Compiled Code)
at java.awt.Component.dispatchEvent(Compiled Code)
at java.awt.EventQueue.dispatchEvent(Compiled Code)
at java.awt.EventDispatchThread.pumpOneEvent(Compiled Code)
at java.awt.EventDispatchThread.pumpEvents(Compiled Code)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:83)
The user is entering the parameters for the UNIX command from a Java applet. Everything looks right, but I can't seem to run the file? Please help! All is appreciated.
Jason Banks
Northeastern UniversitySorry, this is a bug that I've reported -- see Sun's response and my original report (along with how to get around the problem) shown below:
Hi Vira Van.,
The bug you have reported is a duplicate of Bug ID: 4522533.
Thank you for providing us with additional information
that can be used in the resolution of this bug.
This bug can be monitored via the the Java Developer
Connection Bug Parade at:
http://developer.java.sun.com/developer/bugParade/index.jshtml
The Java Developer Connection is a free channel that is
maintained by staff here at Sun. Access this web page to join:
http://developer.java.sun.com/servlet/RegistrationServlet
The home page for the JDC is:
http://java.sun.com/jdc
Regards,
Girish
----------------- Original Bug Report-------------------
category : java
release : 1.4
subcategory : jar
type : bug
synopsis : signed applet: bad major version number on NN4.79 and ClassNotFound in IE5.5
description : FULL PRODUCT VERSION :
java version "1.4.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
FULL OPERATING SYSTEM VERSION : Windows 98 [Version
4.10.2222]
ADDITIONAL OPERATING SYSTEMS :
BROWSERS: Netscape Navigator 4.79
: Internet Explorer 5.5
EXTRA RELEVANT SYSTEM CONFIGURATION :
Applet failed to start in Netscape, the following error
message appeared in the Java Console:
Netscape Communications Corporation -- Java 1.1.5
Type '?' for options.
Symantec Java! ByteCode Compiler Version 210.065
Copyright (C) 1996-97 Symantec Corporation
# Applet exception: error: java.lang.ClassFormatError: Bad
major version number
java.lang.ClassFormatError: Bad major version number
at java.lang.ClassLoader.defineClass(Compiled Code)
at netscape.applet.AppletClassLoader.findClass(Compiled
Code)
at netscape.applet.AppletClassLoader.loadClass1(Compiled
Code)
* at netscape.applet.AppletClassLoader.loadClass(Compiled
Code)
at netscape.applet.AppletClassLoader.loadClass(Compiled
Code)
at
netscape.applet.DerivedAppletFrame$LoadAppletEvent.dispatch(
Compiled Code)
at
java.awt.EventDispatchThread$EventPump.dispatchEvents(Compil
ed Code)
at java.awt.EventDispatchThread.run(Compiled Code)
at
netscape.applet.DerivedAppletFrame$AppletEventDispatchThread
.run(Compiled Code)
The same applet
A DESCRIPTION OF THE PROBLEM :
Unable to run signed applet with Netscape 4.79 and IE5.5
native JVM.
REGRESSION. Last worked in version 1.3.1
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1.compile program and copy class files to a temp directory
2.sign the applet for Netscape as follows:
signtool -k aok -d \progra~1\netscape\users\viravan -Z
FIO.jar temp
3.sign the applet for Internet Explorer as follows:
cabarc -p n FileIO.cab FileIO*.class
setreg 1 true
makecert -sk aok -n "CN=aok" aok.cer
cert2spc aok.cer aok.spc
signcode -j javasign.dll -jp LOWX -spc aok.spc -k aok
FileIO.cab
Run the applet with the following HTML file:
<html><head><Title>Self-Signed Applet</Title>
<script>
document.layers ? parm=1 : parm=0;
</script>
<body>
This file I/O applet lets you read and write to the user's
local disk.<br>
<br>
<script>
document.writeln('<APPLET CODE = "FileIO" CODEBASE = "."
ARCHIVE = "FIO.jar" WIDTH = 10 HEIGHT = 10 NAME = "JSF">');
document.writeln('<param name="Netscape"
value="'+parm+'">');
document.writeln('<param name="cabbase"
value="FileIO.cab">');
document.writeln('</APPLET>');
</script>
</body>
</html>
EXPECTED VERSUS ACTUAL BEHAVIOR :
A frame with a textarea and some buttons should popup in the
center of the screen.
ERROR MESSAGES/STACK TRACES THAT OCCUR :
Applet signed with signtool failed to start in Netscape, the following error
message appeared in the Java Console:
Netscape Communications Corporation -- Java 1.1.5
Type '?' for options.
Symantec Java! ByteCode Compiler Version 210.065
Copyright (C) 1996-97 Symantec Corporation
# Applet exception: error: java.lang.ClassFormatError: Bad major version number
java.lang.ClassFormatError: Bad major version number
at java.lang.ClassLoader.defineClass(Compiled Code)
at netscape.applet.AppletClassLoader.findClass(Compiled Code)
at netscape.applet.AppletClassLoader.loadClass1(Compiled Code)
* at netscape.applet.AppletClassLoader.loadClass(Compiled Code)
at netscape.applet.AppletClassLoader.loadClass(Compiled Code)
at netscape.applet.DerivedAppletFrame$LoadAppletEvent.dispatch(Compiled Code)
at java.awt.EventDispatchThread$EventPump.dispatchEvents(Compiled Code)
at java.awt.EventDispatchThread.run(Compiled Code)
at netscape.applet.DerivedAppletFrame$AppletEventDispatchThread.run(Compiled
Code)
The same applet signed with signcode failed to start in Internet explorer, the
error message in the Java Console is:
Error loading class: FileIO
java.lang.NoClassDefFoundError
java.lang.ClassNotFoundException: FileIO
at com/ms/vm/loader/URLClassLoader.loadClass
at com/ms/vm/loader/URLClassLoader.loadClass
at com/ms/applet/AppletPanel.securedClassLoad
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.run
at java/lang/Thread.run
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FileIO extends Applet implements ActionListener {
public static void main(String[] args) {
new FileIO();
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
public void init() {
String tmp=getParameter("Netscape");
if (tmp!=null) {
if (tmp.equals("1")) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalFileAccess");
NS=true;
} catch (Throwable exception) {}
new FileIO();
F.setResizable(false);
public void stop() {
F.dispose();
public FileIO() {
newline=System.getProperty("line.separator");
F.setLayout(new BorderLayout(0,0));
String line,inbuf="";
String newline=System.getProperty("line.separator");
text=new TextArea(inbuf,24,80,TextArea.SCROLLBARS_BOTH);
text.setFont(new Font("Courier",Font.PLAIN,12));
text.setBackground(Color.cyan);
text.setForeground(Color.black);
F.add("Center",text);
Panel pan=new Panel();
pan.setLayout(new FlowLayout(1,0,0));
pan.setBackground(Color.yellow);
TF=new TextField(40);
TF.setFont(new Font("Courier",Font.PLAIN,12));
pan.add(TF);
OP=new Button("Open");
OP.addActionListener(this);
pan.add(OP);
FS=new Button("Save");
FS.addActionListener(this);
pan.add(FS);
SA=new Button("Save-As");
SA.addActionListener(this);
pan.add(SA);
reset=new Button("Reset");
reset.addActionListener(this);
pan.add(reset);
F.add("South",pan);
F.pack();
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
Dimension size=F.getSize();
int X=(screen.width-size.width)/2;
int Y=(screen.height-size.height)/2;
F.setLocation(X,Y);
F.setVisible(true);
public void actionPerformed(ActionEvent event) {
String tmp="";
String O=text.getText();
StringTokenizer tkn=new StringTokenizer(O,newline);
int ntkn=tkn.countTokens();
Object ev=event.getSource();
if (ev.equals(OP)) {
FileDialog fd=new FileDialog(F,"File to open",FileDialog.LOAD);
fd.setFile("*.java");
fd.show();
tmp=fd.getDirectory();
if (fd.getFile()==null) {text.requestFocus(); return;}
tmp+=fd.getFile();
TF.setText(tmp);
try {
if (NS)
{netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");}
BufferedReader reader=new BufferedReader(new FileReader(tmp));
String line;
String crlf="";
tmp="";
while ((line=reader.readLine())!=null) {
tmp+=crlf+line;
crlf="\n";
reader.close();
text.setText(tmp);
} catch (Throwable e) {
e.printStackTrace();
} else if (ev.equals(FS) || ev.equals(SA)) {
try {
if (ev.equals(SA)) {
FileDialog fd=new FileDialog(F,"File to save",FileDialog.SAVE);
fd.setFile("*.java");
fd.show();
tmp=fd.getDirectory();
tmp+=fd.getFile();
} else {
tmp=TF.getText();
if (tmp.length()==0) {text.requestFocus(); return;}
if (tmp.indexOf(".java")<0) tmp+=".java";
TF.setText(tmp);
if (NS)
{netscape.security.PrivilegeManager.enablePrivilege("UniversalFileWrite");}
FileOutputStream fos=new FileOutputStream(tmp);
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new
DataOutputStream(fos)));
for (int i=0;i<ntkn;i++) out.write(tkn.nextToken()+newline);
out.flush();
out.close();
if (NS)
{netscape.security.PrivilegeManager.revertPrivilege("UniversalFileWrite");}
System.out.println(tmp+" saved");
} catch (Throwable e) {
e.printStackTrace();
} else if (ev.equals(reset)) {
text.setText("");
TF.setText("");
text.requestFocus();
private String replace(String input, String srch, String repl) {
int i=input.indexOf(srch);
while (i>=0) {
input=input.substring(0,i)+repl+input.substring(i+srch.length());
i=input.indexOf(srch);
return input;
private Button OP,FS,SA,reset,TB;
private boolean newLine,NS=false;
private TextArea text;
private TextField TF;
private final char NL='\n';
private String content,newline;
private static Frame F=new Frame("FileIO");
---------- END SOURCE ----------
CUSTOMER WORKAROUND :
build the signed applet with SDK1.3.1 or make it a signed
applet that uses Java Plugin 1.4.0 (i.e., sign it with jarsigner).
workaround :
suggested_val :
cust_name : Vira Van.
dateCreated : 2002-03-24 19:52:18.4
dateEvaluated : 2002-04-01 18:48:10.858 -
Need some pointers please :)
Hi,
I've been given an application which I have to modify to edit a 'raw' image, so far I have been able to implement the loading of the image, but I am stuck with editing it.
The there are 3 classes to the application, rawimage, skelappipcanvas and skelappipframe.
So far as to my understanding, the rawimage class loads the raw image into a pixel array and then converts it into an image which is then displayed on the canvas. The frame contains the menu.
What I have to do is edit the picture, by manipulating the array, adding 5 to all values in the array for example. I understand that the best way to do that is to create a function and call that function when I select the menu option.
My problem is that im not sure how to implement the editing of the array..any pointers would be greatly appreciated. I have posted the code below..sorry for the amount of text.
RawImage Class:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class RawImage
public int imWidth = 640; // default image width
public int imHeight = 480; // default image height
public int imDepth = 256; // default image depth
public short rawPixelArray2D[][]; // array of image pixels
// (to contain grey-scale bitmap)
private Image dispIm; // display image
private int imConvBuf[]; // buffer for converting between raw image bitmap and display image object
// buffer entries are pixel colour values computed using colour model
private ColorModel colMod = ColorModel.getRGBdefault(); //colour model of display image
* Constructs and initialises a grey-scale image object
* @param filename name of input file.
* @since JDK1.1
public RawImage(String filename)
rawPixelArray2D = new short[imHeight][imWidth]; // create pixel array
imConvBuf = new int[imHeight * imWidth];
load(filename); // read data from file into raw bitmap array
arrayToDispImage(); // convert raw bitmap into display image object
* Constructs and initialises a grey-scale image object
* @param rawGreyBitMap 2D array containing raw bitmap.
* @param width width of 2D array.
* @param height height of 2D array.
* @since JDK1.1
public RawImage(short rawGreyBitMap[][], int width, int height)
rawPixelArray2D = rawGreyBitMap;
imWidth = width;
imHeight = height;
imConvBuf = new int[imHeight * imWidth];
arrayToDispImage(); // convert raw bitmap into display image object
* Displays image
* @param none.
* @since JDK1.1
public void display(Graphics gc)
gc.drawImage(dispIm, 0, 0, null);
* Loads image from file
* @param filename name of input file.
* @since JDK1.1
public void load(String filename)
// load pixel array from file
try
DataInputStream inputStream =
new DataInputStream(new FileInputStream(filename));
try
// read each byte from binary file into raw bitmap
for (int row = 0; row < imHeight; ++row)
for (int col = 0; col < imWidth; ++col)
rawPixelArray2D[row][col] = (short) inputStream.readUnsignedByte();
catch(EOFException e)
System.out.println("File shorter than expected. End of reading from file " + filename);
inputStream.close();
catch(FileNotFoundException e)
System.out.println("Cannot find file " + filename);
catch(IOException e2)
System.out.println("Error reading input from file " + filename);
* Saves image to file
* @param filename name of input file.
* @since JDK1.1
public void save(String filename)
// save pixel array to file
try
DataOutputStream outputStream =
new DataOutputStream(new FileOutputStream(filename));
// write each byte from raw bitmap into binary file
for (int row = 0; row < imHeight; ++row)
for (int col = 0; col < imWidth; ++col)
outputStream.writeByte( (int) rawPixelArray2D[row][col] );
outputStream.close();
catch(IOException e)
System.out.println("Error writing output to file " + filename);
* Converts raw grey pixel array into display Image object
* @param none.
* @since JDK1.1
private void arrayToDispImage()
for (int row = 0; row < imHeight; row++)
int colOffset = row * imWidth;
for (int col = 0; col < imWidth; col++)
imConvBuf[col + colOffset] =
0xFF000000 | (rawPixelArray2D[row][col] << 16)
| (rawPixelArray2D[row][col] << 8)
| rawPixelArray2D[row][col];
MemoryImageSource MemSource = new MemoryImageSource(imWidth, imHeight, colMod,
imConvBuf, 0, imWidth);
dispIm = Toolkit.getDefaultToolkit().createImage(MemSource);
SkelAppIPCanvas class:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SkelAppIPCanvas extends Canvas
private int xCanvasCentre = 0; // coordinates of centre of canvas
private int yCanvasCentre = 0;
private RawImage image = null; // image
* Constructs and initialises a canvas object
* @param none.
* @since JDK1.1
public SkelAppIPCanvas()
super(); // call parent's constructor
addListenersToCanvas(); // add event listeners
* Adds listeners to canvas
* @param none.
* @since JDK1.1
public void addListenersToCanvas()
// add mouse listener
addMouseListener( // use argument which is an object of an anonymous subclass of MouseAdapter
new MouseAdapter()
public void mousePressed(MouseEvent event)
serviceMouseEvent(MouseEvent.MOUSE_PRESSED, event.getX(), event.getY());
public void mouseClicked(MouseEvent event)
serviceMouseEvent(MouseEvent.MOUSE_CLICKED, event.getX(), event.getY());
public void mouseReleased(MouseEvent event)
serviceMouseEvent(MouseEvent.MOUSE_RELEASED, event.getX(), event.getY());
// add mouse motion listener
addMouseMotionListener( // use argument which is an object of an anonymous subclass of MouseMotionAdapter
new MouseMotionAdapter()
public void mouseDragged(MouseEvent event)
serviceMouseEvent(MouseEvent.MOUSE_DRAGGED, event.getX(), event.getY());
public void mouseMoved(MouseEvent event)
serviceMouseEvent(MouseEvent.MOUSE_MOVED, event.getX(), event.getY());
// add key listener
addKeyListener( // use argument which is an object of an anonymous subclass of KeyAdapter
new KeyAdapter()
public void keyPressed(KeyEvent event)
// service keyboard event
serviceKeyEvent(event);
* Gets the coordinates of the centre of the canvas.
* @param none.
* @since JDK1.1
public Point getCanvasCentre()
updateCanvasCentre();
return new Point(xCanvasCentre, yCanvasCentre);
* Updates the coordinates of the centre of the canvas.
* @param none.
* @since JDK1.1
public void updateCanvasCentre()
Dimension canvasDimensions = getSize();
xCanvasCentre = canvasDimensions.width / 2;
yCanvasCentre = canvasDimensions.height / 2;
* |
* PAINT MESSAGE SERVICING |
* |
// CUSTOMISE THE "TO DO" COMMENTS AS APPROPRIATE
* Updates canvas area.
* @param graphicsContext a Graphics object.
* @since JDK1.1
public void paint(Graphics graphicsContext)
// Display currently loaded image
if (image != null)
image.display(graphicsContext);
* |
* "ARROW KEYS" SERVICING |
* |
// CUSTOMISE THE "TO DO" COMMENTS AS APPROPRIATE
* Services "arrow keys" events (NOTE: for some reason the key listener gets
* decoupled from the canvas object after the window has been minimised.)
* @param event a key-event object.
* @since JDK1.1
public void serviceKeyEvent(KeyEvent event)
switch(event.getKeyCode())
case KeyEvent.VK_UP:
// TO DO: service up-key as approriate
break;
case KeyEvent.VK_LEFT:
// TO DO: service left-key as approriate
break;
case KeyEvent.VK_DOWN:
// TO DO: service down-key as approriate
break;
case KeyEvent.VK_RIGHT:
// TO DO: service right-key as approriate
break;
default:
// TO DO: service "all-other-keys" as approriate
break;
* |
* MOUSE SERVICING |
* |
// CUSTOMISE THE "TO DO" COMMENTS AS APPROPRIATE
* Services mouse events.
* @param eventID ID of mouse event.
* @param xMousePosition x coordinate of cursor at occurence mouse event.
* @param yMousePosition y coordinate of cursor at occurence mouse event.
* @since JDK1.1
public void serviceMouseEvent(int eventID, int xMousePosition, int yMousePosition)
switch(eventID)
case MouseEvent.MOUSE_CLICKED:
// TO DO: service MOUSE_CLICKED as approriate
break;
case MouseEvent.MOUSE_DRAGGED:
// TO DO: service MOUSE_DRAGGED as approriate
break;
case MouseEvent.MOUSE_PRESSED:
// TO DO: service MOUSE_PRESSED as approriate
break;
case MouseEvent.MOUSE_RELEASED:
// TO DO: service MOUSE_RELEASED as approriate
break;
case MouseEvent.MOUSE_MOVED:
// TO DO: service MOUSE_MOVED as approriate
break;
default:
// TO DO: service "all-other-mouse-states" as approriate
break;
* Loads image from file.
* @param filename name of the file.
* @since JDK1.1
public void loadRawImage(String filename)
image = new RawImage(filename); // load raw image from file
repaint(); // trigger a screen refresh for displaying image just loaded
* Saves image to file.
* @param filename name of the file.
* @since JDK1.1
public void saveRawImage(String filename)
// save raw image to file
image.save(filename);
SkelAppIPFrame class:
import java.awt.*;
import java.awt.event.*;
public class SkelAppIPFrame extends Frame
// drawing area
private SkelAppIPCanvas displayCanvas;
// menu items
private MenuItem fileOpen, saveAs, exitApp,
/* VARIABLES FOR STUDENT MENUS */
studentMenu1_1, studentMenu1_2, studentMenu1_3, studentMenu1_4,
studentMenu2_1_1, studentMenu2_1_2, studentMenu2_1_3,
studentMenu2_2_1, studentMenu2_2_2;
/* END OF VARIABLES FOR STUDENT MENUS */
//image
private RawImage image = null;
* Creates a window
* @param commandArgs command line arguments for application.
* @since JDK1.1
public static void main(String [] commandArgs)
new SkelAppIPFrame();
* Constructs a window (frame + canvas + menu)
* @param none.
* @since JDK1.1
public SkelAppIPFrame()
// set frame title
super("IP Programming Framework");
// add window listener
addWindowListenerToFrame();
// add menu
addMenu();
// set frame size
Dimension screenDimensions = getToolkit().getScreenSize();
setSize(screenDimensions.width, screenDimensions.height);
// add canvas in centre of frame
displayCanvas = new SkelAppIPCanvas();
add("Center", displayCanvas);
// show frame
show();
* Gets the name of the input file entered by the user.
* @param none.
* @since JDK1.0
private String getInputFileName()
return getFileName("File Open", FileDialog.LOAD);
* Gets the name of the output file entered by the user.
* @param none.
* @since JDK1.0
private String getOutputFileName()
return getFileName("File Save", FileDialog.SAVE);
* Gets the name of the input or output file entered by the user.
* @param title a string specifying the title of the dialog box.
* @param mode an integer specifying the mode (file open or save dialog box).
* @since JDK1.0
private String getFileName(String title, int mode)
FileDialog fileDlg = new FileDialog(this, title, mode);
fileDlg.setDirectory("");
fileDlg.setFile("");
fileDlg.show();
String folderName = fileDlg.getDirectory();
String fileNameBuffer = fileDlg.getFile();
String fileName = null;
// get file name if it has been specified by user
if (fileNameBuffer != null)
fileName = folderName + fileNameBuffer;
return fileName;
* Adds a window listener to the window frame
* @param none.
* @since JDK1.1
public void addWindowListenerToFrame()
addWindowListener( // use argument which is an object of an anonymous subclass of WindowAdapter
new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
* Adds a menu to the window frame
* @param none.
* @since JDK1.1
public void addMenu()
// create and set menu bar
MenuBar frameMenuBar = new MenuBar();
setMenuBar(frameMenuBar);
// create pull-down menu and attach to menu bar
Menu fileMenu = new Menu("File");
frameMenuBar.add(fileMenu);
// create menu items for "File" pull-down menu
fileOpen = new MenuItem( "Open ...", new MenuShortcut(KeyEvent.VK_O) );
saveAs = new MenuItem( "Save As ...", new MenuShortcut(KeyEvent.VK_S) );
exitApp = new MenuItem( "Exit", new MenuShortcut(KeyEvent.VK_X) );
// attach menu items to pull-down menu
fileMenu.add(fileOpen);
fileMenu.addSeparator();
fileMenu.add(saveAs);
fileMenu.addSeparator();
fileMenu.add(exitApp);
// create menu-action listener, and add it to each menu item
SkelApp2DGMenuDispatcher menuListener = new SkelApp2DGMenuDispatcher();
fileOpen.addActionListener(menuListener);
saveAs.addActionListener(menuListener);
exitApp.addActionListener(menuListener);
* |
* MENUS |
* |
// STRINGS THAT WILL APPEAR ON THE MENU
// TODO: CUSTOMISE THE TEXT BETWEEN DOUBLE QUOTES AS APPROPRIATE
String studentMenu1Label = "Menu 1",
studentMenu1_1Label = "lighten",
studentMenu1_2Label = "Your Menu 1.2",
studentMenu1_3Label = "Your Menu 1.3",
studentMenu1_4Label = "Your Menu 1.4",
studentMenu2Label = "Student Menu 2",
studentMenu2_1Label = "Your Menu 2.1",
studentMenu2_1_1Label = "Your Menu 2.1.1",
studentMenu2_1_2Label = "Your Menu 2.1.2",
studentMenu2_1_3Label = "Your Menu 2.1.3",
studentMenu2_2Label = "Your Menu 2.2",
studentMenu2_2_1Label = "Your Menu 2.2.1",
studentMenu2_2_2Label = "Your Menu 2.2.2";
// END OF MENU STRINGS
// create pull-down menus and attach to menu bar
Menu studentMenu1 = new Menu(studentMenu1Label);
Menu studentMenu2 = new Menu(studentMenu2Label);
frameMenuBar.add(studentMenu1);
frameMenuBar.add(studentMenu2);
// create menu items for <studentMenu1> pull-down menu
studentMenu1_1 = new MenuItem( studentMenu1_1Label, new MenuShortcut(KeyEvent.VK_U) );
studentMenu1_2 = new MenuItem( studentMenu1_2Label, new MenuShortcut(KeyEvent.VK_V) );
studentMenu1_3 = new MenuItem( studentMenu1_3Label, new MenuShortcut(KeyEvent.VK_W) );
studentMenu1_4 = new MenuItem( studentMenu1_4Label, new MenuShortcut(KeyEvent.VK_X) );
// create cascading menus for <studentMenu2> pull-down menu
Menu studentMenu2_1 = new Menu(studentMenu2_1Label);
Menu studentMenu2_2 = new Menu(studentMenu2_2Label);
// create menu items for <studentMenu2 | studentMenu2_1> cascaded menu
studentMenu2_1_1 = new MenuItem( studentMenu2_1_1Label, new MenuShortcut(KeyEvent.VK_R) );
studentMenu2_1_2 = new MenuItem( studentMenu2_1_2Label, new MenuShortcut(KeyEvent.VK_S) );
studentMenu2_1_3 = new MenuItem( studentMenu2_1_3Label, new MenuShortcut(KeyEvent.VK_T) );
// attach menu items to <studentMenu2 | studentMenu2_1> cascaded menu
studentMenu2_1.add(studentMenu2_1_1);
studentMenu2_1.add(studentMenu2_1_2);
studentMenu2_1.add(studentMenu2_1_3);
// create cascading menus for <studentMenu2 | studentMenu2_2> cascaded menu
studentMenu2_2_1 = new MenuItem( studentMenu2_2_1Label, new MenuShortcut(KeyEvent.VK_H) );
studentMenu2_2_2 = new MenuItem( studentMenu2_2_2Label, new MenuShortcut(KeyEvent.VK_N) );
// attach menu items to <studentMenu2 | studentMenu2_2> cascaded menu
studentMenu2_2.add(studentMenu2_2_1);
studentMenu2_2.add(studentMenu2_2_2);
// attach menu items and cascaded menus to pull-down menus
studentMenu1.add(studentMenu1_1);
studentMenu1.add(studentMenu1_2);
studentMenu1.add(studentMenu1_3);
studentMenu1.add(studentMenu1_4);
studentMenu2.add(studentMenu2_1);
studentMenu2.add(studentMenu2_2);
// add action listener for menu items
studentMenu1_1.addActionListener(menuListener);
studentMenu1_2.addActionListener(menuListener);
studentMenu1_3.addActionListener(menuListener);
studentMenu1_4.addActionListener(menuListener);
studentMenu2_1_1.addActionListener(menuListener);
studentMenu2_1_2.addActionListener(menuListener);
studentMenu2_1_3.addActionListener(menuListener);
studentMenu2_2_1.addActionListener(menuListener);
studentMenu2_2_2.addActionListener(menuListener);
* Defines menu dispatcher (as an inner class)
* @since JDK1.1
class SkelApp2DGMenuDispatcher implements ActionListener
* Receives menu-selection events and forwards them for servicing.
* @param event an event.
* @since JDK1.1
public void actionPerformed(ActionEvent event)
if ( event.getSource() instanceof MenuItem )
MenuItem menuItemObject = (MenuItem) event.getSource();
serviceMenuEvent(menuItemObject);
* Services menu-selection event.
* @param menuItemObject a MenuItem object.
* @since JDK1.1
public void serviceMenuEvent(MenuItem menuItemObject)
* |
* MENU SERVICING |
* |
// CUSTOMISE THE "TO DO" COMMENTS AS APPROPRIATE
if (menuItemObject == fileOpen)
String fileName = null;
// launch file-open dialog box and load file if file name has been specified
if ( ( fileName = getInputFileName() ) != null )
// load image from file
displayCanvas.loadRawImage(fileName);
else if (menuItemObject == saveAs)
String fileName = null;
// launch file-save dialog box and save file if file name has been specified
if ( ( fileName = getOutputFileName() ) != null )
// save image to file
displayCanvas.saveRawImage(fileName);
else if (menuItemObject == exitApp)
System.exit(0); // confirmation message box not implemented
else if (menuItemObject == studentMenu1_1)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu1_1>
System.out.println("test");
else if (menuItemObject == studentMenu1_2)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu1_2>
else if (menuItemObject == studentMenu1_3)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu1_3>
else if (menuItemObject == studentMenu1_4)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu1_4>
else if (menuItemObject == studentMenu2_1_1)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu2_1_1>
else if (menuItemObject == studentMenu2_1_2)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu2_1_2>
else if (menuItemObject == studentMenu2_1_3)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu2_1_3>
else if (menuItemObject == studentMenu2_2_1)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu2_2_1>
else if (menuItemObject == studentMenu2_2_2)
// TO DO: ADD RELEVANT MENU SERVICING CODE HERE
// FOR <studentMenu2_2_2>
}Recommendations include:
* Use code tags when posting code. No one likes to look at unformatted code. To do this, either highlight your code block and press the "code" button at the top above the message block or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
// your code block goes here
[/code]* Post a much smaller amount of code. I seriously doubt that anyone will look at your code given its length.
* But still if possible, have your posted code be compilable and able to demonstrate your problem. This is called an SSCCE and you can read up on it here:
http://homepage1.nifty.com/algafield/sscce.html
Question: Why are you using AWT components and not Swing? -
I Know that for using XML Interop I have to produce an XML file like that :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jdeRequest comment="" environment="PY812" pwd="xxxx" role="*ALL" session="" sessionidle="" type="callmethod" user="BUFFETAUD">
<callMethod app="" name="LaunchBatchApplication">
<returnCode code="0"/>
<params>
<param name="szReport">R0006P</param>
<param name="szVersionJDE">XJDE0001</param>
<param name="cSynch">0</param>
<param name="cPrintPreview">0</param>
<param name="szDataSourceOverride"/>
<param name="mnServerJobNumber">0</param>
<param name="cReturn"/>
<param name="cJDELogging">0</param>
<param name="cTracing">0</param>
<param name="cUBELoggingLevel">1</param>
<param name="szJobQueue">QBATCH</param>
</params>
</callMethod>
</jdeRequest>
We are under JDE 8.12 Tools 8.98.2.3 and an AS400 V6R1.
We are now using Oracle Data Ingrator 11G.
I would like to know how and where to send using ODI this XML to make JDE execute my call?This is from Oracle.
Please mark the answer as correct if you think it's right.
JXMLTool (EnterpriseOne 8.98)
Introduction:
The JXMLTool is a GUI tool developed by Global Support Services to submit XML requests to ERP enterprise servers. The tool can be used to verify the integrity of the ERP services (kernel configuration, BSFN processing, among others) when testing inbound integrations from XPI and/or other third party systems to ERP. This document contains instructions on how to install and configure the tool.
Installation and Configuration:
1) Verify that a supported Java Development Kit (JDK) is installed in the workstation to be used in the test (for example, verify that JDK 1.4.2 is installed).
Note: It is recommended that the workstation also have an EnterpriseOne 8.12 full client package installed.
2) Create a new directory in the workstation (for example, C:\JXMLTool).
3) Copy the following files from the Deployment server to the directory created in step 2:
e812\system\classes\Base_JAR.jar
e812\system\classes\JdeNet_JAR.jar
e812\system\classes\System_JAR.jar
e812\system\classes\log4j.jar
e812\system\classes\xerces.jar
e812\system\classes\xalan.jar
e812\system\classes\ManagementAgent_JAR.jar
e812\system\classes\jmxri.jar
e812\system\classes\commons-httpclient-3.0.jar
e812\system\classes\commons-logging.jar
e812\system\classes\ xmlparserv2.jar
e812\system\classes\ jmxremote_optional.jar
e812\system\Classes\samples\jdeinterop.ini.templ
e812\system\Classes\samples\jdelog.properties
Note: If you have multiple-foundation implemented in the system, make sure the files you are copying match the service pack level installed in the enterprise server.
4) Rename jdeinterop.ini.templ to jdeinterop.ini. Modify the jdeinterop.ini file copied in step 3 to reflect the correct enterprise server name:
a) Ensure that parameters glossaryTextServer in [SERVER] section, serviceNameConnect in [JDENET] section, and enterpriseServer, port in [INTEROP] section specify the correct enterprise server name and JDENET port number).
b) Configure the value of Repository under [INTEROP] section such that it points to the directory created in step 2 (for example, “Repository= C:\JXMLTool”).
c) Ensure that parameter SecurityServer in [SECURITY] section specify the correct security server.
d) Configure OCMEnabled to “false” in [OCM] section.
e) Add the parameter netTrace to [JDENET] section and configure its value as “1” (for example, “netTrace=1”)
5) Rename jdelog.properties.templ to jdelog.properties. Modify the jdelog.properties file to reflect the characteristics of the machine:
a) Ensure that jdelog.handler.JDELOG.File points to directory created in step 2 (for example, jdelog.handler.JDELOG.File=C:/JXMLTool/jderoot.log).
b) Ensure that jdelog.handler.JASLOG.File points to directory created in step 2 (for example, jdelog.handler.JASLOG.File=C:/JXMLTool/jas.log).
c) Remove comment marks from parameters jdelog.Debug, jdelog.handler.jasdebug, jdelog.handler.jasdebug.File, and jdelog.handler.jasdebug.Level.
c) Ensure that jdelog.handler.jasdebug.File points to directory created in step 2 (for example, jdelog.handler.jasdebug.File=C:/JXMLTool/jasdebug.log).
6) Create a new text file using the text editor of your choice (for example, Notepad).
7)Paste the following text to the new document:
@echo off
REM Edit this file to the locations for Java and EnterpriseOne
REM JDK root directory
set JAVA_HOME=C:\j2sdk1.4.2_12
set PATH=C:\j2sdk1.4.2_12\bin
REM EnterpriseOne Windows client install path
set OneWorld_HOME=C:\e812
REM This directory
set EXAMPLES=C:\Interop\JXMLTool
REM Set the CLASSPATH environment variable.
REM The following are libraries that are needed for Connector samples:
set CLASSPATH=Base_JAR.jar
set CLASSPATH=%CLASSPATH%;C:\Interop\JXMLTool\
set CLASSPATH=%CLASSPATH%;C:\Interop\JXMLTool\JXMLTool.class
set CLASSPATH=%CLASSPATH%;JdeNet_JAR.jar
set CLASSPATH=%CLASSPATH%;System_JAR.jar
set CLASSPATH=%CLASSPATH%;log4j.jar
set CLASSPATH=%CLASSPATH%;xerces.jar
set CLASSPATH=%CLASSPATH%;xalan.jar
set CLASSPATH=%CLASSPATH%;ManagementAgent_JAR.jar
set CLASSPATH=%CLASSPATH%;jmxri.jar
set CLASSPATH=%CLASSPATH%;commons-httpclient-3.0.jar
set CLASSPATH=%CLASSPATH%;commons-logging.jar
set CLASSPATH=%CLASSPATH%;xmlparserv2.jar
set CLASSPATH=%CLASSPATH%;jmxremote_optional.jar
set CLASSPATH=%CLASSPATH%;%OneWorld_HOME%\system\classes\
a) Ensure that "set JAVA_HOME" command sets the variable with correct path to JDK directory (for example, "set JAVA_HOME=c:\jdk142").
b) Configure value of OneWorld_HOME such that it points to the directory where OneWorld® is installed (for example, “set OneWorld_HOME=C:\e812”).
c) Ensure that "set EXAMPLES" command sets the variable with the correct path to directory created in step 2 (for example, "set EXAMPLES=C:\JXMLTool").
d) Configure value of JDEINTEROPINI such that it points to the jdeinterop.ini file you copied in step 3 (for example,
“set JDEINTEROPINI=%EXAMPLES%\jdeinterop.ini”).
e) Append the path of the bin directory of the JDK to the PATH variable. For example, add the following line:
“set PATH=%JAVA_HOME%\bin”
8) Save the file as setenv.bat in the directory created in step 2 (for example, C:\JXMLTool\setEnv.bat).
9) Create a new text file using the text editor of your choice (for example, Notepad).
10) Paste the following text to the new document:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.GregorianCalendar;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import com.jdedwards.system.xml.XMLRequest;
import com.jdedwards.system.net.JdeNetTimeoutException;
import com.jdedwards.system.net.JdeNetConnectFailedException;
// Application: JXMLTool
// Description: Java tool that submits XML requests to OneWorld® enterprise Servers
// Author: Luis A. Santillo
public class JXMLTool extends JFrame implements ActionListener {
Panel xmlPanel;
Label ServerNameLabel;
Label PortNumberLabel;
TextField PortNumberField;
TextField ServerNameField;
TextArea RequestArea;
TextArea ReplyArea;
Button submitButton;
String directory;
String owServerName;
String ReplyString;
int owPortNumber;
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
Menu helpMenu = new Menu("Help");
MenuItem openMenuItem = new MenuItem("Open");
MenuItem exitMenuItem = new MenuItem("Exit");
MenuItem helpMenuItem = new MenuItem("About");
public static void main(String args[]) {
JXMLTool jxmltool = new JXMLTool();
jxmltool.init();
public void init () {
xmlPanel = createXMLPanel();
this.setSize(640, 480);
this.setResizable(true);
this.getContentPane().add(xmlPanel, BorderLayout.CENTER);
this.setVisible(true);
openMenuItem.addActionListener(this);
fileMenu.add(openMenuItem);
fileMenu.add(new MenuItem("-"));
exitMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
helpMenu.add(helpMenuItem);
mb.add(fileMenu);
mb.add(helpMenu);
this.setMenuBar(mb);
submitButton.addActionListener(this);
directory = System.getProperty("user.dir");
private Panel createXMLPanel()
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
xmlPanel = new Panel();
xmlPanel.setLayout(gridbag);
buildConstraints(constraints, 0, 0, 1, 1, 10, 5);
constraints.fill = GridBagConstraints.NONE;
ServerNameLabel = new Label("OneWorld® Server Name", Label.LEFT);
gridbag.setConstraints(ServerNameLabel, constraints);
xmlPanel.add(ServerNameLabel);
buildConstraints(constraints, 1, 0, 1, 1, 40, 0);
constraints.fill = GridBagConstraints.NONE;
ServerNameField = new TextField("", 20);
gridbag.setConstraints(ServerNameField, constraints);
xmlPanel.add(ServerNameField);
buildConstraints(constraints, 2, 0, 1, 1, 10, 0);
constraints.fill = GridBagConstraints.NONE;
PortNumberLabel = new Label("Port Number", Label.LEFT);
gridbag.setConstraints(PortNumberLabel, constraints);
xmlPanel.add(PortNumberLabel);
buildConstraints(constraints, 3, 0, 1, 1, 40, 0);
constraints.fill = GridBagConstraints.NONE;
PortNumberField = new TextField("", 20);
gridbag.setConstraints(PortNumberField, constraints);
xmlPanel.add(PortNumberField);
buildConstraints(constraints, 0, 1, 4, 1, 0, 40);
constraints.fill = GridBagConstraints.BOTH;
RequestArea = new TextArea("", 10, 80);
gridbag.setConstraints(RequestArea, constraints);
xmlPanel.add(RequestArea);
buildConstraints(constraints, 0, 2, 4, 1, 0, 5);
constraints.fill = GridBagConstraints.NONE;
submitButton = new Button("Submit");
gridbag.setConstraints(submitButton, constraints);
xmlPanel.add(submitButton);
buildConstraints(constraints, 0, 3, 4, 1, 0, 40);
constraints.fill = GridBagConstraints.BOTH;
ReplyArea = new TextArea("", 10, 80);
ReplyArea.setBackground(Color.gray);
gridbag.setConstraints(ReplyArea, constraints);
xmlPanel.add(ReplyArea);
return xmlPanel;
void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof MenuItem) {
String label = ((MenuItem)e.getSource()).getLabel();
if (label.equals("File"));
if (label.equals("Open")) {
FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
f.setDirectory(directory);
f.show();
directory = f.getDirectory();
setFile(directory, f.getFile());
f.dispose();
if (label.equals("Exit"))
System.exit(0);
if (label.equals("About"));
if (e.getSource() instanceof Button) {
if (ServerNameField.getText().equals(""))
ReplyArea.setText("Error: server name is either null or empty!\nPlease enter new server name.\n");
else {
if (PortNumberField.getText().equals(""))
ReplyArea.setText("Error: port number is either null or empty!\nPlease enter new port number.\n");
else {
owServerName = ServerNameField.getText();
try {
owPortNumber = Integer.parseInt(PortNumberField.getText());
ReplyString = submitXMLRequest(RequestArea.getText());
ReplyArea.setText(ReplyArea.getText() + "\n\n" + ReplyString);
catch (NumberFormatException nfex) {
ReplyArea.setText("Error: unable to format port number!\n");
ReplyArea.setText(ReplyArea.getText() + "Exception: " + nfex +"\nPlease enter new port number.\n");
public void setFile(String directory, String filename) {
if ((filename == null) || (filename.length() == 0)) return;
File f;
FileReader in = null;
try {
f = new File(directory, filename);
in = new FileReader(f);
int size = (int) f.length();
char[] data = new char[size];
int chars_read = 0;
while(chars_read < size)
chars_read += in.read(data, chars_read, size-chars_read);
RequestArea.setText(new String(data));
catch (IOException e) {
ReplyArea.setText(e.getClass().getName() + ": " + e.getMessage());
finally { try { if (in != null) in.close(); } catch (IOException e) {} }
public String submitXMLRequest(String xmlIn) {
GregorianCalendar gregCalendar = new GregorianCalendar();
String xmlOut = null;
Date currentDate;
try {
ReplyArea.setText(gregCalendar.getTime() + " New XML request.\n");
ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Creating XML request using text in area above.\n");
XMLRequest xml = new XMLRequest(owServerName, owPortNumber, xmlIn);
ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " XML request submitted to " + owServerName + " using port number " + PortNumberField.getText() + ".\n");
ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Waiting for reply from " + owServerName + ".\n");
xmlOut = xml.execute();
catch (JdeNetTimeoutException toex) {
ReplyArea.setText(ReplyArea.getText() + "\nError: JDENet timed out!\n" + "Exception: " + toex +"\n\n");
catch (JdeNetConnectFailedException cfex) {
ReplyArea.setText(ReplyArea.getText() + "\nError: JDENet connect failed!\n" + "Exception: " + cfex +"\n\n");
catch (java.io.IOException ioex) {
ReplyArea.setText(ReplyArea.getText() + "\nError: IO Exception!\n" + "Exception: " + ioex +"\n\n");
currentDate = new Date ();
gregCalendar.setTime(currentDate);
ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Reply received from " + owServerName + ".\n");
return xmlOut;
public void processWindowEvent(WindowEvent e) {
if (e.getID() == Event.WINDOW_DESTROY) {
System.exit(0);
11) Save the file as JXMLTool.java in the directory created in step 2 (for example, C:\JXMLTool\JXMLTool.java).
12) Create a new text file using the text editor of your choice (for example, Notepad).
13) Paste the following text to the new document:
@echo off
call setenv.bat
javac JXMLTool.java
14) Save the file as build.bat in the directory created in step 2 (for example, C:\JXMLTool\build.bat).
15) Build the JXMLTool Java application:
a) Open a new MS-DOS Command Prompt window.
b) Change the current directory to the directory created in step 2.
c) Call the build.bat script to compile the Java code and create the JXMLTool Java class.
d) Verify that JXMLTool.class exists in the directory created in step 2 (for example,
“C:\JXMLTool\JXMLTool.class”).
16) Create a new text file using the text editor of your choice (for example, Notepad).
17) Paste the following text to the new document:
@echo off
call setenv.bat
java -Dconfig_file=jdeinterop.ini JXMLTool
18) Save the file as run.bat in the directory created in step 2 (for example, C:\JXMLTool\run.bat).
Usage:
1) Open a new MS-DOS Command Prompt window.
2) Change the current directory to the directory created in step 2.
3) Call the run.bat script to execute the JXMLTool Java application.
5) In the Java application, enter enterprise server name and port number in appropriate text fields.
6) Enter the following text in the upper panel:
<?xml version='1.0' ?>
<jdeRequest type='callmethod' user='JDE' pwd='JDE' environment='JPD812' session=''>
<callMethod name='GetEffectiveAddress' app='JXMLTool'>
<params>
<param name='mnAddressNumber'>1001</param>
</params>
</callMethod>
</jdeRequest>
7) Modify the XML information to reflect the characteristics of the system:
a) Replace user, password, and environment with correct values for your system.
b) If 1001 is not a valid AddressBook number, replace it with a valid AB number.
8) Click the button “Submit”.
9) Verify that an XML reply is received from enterprise server. The reply will be displayed in the lower panel.
Retrieving an XML Template for BSFN Request:
1) Repeat steps 1 through 9 in Usage, using the following text in step 6:
<?xml version='1.0' ?>
<jdeRequest type='callmethod' user='JDE' pwd='JDE' environment='JPD812'>
<callMethodTemplate name='GetEffectiveAddress' app='JXMLTool'/>
</jdeRequest>
2) Highlight the text in the lower panel, starting with tag “<?xml version='1.0' ?>”.
3) Press Control (Ctrl) and C keys simultaneously.
4) Open a new text document using the text editor of your choice.
5) Paste contents into new text document.
6) Remove tag “<returnCode=’0’/>”.
7) Save text document with extension .xml. -
Help plz-internalFrames--buttons-video..any jgurus around??
Hi to all
My name is Dimitrios and i am developing a program which is consisted by a client program and a server program. The purpose of the application is to stream video (TV channels) to the client.The server program is used to authenticate the client (at the moment) where the client after the authentication is providing a GUI in order to choose the Chanel and watch the video.In more detail:
Client site:
2 classes ( frames)
The 1st frame (login.java) prompts for username and password. The server (prog) authenticates the pass and if correct the client "moves" to the next frame (by set visible false to the 1st frame).
The 2nd frame (client.java) is the actual GUI of the program. It is consisted by two buttons (assume we have two T.V channel options) and an internal frame which is where the video is displayed.
In order to develop this program i have split up the tasks and try to solve each task at a time. What i mean is:
1)Create an authentication procedure (DONE)
2)Create the GUI of the client (DONE)
3)Create the operation where button is pressed and video is played IN THE INTERNAL FRAME (in progress)
4)Stream video (in progress)
Since i don't know yet how am i going to produce the streaming what iv done is to embed a simple quicktime player in the client and open a movie file to produce video. I need to produce the video in the internal frame first.
My question is:
1) How am i going to produce the video in the internal frame after the button is pressed. Note that the button is not in the internal frame (obvious i think).
2)i decided to use quicktime player API cause during my research i fpund out that is the best option.I did trie JMF but i wasnt that satisfied. Do you propose any other solution. I did try to find out if i could embed Windows Media player in my frame but i didn't find any info regarding WMP and java frames.
I do have some knowledge about java but i wouldnt consider my self an advance programmer. THIS IS NOT A JOB CASE but a presentation from my UNI.
Thanks in advance for reading all this.
ps1 i am using netbeans
ps2 in the code below i havent icluded the initcompomens() method cause my code is too big for the post
My Code:
CLIENT-second Frame
import java.awt.*;*
*import java.awt.event.*;
import javax.swing.*;*
*import java.io.File;*
*import quicktime.*;
import quicktime.app.*;*
*import quicktime.app.players.*;
import quicktime.app.display.*;*
*import quicktime.io.*;
import quicktime.std.*;*
*import quicktime.std.movies.*;
import quicktime.*;*
*import javax.swing.*;
public class client extends javax.swing.JFrame {
static Movie movie;
/** Creates new form client */
public client()
initComponents();
setVisible(true);
// login.setVisible(false);
// @SuppressWarnings("unchecked")
{METHOD INITCOMPOMENTS
Too big to fit one the post }
private void buttonClickAnt(java.awt.event.MouseEvent evt) {
try {
QTSession.open();
FileDialog fd = new FileDialog (this,"Select source movie",FileDialog.LOAD);
fd.show();
if (fd.getFile() == null)
return;
// get movie from file
File f = new File (fd.getDirectory(), fd.getFile());
OpenMovieFile omFile =
OpenMovieFile.asRead (new QTFile (f));
movie = Movie.fromFile (omFile);
// get a Drawable for Movie, put in QTCanvas
MoviePlayer player = new MoviePlayer (movie);
QTCanvas canvas = new QTCanvas();
canvas.setClient (player, true);
add (canvas);
// windows-like close-to-quit
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
QTSession.close();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
try {
movie.start();
} catch (Exception e) {
e.printStackTrace();
private void trip(javax.swing.event.InternalFrameEvent evt) {
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}Edited by: tripis on Feb 11, 2009 10:41 AMIf you feel more adventurious and have Afer Effects, you might be interested in this series of screen captures
http://vimeo.com/album/214460.
John Rich -
Q: readObject(), array?
class Eph2000F extends Frame implements ActionListener, WindowListener, Runnable
{ public void actionPerformed(ActionEvent AE) //===============================================
{ if(AE.getSource()==MI_Avaa) //open
{ FileDialog f=new FileDialog(this,"Avaa Examiphobia-tiedosto (*.eph)",FileDialog.LOAD);
f.show();
tiedosto=f.getFile(); //file
polku=f.getDirectory(); //path
lueTiedot();
KysymysLuokka Kysymykset[]; //questionclass questions[]
static class KysymysLuokka implements Serializable { ... }
public void lueTiedot() //readData()
{ if(tiedosto!=""&&tiedosto!=null&&polku!=""&&polku!=null)
{ f=new File(polku+tiedosto);
if(!f.exists()) { ilmoita("Tiedosto ei ole olemassa!"); return; } //tell to user...
else if(f.isDirectory()) { ilmoita("Tiedosto on hakemisto!"); return; }
else if(!f.canWrite()) { ilmoita("Tiedosto on kirjoitus-suojattu!"); return; }
try
{ FileInputStream FIS=new FileInputStream(f);
ObjectInputStream OIS=new ObjectInputStream(FIS);
Kysymykset=new KysymysLuokka[1];
Kysymykset[0]=new KysymysLuokka();
kysymysNyt=0; //question now
Kysymykset=(KysymysLuokka[])OIS.readObject(); //-> to catch, because Kysymykset=null!!!
OIS.close(); out("OIS.close() suoritettu");
kysymysNyt=0; out("kysymysNyt=0; suoritettu");
catch(Exception E) { ilmoita("Deserialisointi ei onnistunut..."); } //it comes here.
Hi! where's the problem. this is ver 2.00 of eph; and ver 1.00 worked correctly.
I just can't find the problem. kysymykset = null, whyHave you checked so that you havent serialized it as
null?Thanks, I think you are right, that I should check null-selialization. I must have algoritm-problem with save-method(), it propably saves object as null and there's nothing...
Otherwise I would recomend to put in traces and see
were you get it set to null.
By the way, do you get exceptions on this one? yes; lueTiedot()-> nullPointerException -
I have a code for finding peaks of a graph given by someone in the forum and I have also changed it to suit my requirements. But it fails to distinguish between different peaks and also the period between two consecutive similar peaks. I am including the code and also the text file. Please help me as I have submit this within 2 days.
This is the java file.
package medinfo.ecg;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.RandomAccessFile;
public class Abes3{
static class Point{
public int x;
public int y;
public Point(int x, int y){
this.x= x;
this.y= y;
public String toString() { return "(" +x +"," +y +")"; }
static class Graph{
private ArrayList mPoints= new ArrayList();
public void add(Point point){
mPoints.add(point);
public Point get(int i){
return (Point) mPoints.get(i);
public int size(){
return mPoints.size();
public int width(){
return ((Point) mPoints.get(size()-1)).x;
public Point getMin(){
return getExtremity(true);
public Point getMax(){
return getExtremity(false);
private Point getExtremity(boolean min){
Point extremity= null;
Point point= null;
Iterator points= mPoints.iterator();
while (points.hasNext()){
point= (Point) points.next();
if (extremity == null || (min && point.y < extremity.y) || (!min && point.y > extremity.y)){
extremity= point;
return extremity;
public Point[] getPeaks(){
return getExtremities(true);
public Point[] getTroughs(){
return getExtremities(false);
private Point[] getExtremities(boolean peak){
ArrayList extremities= new ArrayList();
Point point= null;
Point prev= null;
Point next= null;
for (int i= 0; i< mPoints.size(); i++){
point= (Point) mPoints.get(i);
prev= (Point) (i > 0 ? mPoints.get(i-1) : null);
next= (Point) (i < mPoints.size() -1 ? mPoints.get(i+1) : null);
if (prev == null && next == null)
extremities.add(point);
else if (prev == null){
if ((peak && point.y > next.y)|| (!peak && point.y <= next.y))
extremities.add(point);
else if (next == null){
if ((peak && point.y > prev.y) || (!peak && point.y <= prev.y))
extremities.add(point);
else if ((peak && (point.y > prev.y && point.y >= next.y)) || (!peak && (point.y < prev.y && point.y <= next.y))){
extremities.add(point);
Point[] array= new Point[extremities.size()];
extremities.toArray(array);
return array;
public String toString(){
String str= "Min:" getMin() " Max:" +getMax();
str += " Peaks:";
Point[] peaks= getPeaks();
for (int i= 0; i< peaks.length; i++)
str += peaks.toString();
str += " Troughs:";
Point[] troughs= getTroughs();
for (int i= 0; i< troughs.length; i++)
str += troughs[i].toString();
str += " Peak Periods:";
for (int i= 0; i< peaks.length -1; i++){
int period= Math.abs(peaks[i].x -peaks[i+1].x);
str += peaks[i] +":" +peaks[i+1] +"=" +period;
if (i < peaks.length -2)
str += ",";
return str;
static class GraphPanel extends JPanel{
private int gap= 200;
private int mult= 1;
private Graph mGraph;
private Point mPeak= null;
private Point mTrough= null;
public GraphPanel(Graph graph){
mGraph= graph;
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
findPeakAndTrough(e.getPoint().x);
public Dimension getPreferredSize(){
return new Dimension((gap+mGraph.width())*mult, (gap+mGraph.getMax().y)*mult);
public void paint(Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,getSize().width, getSize().height);
g.setColor(Color.black);
for (int i= 0; i< mGraph.size() -1; i++){
g.drawLine(getX(mGraph.get(i).x), getY(mGraph.get(i).y),getX(mGraph.get(i+1).x), getY(mGraph.get(i+1).y));
Point max= mGraph.getMax();
String str= max.toString();
double width= g.getFontMetrics().getStringBounds(str,g).getWidth();
g.setColor(Color.magenta);
g.drawString(str,(int)(getX(max.x) -(width/2)), getY(max.y) -2);
Point min= mGraph.getMin();
str= min.toString();
width= g.getFontMetrics().getStringBounds(str, g).getWidth();
int height= (int)g.getFontMetrics().getStringBounds(str, g).getHeight();
g.setColor(Color.blue);
g.drawString(str,(int)(getX(min.x) -(width/2)), getY(min.y) +height);
if (mPeak != null && mTrough != null){
g.setColor(Color.red);
int x= mPeak.x -((mPeak.x -mTrough.x)/2);
int y= mPeak.y -((mPeak.y -mTrough.y)/2);
g.drawLine(getX(x), getY(mPeak.y),getX(x), getY(mTrough.y));
g.drawLine( getX(mPeak.x), getY(mPeak.y),getX(x), getY(mPeak.y));
g.drawLine(getX(mTrough.x), getY(mTrough.y),getX(x), getY(mTrough.y));
str= "Period= " +(mPeak.y -mTrough.y);
width= g.getFontMetrics().getStringBounds(str, g).getWidth();
g.drawString(str,(int)(getX(x) -(width/2)), getY(mPeak.y) -2);
private int getX(int x){
return gap/16 +(x*mult);
private int getY(int y){
return getSize().height -gap -(y*mult);
private void findPeakAndTrough(int x){
mPeak= null;
mTrough= null;
Point[] peaks= mGraph.getPeaks();
Point[] troughs= mGraph.getTroughs();
for (int i= 0; i< peaks.length && i< troughs.length; i++){
if (getX(peaks[i].x) <= x){
mPeak= peaks[i];
mTrough= troughs[i];
if (mTrough.x < mPeak.x)
mTrough= troughs[i+1];
else{
if (mTrough != null && getX(mTrough.x) <= x)
mPeak= peaks[i];
break;
repaint();
static void frame(Graph graph, String title, int location){
JFrame frame= new JFrame(title);
frame.getContentPane().add(new GraphPanel(graph), BorderLayout.CENTER);
frame.setDefaultCloseOperation(3);
frame.pack();
frame.setLocation(location, location);
frame.setVisible(true);
static void test(){
try{
RandomAccessFile raf = new RandomAccessFile("test.txt","r");
long l = 0;
Graph graph= new Graph();
while (l < raf.length()){
String str = raf.readLine().toString();
l = raf.getFilePointer();
if (str != null){
String xtr = str.substring(0,4);
String ytr = str.substring(4);
int x = new Double(100*Double.parseDouble(xtr)).intValue();
int y = new Double(1000*Double.parseDouble(ytr)).intValue();
Point[] points = {new Point(x,y)};
for (int i= 0; i< points.length; i++){
graph.add(points[i]);
frame(graph,"Test",0);
System.err.println("Test: " +graph);
raf.close();
}catch (Exception e){
System.out.println("Caught Exception " + e.toString());
public static void main(String[] argv){
test();
Below is the txt file.
0 0
0.1 0
0.2 0.001
0.3 0.004
0.4 0.0065
0.5 0.0085
0.6 0.008
0.7 0.006
0.8 0.003
0.9 -0.001
1.0 -0.003
1.1 -0.0058
1.2 -0.007
1.3 -0.006
1.4 -0.004
1.5 -0.003
1.6 -0.0015
1.7 0.001
1.8 0.003
1.9 0.005
2.0 0.0064
2.1 0.0075
2.2 0.009
2.3 0.012
2.4 0.025
2.5 0.038
2.6 0.045
2.7 0.04
2.8 0.03
2.9 0.015
3.0 0.0085
3.1 0.007
3.2 0.0058
3.3 0.0045
3.4 0.0035
3.5 0.002
3.6 -0.001
3.7 -0.0028
3.8 -0.0044
3.9 -0.006
4.0 -0.0055
4.1 -0.0036
4.2 -0.0028
4.3 -0.0014
4.4 0.0009
4.5 0.0016
4.6 0.0024
4.7 0.0035
4.8 0.0044
4.9 0.0051
5.0 0.006
5.1 0.0055
5.2 0.0048
5.3 0.0039
5.4 0.0031
5.5 0.0023
5.6 0.0014
5.7 0.00087
5.8 0
5.9 0
6.0 0.001
6.1 0.004
6.2 0.0065
6.3 0.0085
6.4 0.008
6.5 0.006
6.6 0.003
6.7 -0.001
6.8 -0.003
6.9 -0.0058
7.0 -0.007
7.1 -0.006
7.2 -0.004
7.3 -0.003
7.4 -0.0015
7.5 0.001
7.6 0.003
7.7 0.005
7.8 0.0064
7.9 0.0075
8.0 0.009
8.1 0.012
8.2 0.025
8.3 0.038
8.4 0.045
8.5 0.04
8.6 0.03
8.7 0.015
8.8 0.0085
8.9 0.007
9.0 0.0058
9.1 0.0045
9.2 0.0035
9.3 0.002
9.4 -0.001
9.5 -0.0028
9.6 -0.0044
9.7 -0.006
9.8 -0.0055
9.9 -0.0036
10.0 -0.0028
10.1 -0.0014
10.2 0.0009
10.3 0.0016
10.4 0.0024
10.5 0.0035
10.6 0.0044
10.7 0.0051
10.8 0.006
10.9 0.0055
11.0 0.0048
11.1 0.0039
11.2 0.0031
11.3 0.0023
11.4 0.0014
11.5 0.00087
11.6 0
11.7 0
11.8 0.001
11.9 0.004
12.0 0.0065
12.1 0.0085
12.2 0.008
12.3 0.006
12.4 0.003
12.5 -0.001
12.6 -0.003
12.7 -0.0058
12.8 -0.007
12.9 -0.006
13.0 -0.004
13.1 -0.003
13.2 -0.0015
13.3 0.001
13.4 0.003
13.5 0.005
13.6 0.0064
13.7 0.0075
13.8 0.009
13.9 0.012
14.0 0.025
14.1 0.038
14.2 0.045
14.2 0.04
14.3 0.03
14.4 0.015
14.5 0.0085
14.6 0.007
14.7 0.0058
14.8 0.0045
14.9 0.0035
15.0 0.002
15.1 -0.001
15.2 -0.0028
15.3 -0.0044
15.4 -0.006
15.5 -0.0055
15.6 -0.0036
15.7 -0.0028
15.8 -0.0014
15.9 0.0009
16.0 0.0016
16.1 0.0024
16.2 0.0035
16.3 0.0044
16.4 0.0051
16.5 0.006
16.6 0.0055
16.7 0.0048
16.8 0.0039
16.9 0.0031
17.0 0.0023
17.1 0.0014
17.2 0.00087
17.3 0
17.4 0
17.5 0.001
17.6 0.004
17.7 0.0065
17.8 0.0085
17.9 0.008
18.0 0.006
18.1 0.003
18.2 -0.001
18.3 -0.003
18.4 -0.0058
18.5 -0.007
18.6 -0.006
18.7 -0.004
18.8 -0.003
18.9 -0.0015
19.0 0.001
19.1 0.003
19.2 0.005
19.3 0.0064
19.4 0.0075
19.5 0.009
19.6 0.012
19.7 0.025
19.8 0.038
19.9 0.045
20.0 0.04
20.1 0.03
20.2 0.015
20.3 0.0085
20.4 0.007
20.5 0.0058
20.6 0.0045
20.7 0.0035
20.8 0.002
20.9 -0.001
21.0 -0.0028
21.1 -0.0044
21.2 -0.006
21.3 -0.0055
21.4 -0.0036
21.5 -0.0028
21.6 -0.0014
21.7 0.0009
21.8 0.0016
21.9 0.0024
22.0 0.0035
22.1 0.0044
22.2 0.0051
22.3 0.006
22.4 0.0055
22.5 0.0048
22.6 0.0039
22.7 0.0031
22.8 0.0023
22.9 0.0014
23.0 0.00087
23.1 0
23.2 0
23.3 0.001
23.4 0.004
23.5 0.0065
23.6 0.0085
23.7 0.008
23.8 0.006
23.9 0.003
24.0 -0.001
24.1 -0.003
24.2 -0.0058
24.3 -0.007
24.4 -0.006
24.5 -0.004
24.6 -0.003
24.7 -0.0015
24.8 0.001
24.9 0.003
25.0 0.005
25.1 0.0064
25.2 0.0075
25.3 0.009
25.4 0.012
25.5 0.025
25.6 0.038
25.7 0.045
25.8 0.04
25.9 0.03
26.0 0.015
26.1 0.0085
26.2 0.007
26.3 0.0058
26.4 0.0045
26.5 0.0035
26.6 0.002
26.7 -0.001
26.8 -0.0028
26.9 -0.0044
27.0 -0.006
27.1 -0.0055
27.2 -0.0036
27.3 -0.0028
27.4 -0.0014
27.5 0.0009
27.6 0.0016
27.7 0.0024
27.8 0.0035
27.9 0.0044
28.0 0.0051
28.1 0.006
28.2 0.0055
28.3 0.0048
28.4 0.0039
28.5 0.0031
28.6 0.0023
28.7 0.0014
28.8 0.00087Well thanks all of you for your replies. I have now solved that problem. I need another help.
ChooseFiles.java
import java.awt.*;
import java.awt.event.*;
public class ChooseFiles{
public static void main(String[] args){
getFiles();
public static String getFiles(){
DialogFrames df = new DialogFrames("MedInfo");
df.setSize(800,555);
df.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
df.show();
return df.getFile();
class DialogFrames extends Frame implements ActionListener{
Menu m = new Menu("File");
MenuBar mb = new MenuBar();
MenuItem mi = new MenuItem("Open");
FileDialog fd;
DialogFrames(String title){
super(title);
setLayout(new GridLayout(1,1));
m.add(mi);
mi.addActionListener(this);
mb.add(m);
setMenuBar(mb);
fd = new FileDialog(this,"Open");
public void actionPerformed(ActionEvent ae){
if (ae.getSource()==mi){
fd.setVisible(true);
public String getFile(){
return fd.getFile();
app.java
package medinfo.ecg;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.RandomAccessFile;
public class app{
ChooseFiles cf = new ChooseFiles();
static class Point{
public int x;
public int y;
public Point(int x, int y){
this.x= x;
this.y= y;
public String toString() { return "(" +x +"," +y +")"; }
static class Graph{
private ArrayList mPoints= new ArrayList();
public void add(Point point){
mPoints.add(point);
public Point get(int i){
return (Point) mPoints.get(i);
public int size(){
return mPoints.size();
public int width(){
return ((Point) mPoints.get(size()-1)).x;
public Point[] getMin(){
return getExtremity(true);
public Point[] getMax(){
return getExtremity(false);
private Point[] getExtremity(boolean min){
Point extremity[]= new Point[mPoints.size()];
Point point[]= new Point[mPoints.size()];
Iterator points= mPoints.iterator();
while (points.hasNext()){
for (int i=0;i<mPoints.size();i++){
point= (Point) points.next();
if (extremity[i] == null || (min && point[i].y < extremity[i].y) || (!min && point[i].y > extremity[i].y)){
extremity[i]= point[i];
return extremity;
public Point[] getMin1(){
Point min1[]= new Point[10];
Point[] troughs= getExtremities(false);
for (int i=0;i<min1.length-1;i++){
if ( Math.min(troughs[i].y,troughs[i+1].y)==troughs[i+1].y)
min1[i] = troughs[i];
return min1;
public Point[] getPeaks(){
return getExtremities(true);
public Point[] getTroughs(){
return getExtremities(false);
private Point[] getExtremities(boolean peaks){
ArrayList extremities= new ArrayList();
Point point= null;
Point prev= null;
Point next= null;
for (int i= 0; i< mPoints.size(); i++){
point= (Point) mPoints.get(i);
prev= (Point) (i > 0 ? mPoints.get(i-1) : null);
next= (Point) (i < mPoints.size() -1 ? mPoints.get(i+1) : null);
if (prev == null && next == null)
extremities.add(point);
else if (prev == null){
if ((peaks && point.y > next.y)|| (!peaks && point.y <= next.y))
extremities.add(point);
else if (next == null){
if ((peaks && point.y > prev.y) || (!peaks && point.y <= prev.y))
extremities.add(point);
else if ((peaks && (point.y > prev.y && point.y >= next.y)) || (!peaks && (point.y < prev.y && point.y <= next.y))){
extremities.add(point);
Point[] array= new Point[extremities.size()];
extremities.toArray(array);
return array;
public String toString(){
String str= "";
Graph graph = new Graph();
for (int i=0;i<graph.size();i++)
str += "Min:" +getMin()[i] + " Max:" +getMax()[i];
// str += " Peaks:";
str += "Min1 : ";
Point[] min1= getMin1();
for (int i=0;i<graph.size();i++)
str += min1[i].toString();
Point[] peaks= getPeaks();
// str += " Peak Periods : ";
for (int i= 0; i< peaks.length -1; i++){
int period= Math.abs(peaks[i].x -peaks[i+1].x);
str += peaks[i] +"," +peaks[i+1] +":" +period;
if (i < peaks.length -2)
str += ",";
return str;
static class GraphPanel extends JPanel{
private int gap= 100;
private int mult= 1;
private Graph mGraph;
private Point mPeak= null;
private Point mTrough= null;
public GraphPanel(Graph graph){
mGraph= graph;
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
findPeakAndTrough(e.getPoint().x);
public Dimension getPreferredSize(){
Dimension d = null;
for (int i=0;i<mGraph.size();i++)
d = new Dimension((gap+mGraph.width())*mult, (gap+mGraph.getMax()[i].y)*mult);
return d;
public void paint(Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,getSize().width, getSize().height);
g.setColor(Color.black);
for (int i= 0; i< mGraph.size() -1; i++){
g.drawLine(getX(mGraph.get(i).x), getY(mGraph.get(i).y),getX(mGraph.get(i+1).x), getY(mGraph.get(i+1).y));
Point max= mGraph.getMax()[i];
String str= max.toString();
double width= g.getFontMetrics().getStringBounds(str,g).getWidth();
g.setColor(Color.magenta);
g.drawString(str,(int)(getX(max.x) -(width/2)), getY(max.y) -2);
Point min= mGraph.getMin()[i];
str= min.toString();
width= g.getFontMetrics().getStringBounds(str, g).getWidth();
int height= (int)g.getFontMetrics().getStringBounds(str, g).getHeight();
g.setColor(Color.blue);
g.drawString(str,(int)(getX(min.x) -(width/2)), getY(min.y) +height);
if (mPeak != null && mTrough != null){
g.setColor(Color.red);
int x= mPeak.x -((mPeak.x -mTrough.x)/2);
int y= mPeak.y -((mPeak.y -mTrough.y)/2);
g.drawLine(getX(x), getY(mPeak.y),getX(x), getY(mTrough.y));
g.drawLine( getX(mPeak.x), getY(mPeak.y),getX(x), getY(mPeak.y));
g.drawLine(getX(mTrough.x), getY(mTrough.y),getX(x), getY(mTrough.y));
str= "Period= " +(mPeak.y -mTrough.y);
width= g.getFontMetrics().getStringBounds(str, g).getWidth();
g.drawString(str,(int)(getX(x) -(width/2)), getY(mPeak.y) -2);
private int getX(int x){
return gap/8 +(x*mult);
private int getY(int y){
return getSize().height - gap -(y*mult);
private void findPeakAndTrough(int x){
mPeak= null;
mTrough= null;
Point[] peaks= mGraph.getPeaks();
Point[] troughs= mGraph.getTroughs();
for (int i= 0; i< peaks.length && i< troughs.length; i++){
if (getX(peaks[i].x) <= x){
mPeak= peaks[i];
mTrough= troughs[i];
if (mTrough.x < mPeak.x)
mTrough= troughs[i+1];
else{
if (mTrough != null && getX(mTrough.x) <= x)
mPeak= peaks[i];
break;
repaint();
static void frame(Graph graph, String title, int location){
JFrame frame= new JFrame(title);
frame.getContentPane().add(new GraphPanel(graph), BorderLayout.CENTER);
frame.setDefaultCloseOperation(3);
frame.pack();
frame.setLocation(location, location);
frame.setVisible(true);
static void test(){
try{
String ftr = cf.getFiles();
RandomAccessFile raf = new RandomAccessFile(ftr,"r");
long l = 0;
Graph graph= new Graph();
while (l < raf.length()){
String str = raf.readLine().toString();
l = raf.getFilePointer();
if (str != null){
String xtr = str.substring(0,3);
String ytr = str.substring(3);
int x = new Double(100*Double.parseDouble(xtr)).intValue();
int y = new Double(1000*Double.parseDouble(ytr)).intValue();
Point[] points = {new Point(x,y)};
for (int i= 0; i< points.length; i++){
graph.add(points[i]);
frame(graph,"Test",0);
System.err.println("Test: " +graph);
raf.close();
}catch (Exception e){
System.out.println("Caught Exception " + e.toString());
public static void main(String[] argv){
test();
I get the following compilation error.
app.java:14: Class ChooseFiles not found.
ChooseFiles cf = new ChooseFiles();
^
app.java:14: Class ChooseFiles not found.
ChooseFiles cf = new ChooseFiles();
^
app.java:213: Can't make a static reference to nonstatic variable cf in class app.
String ftr = cf.getFiles();
^
All the files are in the same package. -
How to make the user choose file.
I am making a program in which a file is read using RandomAcessFile. I wamt the user to choose the file from its location. I am giving the code. Just help me in knowing where the error is.
import java.awt.*;
import java.awt.event.*;
public class ChooseFiles{
public static void main(String[] args){
getFiles();
public static String getFiles(){
DialogFrames df = new DialogFrames("MedInfo");
df.setSize(800,555);
df.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
df.show();
return df.getFile();
class DialogFrames extends Frame implements ActionListener{
Menu m = new Menu("File");
MenuBar mb = new MenuBar();
MenuItem mi = new MenuItem("Open");
FileDialog fd;
DialogFrames(String title){
super(title);
setLayout(new GridLayout(1,1));
m.add(mi);
mi.addActionListener(this);
mb.add(m);
setMenuBar(mb);
fd = new FileDialog(this,"Open");
public void actionPerformed(ActionEvent ae){
if (ae.getSource()==mi){
fd.setVisible(true);
public String getFile(){
return fd.getFile();
import java.io.*;
public class Plot{
boolean flag = true;
ChooseFiles cf = new ChooseFiles();
public static void main(String[] args){
try{
String ftr = cf.getFiles();
RandomAccessFile raf = new RandomAccessFile(ftr,"r");
long l = 0;
while (l < raf.length()){
String str = raf.readLine().toString();
l = raf.getFilePointer();
if (str != null){
System.out.println("This line is " str" at l = "+l);
raf.close();
}catch (Exception e){
System.out.println("Caught Exception " + e.toString());
I get the following compilation error. Please help me to sort it out.
Plot.java:7: Can't make a static reference to nonstatic variable cf in class Plot.
String ftr = cf.getFiles();
^I made the changes to Plot.java.
This is the first one.
import java.io.*;
public class Plot{
boolean flag = true;
public static void main(String[] args){
Plot plot = new Plot();
Plot(){
try{
String ftr = "";
ChooseFiles cf = new ChooseFiles();
ftr += cf.getFiles();
RandomAccessFile raf = new RandomAccessFile(ftr,"r");
long l = 0;
while (l < raf.length()){
String str = raf.readLine().toString();
l = raf.getFilePointer();
if (str != null){
System.out.println("This line is " str" at l = "+l);
raf.close();
}catch (Exception e){
System.out.println("Caught Exception " + e.toString());
It gives the following exception.
Caught Exception java.io.FileNotFoundException: null (The system cannot find the file specified)
This is the second one.
import java.io.*;
public class Plot{
boolean flag = true;
public static void main(String[] args){
Plot plot = new Plot();
Plot(){
try{
ChooseFiles cf = new ChooseFiles();
String ftr = cf.getFiles();
RandomAccessFile raf = new RandomAccessFile(ftr,"r");
long l = 0;
while (l < raf.length()){
String str = raf.readLine().toString();
l = raf.getFilePointer();
if (str != null){
System.out.println("This line is " str" at l = "+l);
raf.close();
}catch (Exception e){
System.out.println("Caught Exception " + e.toString());
Caught Exception java.lang.NullPointerException -
JMF FrameGrabbingControl does not exist
I am trying to capture screenshots of the video playing.
to do this i am using FrameGrabbingControl but it is always null.
So i checked it and by using GetControls method i took a look at all the controls that were attached to my player and to my surprise, the FrameGrabbingControl was not on the list. then i tried the same thing with a Processor and got to the same point, the FrameGrabbingControl simply isnt there. I found in the forum that if i set the ContentDescriptor to null, the FrameGrabbingControl will be attached to the processor yet the problem for the player still remains as i need my users to be able to specify which frame they want to grab which they cannot do with a Processor. So i need to get it enabled in the Player.
I have copied my code, can you tell me if anyone has any idea how to get it working?
Thanks a lot
import com.sun.jndi.ldap.ManageReferralControl;
import java.awt.*;
import java.awt.event.*;
import java.lang.String;
import java.io.IOException;
import javax.media.*;
import java.awt.image.*;
import javax.media.control.*;
import javax.media.control.FramePositioningControl;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.protocol.FileTypeDescriptor;
import javax.media.protocol.DataSource;
import javax.media.util.BufferToImage;
import javax.media.datasink.*;
public class MyMediaWindow extends Frame implements ControllerListener, ActionListener {
Player myPlayer=null;
Component myVisualComp=null, myControlComp=null;
/** Creates a new instance of myMediaWindow */
public MyMediaWindow(String mf) {
mediaFile = mf;
MakeFrameReady();
myInitialize();
public MyMediaWindow() {
mediaFile = null;
MakeFrameReady();
myInitialize();
private void MakeFrameReady()
addWindowListener(new myWindowAdapter());
setLayout(new BorderLayout());
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu file = new Menu("File");
Menu tools = new Menu("Video Tools");
MenuItem item1,item2,item3,item4;
file.add(item2 = new MenuItem("Open"));
file.add(item1 = new MenuItem("Close"));
tools.add(item3 = new MenuItem("Add Video"));
tools.add(item4 = new MenuItem("Find Video"));
mbar.add(file);
mbar.add(tools);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
item4.addActionListener(this);
public void actionPerformed(ActionEvent aevent){
String arg=aevent.getActionCommand();
if(arg=="Open"){
FileDialog fd = new FileDialog(this, "Open File", FileDialog.LOAD);
fd.show();
StringBuffer sbPath = new StringBuffer(fd.getDirectory());
sbPath=sbPath.reverse();
sbPath.append("///:elif");
sbPath=sbPath.reverse();
String fileName = fd.getFile();
if (fileName == null)
return;
else sbPath.append(fileName);
mediaFile=sbPath.substring(0);
myInitialize();
PlayWindow();
else if(arg=="Close"){
this.myPlayer.stop();
this.myPlayer.deallocate();
this.myPlayer.close();
System.exit(0);
else if (arg=="Add Video")
FrameGrabbingControl fgc = (FrameGrabbingControl)myPlayer.
getControl("javax.media.control.FrameGrabbingControl");
if (fgc != null)
Buffer buf = fgc.grabFrame();
BufferToImage btoi = new BufferToImage( (VideoFormat) buf.getFormat());
BufferedImage img = (BufferedImage) btoi.createImage(buf);
vsr.example.Main.StartSegmentation(img);
else
System.out.println("Its NULL");
public void myInitialize(){
if(mediaFile!=null){
try{
MediaLocator myMedia=new MediaLocator(mediaFile);
myPlayer=Manager.createRealizedPlayer(myMedia);
Control [] ctrls = myPlayer.getControls();
catch(Exception e){
System.err.println("No file selected");
myVisualComp=myPlayer.getVisualComponent();
if (myVisualComp!=null)
add("Center",myVisualComp);
myControlComp=myPlayer.getControlPanelComponent();
add("South",myControlComp);
validate();
public synchronized void controllerUpdate(ControllerEvent event){
public void PlayWindow(){
setSize(new Dimension(320,240));
setTitle("A Media Player using JMF");
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize=getSize();
if( frameSize.height> screenSize.height){
frameSize.height=screenSize.height;}
if(frameSize.width>screenSize.width){
frameSize.width=screenSize.width;
setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);
setVisible(true);
if(mediaFile!=null){
myPlayer.start();
public static void main(String[] argv)
MyMediaWindow mmw = new MyMediaWindow();
mmw.PlayWindow();
}Message was edited by:
HellawaitsI am trying to capture screenshots of the video playing.Sounds interesting, and I would like to try and
help, but this code does not compile for me here.
(original words deleted in edit)
Can you prepare an SSCCE of this problem?
http://www.physci.org/codes/sscce.html
(..later)
OK.. I was a bit quick before, a couple
more changes and tweaks, but then I
was not only able to run this example
locally, but when I selected the 'add video'
I got to see the current frame pop up in
a JOptionPane.
This was using a simple .MOV* as source file.
Does this code not work for you?
* It is available here.
http://www.javasaver.com/testjs/jmf/anim/lunarphases.mov
If the code below does not work using the
media you are currently giving it, try the
simpler MOV file, or perhaps some of the
other media available here..
http://www.javasaver.com/testjs/jmf/#media
<sscce>import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.String;
import java.io.IOException;
import javax.media.*;
import java.awt.image.*;
import javax.media.control.*;
import javax.media.control.FramePositioningControl;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.protocol.FileTypeDescriptor;
import javax.media.protocol.DataSource;
import javax.media.util.BufferToImage;
import javax.media.datasink.*;
public class MyMediaWindow extends Frame implements ControllerListener, ActionListener {
Player myPlayer=null;
Component myVisualComp=null, myControlComp=null;
String mediaFile;
/** Creates a new instance of myMediaWindow */
public MyMediaWindow(String mf) {
mediaFile = mf;
MakeFrameReady();
myInitialize();
public MyMediaWindow() {
mediaFile = null;
MakeFrameReady();
myInitialize();
private void MakeFrameReady()
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
setLayout(new BorderLayout());
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu file = new Menu("File");
Menu tools = new Menu("Video Tools");
MenuItem item1,item2,item3,item4;
file.add(item2 = new MenuItem("Open"));
file.add(item1 = new MenuItem("Close"));
tools.add(item3 = new MenuItem("Add Video"));
tools.add(item4 = new MenuItem("Find Video"));
mbar.add(file);
mbar.add(tools);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
item4.addActionListener(this);
public void actionPerformed(ActionEvent aevent){
String arg=aevent.getActionCommand();
if(arg=="Open"){
FileDialog fd = new FileDialog(this, "Open File", FileDialog.LOAD);
fd.setVisible(true);
StringBuffer sbPath = new StringBuffer(fd.getDirectory());
sbPath=sbPath.reverse();
sbPath.append("///:elif");
sbPath=sbPath.reverse();
String fileName = fd.getFile();
if (fileName == null)
return;
else sbPath.append(fileName);
mediaFile=sbPath.substring(0);
myInitialize();
PlayWindow();
else if(arg=="Close"){
this.myPlayer.stop();
this.myPlayer.deallocate();
this.myPlayer.close();
System.exit(0);
else if (arg=="Add Video")
FrameGrabbingControl fgc = (FrameGrabbingControl)myPlayer.
getControl("javax.media.control.FrameGrabbingControl");
if (fgc != null)
Buffer buf = fgc.grabFrame();
BufferToImage btoi = new BufferToImage( (VideoFormat) buf.getFormat());
BufferedImage img = (BufferedImage) btoi.createImage(buf);
ImageIcon ii = new ImageIcon(img);
JLabel l = new JLabel(ii);
JOptionPane.showMessageDialog( this, l );
//vsr.example.Main.StartSegmentation(img);
else
System.out.println("Its NULL");
public void myInitialize(){
if(mediaFile!=null){
try{
MediaLocator myMedia=new MediaLocator(mediaFile);
myPlayer=Manager.createRealizedPlayer(myMedia);
Control [] ctrls = myPlayer.getControls();
catch(Exception e){
System.err.println("No file selected");
myVisualComp=myPlayer.getVisualComponent();
if (myVisualComp!=null)
add("Center",myVisualComp);
myControlComp=myPlayer.getControlPanelComponent();
add("South",myControlComp);
validate();
public synchronized void controllerUpdate(ControllerEvent event){
public void PlayWindow(){
setSize(new Dimension(320,240));
setTitle("A Media Player using JMF");
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize=getSize();
if( frameSize.height> screenSize.height){
frameSize.height=screenSize.height;}
if(frameSize.width>screenSize.width){
frameSize.width=screenSize.width;
setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);
setVisible(true);
if(mediaFile!=null){
myPlayer.start();
public static void main(String[] argv)
MyMediaWindow mmw = new MyMediaWindow();
mmw.PlayWindow();
}</sscce> -
Hope that got your attention! Well folks hi there. I'm hoping you can help me out a bit on this one. I've got a JFrame GUI app with the following Components: 1 JLabel, 1 JTextField, 1 JButton, 1 JTextPane, and a menu system up top. It looks "about" like this:
| File Edit Help |
| |----------------------------------------| |----------------| |
| Enter URL | | | Print | |
| |----------------------------------------| |----------------| |
| ------------------------------------------------------------------------------- |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | ---------------------------------------------------------------------------- | |
|-------------------------------------------------------------------------------------|The problem is, with the JTextPane set as not 'enabled' 'setEnabled( false)', I simply can not navigate out of it using the keyboard Tab key (or any other for that matter, not that I'd want to use another key).
If I setEnabled( true), it's fine. But, as I said not if 'false'. I've tried requestFocus(), setNextFocusableComponent( Component), even grabFocus() from the JTextPane to try to go either forwards or backwards from the JTextPane to either the JButton or the JTextField, but it seems trapped in the JTextPane.
When I do printlns from the keyPressed and focusGained methods, it shows that the next JComponent - beit JButton or JTextField - gets focus, but it dosn't really (or I should say practically), since all keys at that point are rendered useless, and I need to break out with the mouse.
I did not look through the 1.3.1_04 (version I'm on) bug reports. Anyone know a solution to this? Thanks in advance.
~Bill1. It took a little time, but I recoded OUT all the other classes. You'll still need your own 'Readme.html' file and you own *.gif icon file, but that's it. Here's the code ... it is still - even beyond this pblm - in dev phase:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import javax.swing.text.html.HTMLEditorKit;
import java.net.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.JarURLConnection;
public class JTestURLPane extends JFrame implements ActionListener {
private static final String USAGE = "Usage java JTestURLPane <URL>",
BJB_IMAGE = "BJ_icon01.gif", // use your own icon
EOL = System.getProperty("line.separator"),
USER_HOME = System.getProperty( "user.home" ),
FILE_MENU = "File",
EDIT_MENU = "Edit",
HELP_MENU = "Help",
PREF_MENU = "Preferences",
NEW_MENUITEM = "New",
OPEN_MENUITEM = "Open",
EXIT_MENUITEM = "Exit",
COPY_MENUITEM = "Copy",
PASTE_MENUITEM = "Paste",
ABOUT_MENUITEM = "About",
CNTNT_MENUITEM = "Contents",
ABOUT = "About JTestURLPane",
HLINK_LABEL = "Key in H-Link URL and hit Enter",
PRINT_LABEL = "Print document",
README = "file:/C:/Readme.html"; // Or whereever
private static final String[] helpAbout = new String[] {
"Version 1.0.0 blah blah blah",
"A product of more blah blah blah",
"Last updated: all the time" };
private static boolean debugger;
private int keyHit;
private String readme,
copypaste,
componentHit,
chosenFileName,
lastDir,
property;
private File chosenFile;
private Container container;
private JPanel jp;
private JLabel jlA,
jlB;
private JTextField jtf;
private JButton jb;
private JTextPane jtp;
private JScrollPane jsp;
private FileDialog filedialogopen;
private JMenuBar jmbar;
private JMenu jmfile,
jmedit,
jmhelp;
private JMenuItem jmfnew,
jmfopen,
jmfexit,
jmecopy,
jmepaste,
jmhabout,
jmhcontents;
private JSeparator jsep1,
jsep2;
private Font menuFace;
private Image bjBImage;
public JTestURLPane( String urlString ) throws Exception {
this( new URL( urlString ) );
public JTestURLPane( URL _url ) {
super( "JTestURLPane" );
bjBImage = Toolkit.getDefaultToolkit().getImage(
JTestURLPane.class.getResource( BJB_IMAGE ) );
Toolkit.getDefaultToolkit().beep();
menuFace = new Font("Dialog", Font.PLAIN, 12);
container = getContentPane();
jp = new JPanel();
jlA = new JLabel( HLINK_LABEL );
jlB = new JLabel( PRINT_LABEL );
jtf = new JTextField( 20 );
jb = new JButton( "Print" );
jtp = new JTextPane(); //JEditorPane();
jsp = new JScrollPane( jtp,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
jp.setLayout( new FlowLayout( FlowLayout.LEFT ) );
jtp.setEditable( false );
jp.setBackground( Color.lightGray );
jtp.setBackground( Color.lightGray );
jsp.setBackground( Color.lightGray );
jb.setBackground( Color.lightGray );
jp.add( jlA );
jp.add( jtf );
jp.add( jlB );
jp.add( jb );
container.add( jp, BorderLayout.NORTH );
container.add( jsp );
lastDir = "";
try {
setPageURL( _url );
catch( Exception e ) {
if ( debugger ) {
System.out.println( "constructor\n"+e );
jtf.addFocusListener( new FocusAdapter() {
public void focusGained( FocusEvent fe ) {
if ( debugger ) {
System.out.println( "jtf has focus" );
jtf.addKeyListener( new KeyAdapter() {
public void keyPressed( KeyEvent ke ) {
keyHit = ke.getKeyCode();
if ( debugger ) {
System.out.println( "jtf - key hit: "+keyHit );
if ( keyHit == 10 ) {
chosenFileName = jtf.getText();
chosenFileName = chosenFileName.startsWith( "http" ) ? chosenFileName : "http://"+chosenFileName;
try {
setPageURL( chosenFileName );
catch( Exception e ) {
if ( debugger ) {
System.out.println( "constructor\n"+e );
else
if ( keyHit == 9 ) {
jb.requestFocus();
jb.addFocusListener( new FocusAdapter() {
public void focusGained( FocusEvent fe ) {
if ( debugger ) {
System.out.println( "jb has focus" );
jb.addKeyListener( new KeyAdapter() {
public void keyPressed( KeyEvent ke ) {
keyHit = ke.getKeyCode();
if ( debugger ) {
System.out.println( "jb - key hit: "+keyHit );
if ( keyHit == 10 ) {
new JPrintIt().print( jtp );
else
if ( keyHit == 9 ) {
jtp.requestFocus();
jb.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent ae ) {
if ( debugger ) {
System.out.println( "jb - clicked" );
new JPrintIt().print( jtp );
jtp.addFocusListener( new FocusAdapter() {
public void focusGained( FocusEvent fe ) {
if ( debugger ) {
System.out.println( "jtp has focus" );
jtp.addKeyListener( new KeyAdapter() {
public void keyPressed( KeyEvent ke ) {
keyHit = ke.getKeyCode();
if ( debugger ) {
System.out.println( "jtp - key hit: "+keyHit );
if ( keyHit == 9 ) {
jtf.requestFocus();
( ( HTMLEditorKit ) ( jtp.getEditorKit() ) ).setLinkCursor( new Cursor( Cursor.HAND_CURSOR ) );
jtp.addHyperlinkListener( new HyperlinkListener() {
public void hyperlinkUpdate( HyperlinkEvent hle ) {
try {
if ( hle.getEventType() == HyperlinkEvent.EventType.ACTIVATED ) {
jtp.setPage( hle.getURL() );
catch( Exception e ) {
if ( debugger ) {
System.out.println( "constructor\n"+e );
jmbar = new JMenuBar();
jmfile = new JMenu( FILE_MENU );
jmedit = new JMenu( EDIT_MENU );
jmhelp = new JMenu( HELP_MENU );
jmfnew = new JMenuItem( NEW_MENUITEM );
jmfopen = new JMenuItem( OPEN_MENUITEM );
jsep1 = new JSeparator();
jmfexit = new JMenuItem( EXIT_MENUITEM );
jmecopy = new JMenuItem( COPY_MENUITEM );
jmepaste = new JMenuItem( PASTE_MENUITEM );
jmhabout = new JMenuItem( ABOUT_MENUITEM );
jsep2 = new JSeparator();
jmhcontents = new JMenuItem( CNTNT_MENUITEM );
jmfile.setMnemonic( 'F' );
jmedit.setMnemonic( 'E' );
jmhelp.setMnemonic( 'H' );
jmfnew.setMnemonic( 'N' );
jmfopen.setMnemonic( 'O' );
jmfexit.setMnemonic( 'x' );
jmecopy.setMnemonic( 'C' );
jmepaste.setMnemonic( 'P' );
jmhabout.setMnemonic( 'B' );
jmhcontents.setMnemonic( 'T' );
jmfnew.setAccelerator(KeyStroke.getKeyStroke( "control N" ) );
jmfopen.setAccelerator(KeyStroke.getKeyStroke( "control O" ) );
jmfexit.setAccelerator(KeyStroke.getKeyStroke( "control shift X" ) );
jmecopy.setAccelerator(KeyStroke.getKeyStroke( "control shift C" ) );
jmepaste.setAccelerator(KeyStroke.getKeyStroke( "control shift V" ) );
jmhabout.setAccelerator(KeyStroke.getKeyStroke( "control B" ) );
jmhcontents.setAccelerator(KeyStroke.getKeyStroke( "control T" ) );
jmbar.setBackground( Color.lightGray );
jmfile.setBackground( Color.lightGray );
jmedit.setBackground( Color.lightGray );
jmhelp.setBackground( Color.lightGray );
jmfnew.setBackground( Color.lightGray );
jmfopen.setBackground( Color.lightGray );
jmfexit.setBackground( Color.lightGray );
jmecopy.setBackground( Color.lightGray );
jmepaste.setBackground( Color.lightGray );
jmhabout.setBackground( Color.lightGray );
jmhcontents.setBackground( Color.lightGray );
jmfile.setFont( menuFace );
jmedit.setFont( menuFace );
jmhelp.setFont( menuFace );
jmfnew.setFont( menuFace );
jmfopen.setFont( menuFace );
jmfexit.setFont( menuFace );
jmecopy.setFont( menuFace );
jmepaste.setFont( menuFace );
jmhabout.setFont( menuFace );
jmhcontents.setFont( menuFace );
jmfnew.addActionListener( this );
jmfopen.addActionListener( this );
jmfexit.addActionListener( this );
jmecopy.addActionListener( this );
jmepaste.addActionListener( this );
jmhabout.addActionListener( this );
jmhcontents.addActionListener( this );
jmfile.add( jmfnew );
jmfile.add( jmfopen );
jmfile.add( jsep1 );
jmfile.add( jmfexit );
jmedit.add( jmecopy );
jmedit.add( jmepaste );
jmhelp.add( jmhabout );
jmhelp.add( jsep2 );
jmhelp.add( jmhcontents );
setJMenuBar( jmbar );
jmbar.add( jmfile );
jmbar.add( jmedit );
jmbar.add( jmhelp );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
dispose();
setIconImage( bjBImage );
setSize( 800, 600 );
setVisible( true );
public void setPageURL( String pageURL ) throws Exception {
this.setPageURL( new URL( pageURL ) );
public void setPageURL( URL _url ) throws Exception {
if ( _url == null ) {
throw new IllegalArgumentException( "In setPageURL" );
jtp.setPage( _url );
public void actionPerformed(ActionEvent event) {
componentHit = event.getActionCommand();
if ( componentHit.equals( NEW_MENUITEM ) ) {
getFileDialog( 'N' );
else
if ( componentHit.equals( OPEN_MENUITEM ) ) {
getFileDialog( 'O' );
else
if ( componentHit.equals( EXIT_MENUITEM ) ) {
dispose();
System.exit( 0 );
else
if ( componentHit.equals( COPY_MENUITEM ) ) {
copypaste = jtp.getText(); // This is an internal app copy, not to clipboard.
else
if ( componentHit.equals( PASTE_MENUITEM ) ) {
jtp.setText( copypaste ); // This is an internal app paste, not to clipboard.
else
if ( componentHit.equals( ABOUT_MENUITEM ) ) {
doHelpAbout();
else
if ( componentHit.equals( CNTNT_MENUITEM ) ) {
doHelpContents();
else {
if ( debugger ) {
System.out.println( "Error - actionPerformed method - componentHit == "
+ componentHit );
public void getFileDialog( char isNew ) {
if ( isNew == 'N' ) {
jtp.setText( "" );
return;
filedialogopen = new FileDialog( this, "Open", FileDialog.LOAD );
if ( !lastDir.equals( "" ) ) {
filedialogopen.setDirectory( lastDir );
filedialogopen.show();
lastDir = filedialogopen.getDirectory();
chosenFileName = filedialogopen.getDirectory() + filedialogopen.getFile();
chosenFile = new File( chosenFileName );
try {
if ( chosenFile.isFile() ) {
if ( debugger ) {
System.out.println( "file:/"+chosenFileName );
setPageURL( "file:/"+chosenFileName );
catch( Exception e ) {
if ( debugger ) {
System.out.println( "getFileDialog\n"+e );
* This is really another class to display messages graphically
public void doHelpAbout() {
for ( int idx=0; idx < helpAbout.length; idx++ ) {
System.out.println( helpAbout[idx] );
public void doHelpContents() {
try {
// setPageURL( JTestURLPane.class.getResource( README ) );
JTestURLPane jturlp = new JTestURLPane( README );
jturlp.setBounds( 100, 100, 600, 400 );
catch( Exception e ) {
if ( debugger ) {
System.out.println( "getFileDialog\n"+e );
public static void main( String[] argv) {
debugger = true;
switch( argv.length ) {
case 0: {
try {
// new JTestURLPane( JTestURLPane.class.getResource( README ) );
new JTestURLPane( README );
catch( Exception e ) {
System.out.println( "Exception in 'main' method\n"+e );
e.printStackTrace();
break;
case 1: {
try {
new JTestURLPane( argv[0] );
catch( Exception e ) {
System.out.println( "Exception in 'main' method\n"+e );
break;
default: {
System.out.println( USAGE );
System.exit ( -1 );
}~Bill
Maybe you are looking for
-
Am trying to install apps from the store but each time am getting a message that a newer version of ipad software is required
-
Adobe Illustrator CS6 crashes with spinning ball on MAC OS X 10.6.8 on new or existing files. Help? Message was edited by: stanbujak
-
HTML link to a Flash file frame
> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --B_3299492325_1333456 Content-type: text/plain; charset="US-ASCII" Content-transfer-encoding: 7bit Hi I've got
-
Dynamic From Menu with Sub Menu
I am trying to create a form where it has a drop down menu that depending on what you select, will change the 2nd drop down menu. For example, you would select one of the 50 states in the first one (data pulled from Mysql) then then when you select a
-
I have some custom buttons added to the sales order screen. When the font in B1 is set to "10", the buttons show up and are aligned just fine. When the user changes the font to anything other than "10", the buttons become mis-aligned and moved on t