I wrote a media player in Java using the Java Media Framework (yeah, I know it's really old!)
on Netbeans, and I have this problem:
I have a browse button which selects the file, initializes the Player and starts playback. The problem is, the button is in private void and hence the player is not accessible across the form.
This is the jButton code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Player pla;
try{
FileDialog fd = new FileDialog(this, "Select File", FileDialog.LOAD);
fd.show();
String filename = fd.getDirectory() + fd.getFile();
pla=Manager.createPlayer(new MediaLocator("file:///"+filename));
pla.start();
}
catch (Exception e){
System.out.println(e.toString());
}
// TODO add your handling code here:
}
How do I make the player pla across the Jpanel so that any button in the panel (Netbeans automatically sets all jButtons to private void) can access the player pla?
P.S.: Someone please suggest me a modern API (other than Xuggler) for Java media, preferably, using FFMPEG but not necessarily.
Thanks!
The class player can have a method
By reflexion you can return any button
JButton getButton(String nameButton) throws Exception{
Field field = clazz.getClass().getField(nameButton);
return (JButton) field.get(this);
}
Related
I am adding to an existing codebase using the Netbeans Platform (14) and its GUI builder to display user selected data to create an output file. The user selects the inputs, then selects to generate the file using a default file name. I want to interrupt the process with a dialog presenting the user with a summary of what they entered, a TextField containing the default file name and the OK - Cancel buttons. I created a DialogDisplayer configured by a DialogDescriptor containing a JPanel which contains the summary info and file name JTextField. This all works, I see the summary data, am able to modify the file name but selecting the OK or Cancel doesn't close the window. Only the X in the upper right will close it.
My actionPerformed() method gets called and exercises the code appropriate to the selected button, but just can't figure out how to close the window from there. I tried setting the closing options to null (dd.setClosingOptions(null);) which the API says causes all action to close the window. No dice.
I don't see a method to call to close the DialogDisplayer window in the API.
I originally thought of using a JDialog but it requires a Frame, which I can't figure out how to get from a org.netbeans.spi.project.ActionProvider, the enclosing class that initiates the request. I have used Swing for more years than I care to admit (since java 1.1) but the Netbeans Platform framework is new to me.
Here is my code:
private class FileNameDialog extends JPanel implements ActionListener
{
private final JTextField fileNameField = new JTextField(50);
private final JLabel fileNameLabel = new JLabel("File Name");
private final JLabel infoLabel = new JLabel();
private final JPanel entryPanel = new JPanel(new FlowLayout());
public FileNameDialog(String fileName, String info)
{
infoLabel.setText(info);
fileNameField.setText(fileName);
setLayout(new BorderLayout());
entryPanel.add(fileNameLabel);
entryPanel.add(fileNameField);
add(BorderLayout.CENTER, infoLabel);
add(BorderLayout.PAGE_END, entryPanel);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(OK_BUTTON))
{
//Replace the file name with what was entered and move on
abort = false; //Global field in enclosing class
logger.log(Level.INFO, "Setting abort to FALSE for {0}",
fileNameField.getText());
}
else if (e.getActionCommand().equals(CANCEL_BUTTON))
{
abort = true; //Global field in enclosing class
logger.log(Level.INFO, "Setting abort to TRUE");
}
//Close the Dialog Window Here (somehow)
}
}
/**
* Request text entry from the user. Currently used for displaying the
* file name and allowing the user to update it. This is the entry point
* for all this code.
* #param info summary text
* #param title window title
* #return the user entered String
*/
private String userRequestDialog(String info, String title, String fileName)
{
FileNameDialog fileNameDialog = new FileNameDialog(fileName, info);
Object [] options = { new JButton ("OK"),
new JButton ("Cancel")};
DialogDescriptor dd = new DialogDescriptor (fileNameDialog,
title,
true,
options,
null,
DialogDescriptor.DEFAULT_ALIGN,
null,
fileNameDialog);
DialogDisplayer.getDefault().notify(dd); //Display the window
dd.setClosingOptions(null); //Doesn't seem to have any effect
return fileNameDialog.fileNameField.getText(); //FileName to use as process continues
}
Just for giggles, I tried Object frame = lookup.lookup(JFrame.class); but that comes back as null.
#jjazzboss - You had the answer that solved my problem and you should get the credit.
Though it technically didn't answer the question, it allowed me to replace the Netbeans DialogDisplayer with a JOptionPane as in below. I also tried a CustomDialog modeled after the one in https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html, but the OK and Cancel buttons still didn't close it. I suspect that something in Netbeans is stealing those events because a breakpoint in the listener never got hit (or I screwed up the code).
boolean cancelled = false;
Frame frame = WindowManager.getDefault().getMainWindow();
while (!cancelled)
{
String newFileName = JOptionPane.showInputDialog(frame, info, fileName);
if (newFileName == null) //OK was not selected
{
return null;
}
else if (isValidFileName(newFileName))
{
return newFileName;
}
else
{
JOptionPane.showMessageDialog(
frame,
"Sorry, \"" + newFileName + "\" "
+ "isn't a valid file name.\n"
+ "Please Try again",
"Bad File Name",
JOptionPane.ERROR_MESSAGE);
}
}
I am trying to make a game and attempting to make a "mute" and "unmute" button, but I cant figure out how to make it so when you push the button it stops the same clip that is being played at the beginning of the program. (using different methods of course).
I attempted to make the clip and audio public, but I keep getting an error and I'm not sure why.
public class TowerDefense
{
String filepath = "MenuTheme.wav";
private Clip clip;
void playMusic(String musicLocation)
{
try{
File musicPath = new File(musicLocation);
if(musicPath.exists())
{
AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
clip = AudioSystem.getClip();
clip.open(audioInput);
clip.start();
clip.loop(Clip.`LOOP_CONTINUOUSLY`);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
void pauseMusic(String musicLocation2)
{
long clipTimePosition = clip.getMicrosecondPosition();
clip.stop();
}
==============
//this is in a different private method called Options
panel.setButtonsActionListener2(**new** ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
frame.dispose();
TowerDefense musicObject = new TowerDefense();
musicObject.pauseMusic(filepath);
Options();
}
});
I was expecting an output of the clip stopping and then you can either make it play again or keep it muted. In this case it just says error when I press the "mute" button.
So, in the code that runs when you click your mute button, you are making a new TowerDefense object that is supplied the music's filepath. Here is the issue with that. The clip that is already playing exists in the program. Creating a new TowerDefense object will not automatically give you access to the clip that is playing.
Ensure that you call the pauseMusic method on the same object where you called the playMusic method.
Thus, if you already have created a TowerDefense object in the program and called playMusic, then give your action listener access to that object and use the existing object to call pauseMusic.
I am relatively new to Java and recently I have been working on a GUI based html parser.
The interface is simple, consisting of:
JTextField for entering a search term
JButton b1 to initiate the search
JButton b2 to exit
JButton b3 to display an URL in the browser using cmd prmt.
The problem arises with b3.
Here is a code sample:
while (mstyle2.find())
{
String s=mstyle2.group(0);
String pattern = "(?i)(<cite.*?>)(.+?)(</cite>)";
String updated = s.replaceAll(pattern, "$2");
String pattern2 = "(?i)(<b>)(.+?)(</b>)";
String updated2 = updated.replaceAll(pattern2, "$2");
String pattern3 = "(http://)";
boolean c=true;
String updated32 = updated2.replaceAll(pattern3, "");
String pattern32 = "(https://)";
final String updated3 = updated32.replaceAll(pattern32,"");
try {
URL url2 = new URL("http://"+updated3);
URLConnection conne = url2.openConnection();
conne.connect();
} catch (MalformedURLException e) {
c=false;
} catch (IOException e) {
c=false;//checks validity of url
}
if(c) {
Process p=Runtime.getRuntime().exec("cmd /c start http://"+updated3);
}
}
The idea is that the following command line should only be executed when b3 is pressed. Otherwise the loop will not execute, and remain in that line until the button is pressed.
Process p=Runtime.getRuntime().exec("cmd /c start http://"+updated3);
However, I cannot find any viable way to properly implement the ActionListener method in order to make this possible.
In most of my tries, once b3 is pressed, all link open at once (thus beating the purpose of the b3) and not one by one with every click of b3.
Solution
JButtons has a method called addActionListener(). This method allows you to attach a runnable to a button, so the code is only called when it is clicked.
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Your code here!
}
});
What is this doing?
Well this is adding a new ActionListener object to your button. However, ActionListener has an abstract method, actionPeformed that needs an implementation. You are simply providing the code in the constructor.
I've created a Swing application with several JInternalFrames which gets added to a JDesktopPane on the event of a mouse click. I want only one instance of the same Internal frame to be present on the DesktopPane. I dont want the same frame to appear twice when the user opens the frame..
The simple solution to your problem is to create an HashMap<String,JInternalFrame>. The key will be the title of that JInternalFrame and value will be the object of that JInternalframe opened currently.Save the (key,value) pair in HashMap when the internal frame is opened first time. Disable the close button for all JInternalFrame window , so that user can't dispose the displayed JInternalFrame window. Register esc key to each JInternalFrame object , so that when esc button of keyboard is pressed the currently display JInternalFrame is minimized on the DesktopPane.Now When you click on menu item to open that same internal frame, check if the title of that JInternalFrame is existing in that HashMap askey. If it exists then retrieve the value for that key and refer it by JInternalFrame variable and then restore the same on DesktopPane. If the corresponding entry of title doesn't exist in that HashMap , create a new JInternalFrame object, make an entry for same in the HasMap and display it.
Note: Whatever I have posted here is the solution for the situation where
you can have many types of JInternalFrame each having unique
different functionality, and you want to keep only one instance of
each of those JInternalFrame.
Here is may sample code. hope this help.
Menu action to call internal frame in main application where JdesktopPane in it.
private void YourJinternalFrameMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
YourJinternalFrame nw = YourJinternalFrame.getInstance();
nw.pack();
//usefull part for you.. if open shows, if not creates new one
if (nw.isVisible()) {
} else {
desktopPane.add(nw);
nw.setVisible(true);
}
try {
nw.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(MainApplication.class.getName()).log(Level.SEVERE, null, ex);
}
}
put this inside of your YourJinternalFrame
private static YourJinternalFrame myInstance;
public static YourJinternalFrame getInstance() {
if (myInstance == null) {
myInstance = new YourJinternalFrame();
}
return myInstance;
Try this simple code :
YourJinternalFrame nw = new YourJinternalFrame();
private void YourJinternalFrameMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
if(!nw.isVisible()){
YourJDesktopPane.add(nw);
nw.setVisible(true);
}
}
Try this simple code
take class variable chk and set equal to 0
then call jframe method
componentremoved
in this set chk =0 again
and if you call your internal frame set
chk =1
and compare chk on calling internal wheather it is zero or not
thats all
I went for a different solution:
final JInternalFrame[] frames = desktopPane.getAllFrames();
if( !Arrays.asList(frames).contains(loginFrame) ) {
loginFrame = new LoginFrame();
desktopPane.add(loginFrame);
loginFrame.setVisible(true);
}
This worked for me (checking for the class name):
final JInternalFrame[] frames = desktopPane.getAllFrames();
LoginFrame loginFrame = new LoginFrame();
if( !Arrays.asList(frames).toString().contains("LoginFrame") ) {
desktopPane.add(loginFrame);
loginFrame.setVisible(true);
loginFrame.validate();
}
i write a method to create a form(3 buttons and a textBox), then i call it in main.
but when i run program, before i enter information in the form (method form6 ),
Other commands that are executed! "s4 and ontname chenged in the form".
this is a part of my code:::::::::::
//////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
System.out.println("*begin main*"); // call form method
String s4= form6(); // s4 is returned by method.
System.out.println("s3333*"+s4);
System.out.println("ont:"+ontname);//it's global }
//////////////////////////////////////////////////////////////////////////
i have 2 questions:::
1--- While the form is running, other commands are executed!
What is their order execution?
2. --- i want to define a button to when i click it,it closes the form.
thanks all.
If I get your code correctly, ontname is either (1) a class member (declared outside a method) or (2) a local variable, which is declared in the method that contains this code snippet.
In both cases there is no need to "return" ontname just because it is not declared inside the anonymous ActionListener instance.
The following example illustrates a typical pattern for this problem:
public void someMethod() {
// ...
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
setOntName(selFile.getPath()); // <-- here we call another method
}
});
// ...
}
void setOntName(String ontName) {
// do something with ontName
}
Alternativly: declare ontName as a static class member (only):
private static String ontName = ""; // <-- accessible from main method
public static void main(String[] args) {
// ...
}
// more methods.
You can't return a value in this Method because the ActionListenerInterface does not allow this. But you can call another method from within the actionPerformed() method and pass the ontname to it.
You can also close the third button in the new method. Or define the third button as final and use it in the actionPerformed() method.
E.g.
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
anotherMethod(ontname);
}
});
private void anotherMethod(String path) {
//doSomething with the path
//close third button here
}
You could probably define your variable ontname as global, outside of your function:
var ontname = null;
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// ...
ontname=selFile.getPath();
}
});
// ...
System.out.println("filepath: "+ontname);
If you want to remember the values, then they should be class level variables.
But, generally, you would want to pass these to some other method to do some processing on them (or, say, persist them in a file). You can pass these as parameters to the other method.
(The second one is better in most cases, I don't know much about your app, so I am unable to give one answer)
There are other problems with your code:
You need to check whether the use has clicked the "Ok" or "Cancel" button in the open dialog to decide whether to get the file or not.
String filename = File.separator+"c:"; does not really make sense. Perhaps you meant String filename = "c:"+File.separator; But even this is not very useful. File.separator is for getting the platform specific file separator char (\ in Windows, / on linux) but since you are hard coding c:, you are anyway constrainting your app to Windows. You might want to have a better platform independent way (start at the "default" path, new JFileChooser() without arguments, and then remember the path the user last used, and proceed from there)
If the argument to the showOpenDialog method is your parent frame, then the dialog would be centered on the parent frame, and would, in most cases, look nicer.
You might also want to relook your variable names.
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
int option = fc.showOpenDialog(null);
if(option = JFileChooser.APROVE_OPTION)
{
File selFile = fc.getSelectedFile();
String ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
doSomeOperation(ontname); //Or, declare ontname as a class level variable.
}
}
});