I have written this code for a simple music player, the problem is that when I click openLabel and open a song and then when I pause it by clicking playLabel the program stops execution (program hangs).
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.Random;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class A extends MouseAdapter implements ChangeListener, Runnable {
private ImageIcon playImage = new ImageIcon(getClass().getResource("Images/play.png"));
private ImageIcon pauseImage = new ImageIcon(getClass().getResource("Images/pause.png"));
private ImageIcon openImage = new ImageIcon(getClass().getResource("Images/open.png"));
private JLabel playLabel = new JLabel(playImage);
private JLabel openLabel = new JLabel(openImage);
public JFrame frame = new JFrame();
public JPanel colorPanel = new JPanel();
private enum Status {ON,OFF,PAUSE,END};
private Status playStatus=Status.OFF;
private JSlider slider = new JSlider();
public Clip songClip;
Thread screenThread = new Thread(this);
public static void main(String arg[]) throws Exception {
new A();
}
public A() throws Exception {
setFrame();
setComponents();
}
public void setFrame() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setCursor(new Cursor(Cursor.HAND_CURSOR));
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
}
public void setComponents() {
slider.setBounds(0,640,1000,15);
slider.setBackground(Color.BLACK);
slider.addChangeListener(this);
slider.setValue(0);
playLabel.setBounds(450,665,100,100);
playLabel.addMouseListener(this);
openLabel.setBounds(540,690,60,60);
openLabel.addMouseListener(this);
colorPanel.setBackground(Color.BLACK);
colorPanel.setBounds(0,100,1500,500);
frame.add(openLabel);
frame.add(playLabel);
frame.add(colorPanel);
frame.add(slider);
}
public void mouseClicked(MouseEvent clicked) {
if (clicked.getSource() == openLabel) {
openLabel.setIcon(openImage);
open();
}
else if (clicked.getSource()==playLabel && playStatus != Status.OFF) {
if (playStatus == Status.PAUSE) {
songClip.start();
screenThread.resume();
playStatus=Status.ON;
playLabel.setIcon(pauseImage);
}
else if (playStatus == Status.ON) {
songClip.stop();
screenThread.suspend();
playStatus=Status.PAUSE;
playLabel.setIcon(playImage);
}
else if (playStatus==Status.END) {
songClip.setMicrosecondPosition(0);
slider.setValue(0);
songClip.start();
screenThread.resume();
playStatus = Status.ON;
playLabel.setIcon(pauseImage);
}
}
}
public void stateChanged(ChangeEvent e) {
if (playStatus != Status.OFF) {
JSlider jslider = (JSlider)e.getSource();
int position = jslider.getValue();
songClip.setMicrosecondPosition(position * 1000000);
}
}
public void open() {
JFileChooser chooseSong = new JFileChooser();
chooseSong.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooseSong.setFileFilter(new FileNameExtensionFilter(null, "wav"));
int chooseButton = chooseSong.showOpenDialog(null);
File songPath = chooseSong.getSelectedFile();
if ( (chooseButton!=JFileChooser.CANCEL_OPTION) && (songPath!=null) && (songPath.getName() != null) ) {
try {
playLabel.setIcon(pauseImage);
if (playStatus != Status.OFF)
songClip.close();
AudioInputStream songFile = AudioSystem.getAudioInputStream(songPath);
songClip = AudioSystem.getClip();
songClip.open(songFile);
int clipLength = (int)(songClip.getMicrosecondLength() / 1000000);
slider.setMinimum(0);
slider.setMaximum(clipLength);
songClip.start();
if (playStatus == Status.OFF)
screenThread.start();
else if (playStatus != Status.OFF)
screenThread.resume();
playStatus=Status.ON;
}
catch(Exception exp) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, String.format("ERROR = %s",exp.getClass()));
System.exit(0);
}
}
}
public void run() {
while (true) {
colorPanel.setBackground(new Color(new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256)));
if (songClip.getMicrosecondPosition() == songClip.getMicrosecondLength()) {
screenThread.suspend();
playStatus=Status.END;
playLabel.setIcon(playImage);
}
}
}
}
This method has been deprecated, as it is inherently deadlock-prone.
This is the reason that is given for the deprecation of Thread.stop(), .suspend() and .resume(). As you are using these in your code it could be the problem.
You are calling screenThread.suspend(); in the block that responds to clicking the play/pause button. Thread methods suspend() and resume() are deadlock prone - that is, using them often causes hard-to-diagnose issues like the one you're having.
You need to remove the use of these methods by instead polling a variable, as described on this page.
Related
I am programming a top-down shooter game, and I want to open a new window between each level of the game. After each level, if a certain criteria is met then the following class is implemented:
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Image.*;
import java.awt.image.BufferedImage.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.*;
import javax.imageio.ImageIO;
import java.io.InputStream.*;
import java.io.*;
public class Shop extends JFrame implements Runnable
{
private static java.awt.image.BufferedImage shotgun, zombie, armor, aRifle;
static ArrayList<Image> stock = new ArrayList<Image>();
private ColorPanel contentPane3;
private JPanel container = new JPanel();
private JPanel contentPane4;
private int item=0;
private boolean broke = false;
private boolean newb = true;
private boolean reg = false;
private boolean stay = true;
public static void main(String [] args)
{
System.out.println("started");
Thread s = new Thread( new Shop () );
System.out.println("running");
s.start();
System.out.println("ended");
}
public Shop()
{
super("Monster Escape v4");
try
{
shotgun = ImageIO.read(getResource("shotgun.png"));
zombie = ImageIO.read(getResource("zombie.png"));
armor = ImageIO.read(getResource("armor.png"));
aRifle = ImageIO.read(getResource("assaultRifle.png"));
}catch (IOException e){System.exit(0);}
stock.clear();
stock.add(armor);
if(!(Client.inventory.contains("shotgun")))
stock.add(shotgun);
if(!(Client.inventory.contains("assaultRifle")))
stock.add(aRifle);
container.removeAll();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane4 = new JPanel();
contentPane4.setPreferredSize(new Dimension( 700,100 ));
contentPane3 = new ColorPanel(Color.WHITE);
contentPane3.setPreferredSize(new Dimension( 700,700 ));
setBounds( 100,100,606,719 );
setResizable(false);
GridLayout g1 = new GridLayout(1, 3);
contentPane4.setLayout(g1);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
JButton sleft = new JButton("←");
JButton sright = new JButton("→");
JButton buy = new JButton("buy");
JButton leave = new JButton("leave");
contentPane4.add(sleft);
contentPane4.add(buy);
contentPane4.add(sright);
contentPane4.add(leave);
sleft.addActionListener((e) -> {
broke = false;
newb = false;
if(item==0)
item = stock.size()-1;
else
item--;
});
sright.addActionListener((e) -> {
broke = false;
newb = false;
if(item==stock.size()-1)
item=0;
else
item++;
});
buy.addActionListener((e) -> {
broke = false;
newb = false;
if(stock.get(item) == armor)
{
if(Client.cash >= 100)
{
Client.maxHealth += 4;
Client.cash -= 100;
reg = true;
}
else
broke = true;
}
else
{
if(Client.cash >= 250)
{
Client.inventory.add(getName(item));
stock.remove(item);
Client.cash -= 250;
item--;
reg = true;
}
else
broke = true;
}
});
leave.addActionListener((e) -> {
stay = false;
});
container.add(contentPane3, BorderLayout.EAST);
container.add(contentPane4, BorderLayout.WEST);
setContentPane(container);
setVisible(true);
}
public static String getName(int i)
{
String temp = null;
if(stock.get(i) == armor)
temp = "armor";
else if(stock.get(i) == shotgun)
temp = "shotgun";
else if(stock.get(i) == aRifle)
temp = "assaultRifle";
return temp;
}
private InputStream getResource(String ref) throws IOException
{
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(ref);
if( in != null )
return in;
return new FileInputStream(ref);
}
public void run()
{
while(stay)
{
repaint();
try
{
Thread.sleep(10);
}catch( InterruptedException e ) { }
}
dispose();
}
}
This includes a ColorPanel subclass that isn't shown. In previous versions of my game, this has worked fine. However, I recently added a KeyListener subclass to my Client, and now nothing happens when I try to instantiate the thread. I created a main method in the Shop class itself to see where the issue is, and it seems that when the code reaches
Thread s = new Thread( new Shop () );
the system terminates entirely, since when I run main it only prints "started." What is causing this?
add
s.join();
after start. In this case main thread will wait until s thread will be finished.
I'm trying to make a trivia game in swing with CardLayout to change between screens in a single JFrame. I have a loop set to move through the states in my enumeration. Everything works quite well except for when, at the end of a game, if I choose to start a new game, it somehow goes to both the first and second states simultaneously. I'm not sure how this happens as this is the only state this happens in.
Code for main:
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.awt.CardLayout;
import java.awt.Color;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class Main
{
public enum State {SPLASH, PREQUESTION, QUESTION, WIN, LOSS};
public static JFrame frame;
public static JPanel content;
public static JPanel neutral;
public static int event;
public static Random rn = new Random();
public static Splash splash;
public static Prequestion eventStart;
public static Question question;
public static Win win;
public static Loss loss;
public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
frame = new JFrame("DREWcathalon");
content = new JPanel();
neutral = new JPanel();
CardLayout cards = new CardLayout();
content.setLayout(cards);
neutral.setBackground(Color.WHITE);
content.add(neutral, "neutral");
frame.add(content);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 750);
frame.setVisible(true);
cards.show(content, "neutral");
State gameState = State.SPLASH;
while (true)
{
switch(gameState)
{
case SPLASH:
event = 0;
splash = new Splash(content, cards);
splash.splashSound();
while (splash.holdState()){};
cards.show(content, "neutral");
gameState = State.PREQUESTION;
splash = null;
break;
case PREQUESTION:
event++;
eventStart = new Prequestion(event, content, cards);
while (eventStart.holdState()){};
cards.show(content, "neutral");
gameState = State.QUESTION;
eventStart = null;
break;
case QUESTION:
question = new Question(event, rn.nextInt(5)+1, content, cards);
while (question.holdState()){};
cards.show(content, "neutral");
if (question.rightState() && event > 9)
{
gameState = State.WIN;
}
else if (question.rightState())
{
gameState = State.PREQUESTION;
}
else
{
gameState = State.LOSS;
}
question = null;
break;
case WIN:
win = new Win(content, cards);
while(win.holdState()){};
cards.show(content, "neutral");
gameState = State.SPLASH;
win = null;
break;
case LOSS:
loss = new Loss(content, cards);
while(loss.holdState()){};
cards.show(content, "neutral");
gameState = State.SPLASH;
loss = null;
break;
}
}
}
}
Code for Win:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.sound.sampled.*;
import java.io.*;
public class Win
{
static private Clip clip;
static private boolean hold = true;
public Win(JPanel content, CardLayout cards) throws UnsupportedAudioFileException, IOException, LineUnavailableException
{
JButton restart = new JButton("New Game+");
JButton quit = new JButton("Flee");
JLabel title = new JLabel("A Winnar is You!");
JPanel wContent = new JPanel();
wContent.add(title);
wContent.add(restart);
wContent.add(quit);
wContent.setBackground(Color.WHITE);
content.add(wContent, "win");
cards.show(content, "win");
File soundFile = new File("TEST.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (clip.getMicrosecondPosition() < clip.getMicrosecondLength())
{
clip.stop();
}
hold = false;
}
});
quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public boolean holdState()
{
return hold;
}
}
I don't have the specific answer to your specific question, which is one reason I'm answering this as a Community Wiki, but I can state with confidence that your program structure is broken and is not written in a way that respects either object-oriented programming principles, as evidenced by your copious use of static fields, or GUI event-driven coding principles, as evidenced by your while (true) loop. The solution is to completely restructure your program, getting rid of your while (true) loop and instead use notifications / observer design pattern to drive state changes.
I can almost guarantee that if you fix these issues, especially by getting rid of the while (true) loop and replacing it with event notification and listening, your problem with game restart will resolve.
If you need more specific help, you'll want to create and post your valid SSCCE (please see the link for the details). I tried doing this myself with your code, but it's taking me too long, and the effort really should be yours.
A very simplistic example that uses simple notification to change state
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private MyState myState = MyState.SPLASH;
private MySplash mySplash = new MySplash(this);
private MyPreQuestion myPreQuestion = new MyPreQuestion(this);
private MyQuestion myQuestion = new MyQuestion(this);
public Main2() {
setLayout(cardLayout);
add(mySplash, MyState.SPLASH.toString());
add(myPreQuestion, MyState.PREQUESTION.toString());
add(myQuestion, MyState.QUESTION.toString());
mySplash.startSplashTimer();
}
public void next() {
int index = 0;
for (int i = 0; i < MyState.values().length; i++) {
if (MyState.values()[i] == myState) {
index = i;
}
}
index++;
index %= MyState.values().length;
setState(MyState.values()[index]);
}
public void setState(MyState nextState) {
myState = nextState;
cardLayout.show(this, nextState.toString());
if (myState == MyState.SPLASH) {
mySplash.startSplashTimer();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
enum MyState {
SPLASH, PREQUESTION, QUESTION // ..., WIN, LOSS
}
#SuppressWarnings("serial")
class NextAction extends AbstractAction {
private Main2 main;
public NextAction(Main2 main) {
super("Next");
putValue(MNEMONIC_KEY, KeyEvent.VK_N);
this.main = main;
}
#Override
public void actionPerformed(ActionEvent e) {
main.next();
}
}
#SuppressWarnings("serial")
abstract class AbstractView extends JPanel {
private Main2 main;
public AbstractView(Main2 main) {
this.main = main;
}
public Main2 getMain() {
return main;
}
public void next() {
main.next();
}
}
#SuppressWarnings("serial")
class MySplash extends AbstractView {
private static final int TIMER_DELAY = 3000;
private Timer timer;
public MySplash(Main2 main) {
super(main);
setPreferredSize(new Dimension(300, 140));
add(new JLabel("My Splash"));
}
public void startSplashTimer() {
timer = new Timer(TIMER_DELAY, e -> {
next();
timer.stop();
});
timer.start();
}
}
#SuppressWarnings("serial")
class MyPreQuestion extends AbstractView {
public MyPreQuestion(Main2 main) {
super(main);
add(new JLabel("Prequestion"));
add(new JButton(new NextAction(main)));
}
}
#SuppressWarnings("serial")
class MyQuestion extends AbstractView {
public MyQuestion(Main2 main) {
super(main);
add(new JLabel("Question"));
add(new JButton(new NextAction(main)));
}
}
I'm trying to figure out this for ages, starting to wonder if it is possible!
I have a starting window for my app - I need it so that when I click on a button I have created, the window either closes and opens a new window or the window resizes and leaves just the canvas (ready to put new widgets, sprites etc... ).
I know I need a handler event for this but I just can't get the code to work.
Im not quite sure whats your question but i coded a example with a JFrame and 3 Buttons.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class OpenWindowAndResizeWindow
{
private JFrame frame;
private JButton btnOpenNewWindow;
private JButton btnResizeWindow;
private JButton btnRemoveAllButtons;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
OpenWindowAndResizeWindow window = new OpenWindowAndResizeWindow();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public OpenWindowAndResizeWindow()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getBtnOpenNewWindow(), BorderLayout.NORTH);
frame.getContentPane().add(getBtnResizeWindow(), BorderLayout.SOUTH);
frame.getContentPane().add(getBtnRemoveAllButtons(), BorderLayout.CENTER);
frame.setVisible(true);
}
private void openNewWindow()
{
OpenWindowAndResizeWindow newWindow = new OpenWindowAndResizeWindow();
frame.dispose();
}
private void removeButtons()
{
getBtnOpenNewWindow().setVisible(false);
getBtnRemoveAllButtons().setVisible(false);
getBtnResizeWindow().setVisible(false);
}
private void resizeWindow()
{
Rectangle rectangle = frame.getBounds();
rectangle.width = (int)rectangle.getWidth() + 100;
rectangle.height = (int)rectangle.getHeight() + 100;
frame.setBounds(rectangle);
}
private JButton getBtnOpenNewWindow() {
if (btnOpenNewWindow == null) {
btnOpenNewWindow = new JButton("Open new Window");
btnOpenNewWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openNewWindow();
}
});
}
return btnOpenNewWindow;
}
private JButton getBtnResizeWindow() {
if (btnResizeWindow == null) {
btnResizeWindow = new JButton("Resize Window");
btnResizeWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resizeWindow();
}
});
}
return btnResizeWindow;
}
private JButton getBtnRemoveAllButtons() {
if (btnRemoveAllButtons == null) {
btnRemoveAllButtons = new JButton("Remove All Buttons");
btnRemoveAllButtons.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeButtons();
}
});
}
return btnRemoveAllButtons;
}
}
This code is ready to compile with javac or just paste it in your IDE.
Maybe this helps a bit. The Java SE API Documentation is useful too.
I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop?
Any info or point in the right direction greatly appreciated.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo
extends JPanel
implements ActionListener
{
JLabel selectedFileLabel;
JList selectedFilesList;
JLabel returnCodeLabel;
public FileChooserDemo()
{
super();
createContent();
}
void initFrameContent()
{
JPanel closePanel = new JPanel();
add(closePanel, BorderLayout.SOUTH);
}
private void createContent()
{
setLayout(new BorderLayout());
JPanel NorthPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem quit = new JMenuItem("Quit");
menuBar.add(menu);
menu.add(quit);
NorthPanel.add(menu,BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(7,1 ));
JButton openButton = new JButton("Open...");
openButton.setActionCommand("OPEN");
openButton.addActionListener(this);
buttonPanel.add(openButton);
JButton saveButton = new JButton("Save...");
saveButton.setActionCommand("SAVE");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
JButton delete = new JButton("Delete");
delete.addActionListener(this);
delete.setActionCommand("DELETE");
buttonPanel.add(delete);
add(buttonPanel, BorderLayout.WEST);
// create a panel to display the selected file(s) and the return code
JPanel displayPanel = new JPanel(new BorderLayout());
selectedFileLabel = new JLabel("-");
selectedFileLabel.setBorder(BorderFactory.createTitledBorder
("Selected File/Directory "));
displayPanel.add(selectedFileLabel, BorderLayout.NORTH);
selectedFilesList = new JList();
JScrollPane sp = new JScrollPane(selectedFilesList);
sp.setBorder(BorderFactory.createTitledBorder("Selected Files "));
MouseListener listener = new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.MOVE);
}
};
selectedFilesList.addMouseListener(listener);
displayPanel.add(sp);
returnCodeLabel = new JLabel("");
returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code"));
displayPanel.add(returnCodeLabel, BorderLayout.SOUTH);
add(displayPanel);
}
public void actionPerformed(ActionEvent e)
{
int option = 0;
File selectedFile = null;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE"))
{
System.exit(0);
}
else if (e.getActionCommand().equals("OPEN"))
{
JFileChooser chooser = new JFileChooser();
chooser.setDragEnabled(true);
chooser.setMultiSelectionEnabled(true);
option = chooser.showOpenDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
else if (e.getActionCommand().equals("SAVE"))
{
JFileChooser chooser = new JFileChooser();
option = chooser.showSaveDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
// display the selection and return code
if (selectedFile != null)
selectedFileLabel.setText(selectedFile.toString());
else
selectedFileLabel.setText("null");
DefaultListModel listModel = new DefaultListModel();
for (int i =0; i < selectedFiles.length; i++)
listModel.addElement(selectedFiles[i]);
selectedFilesList.setModel(listModel);
returnCodeLabel.setText(Integer.toString(option));
}
public static void main(String[] args)
{
SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
FileChooserDemo app = new FileChooserDemo();
app.initFrameContent();
JFrame frame = new JFrame("LoquetUP");
frame.getContentPane().add(app);
frame.setDefaultCloseOperation(3);
frame.setSize(600,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//frame.pack();
frame.setVisible(true);
}
});
}
}
This is my take on the idea. I've used the "traditional" drag and drop API in this example. It has some extra "paint" tweaks just to show off what you might be able to do.
This example doesn't scan folders dropped onto it, so any folder will only register as a single file, but I'm sure you can work it out
public class TestDragNDropFiles {
public static void main(String[] args) {
new TestDragNDropFiles();
}
public TestDragNDropFiles() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private DropTarget dropTarget;
private DropTargetHandler dropTargetHandler;
private Point dragPoint;
private boolean dragOver = false;
private BufferedImage target;
private JLabel message;
public DropPane() {
try {
target = ImageIO.read(new File("target.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
message = new JLabel();
message.setFont(message.getFont().deriveFont(Font.BOLD, 24));
add(message);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected DropTarget getMyDropTarget() {
if (dropTarget == null) {
dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, null);
}
return dropTarget;
}
protected DropTargetHandler getDropTargetHandler() {
if (dropTargetHandler == null) {
dropTargetHandler = new DropTargetHandler();
}
return dropTargetHandler;
}
#Override
public void addNotify() {
super.addNotify();
try {
getMyDropTarget().addDropTargetListener(getDropTargetHandler());
} catch (TooManyListenersException ex) {
ex.printStackTrace();
}
}
#Override
public void removeNotify() {
super.removeNotify();
getMyDropTarget().removeDropTargetListener(getDropTargetHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dragOver) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(0, 255, 0, 64));
g2d.fill(new Rectangle(getWidth(), getHeight()));
if (dragPoint != null && target != null) {
int x = dragPoint.x - 12;
int y = dragPoint.y - 12;
g2d.drawImage(target, x, y, this);
}
g2d.dispose();
}
}
protected void importFiles(final List files) {
Runnable run = new Runnable() {
#Override
public void run() {
message.setText("You dropped " + files.size() + " files");
}
};
SwingUtilities.invokeLater(run);
}
protected class DropTargetHandler implements DropTargetListener {
protected void processDrag(DropTargetDragEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY);
} else {
dtde.rejectDrag();
}
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
repaint();
}
#Override
public void drop(DropTargetDropEvent dtde) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
Transferable transferable = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(dtde.getDropAction());
try {
List transferData = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
if (transferData != null && transferData.size() > 0) {
importFiles(transferData);
dtde.dropComplete(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
}
public class DragUpdate implements Runnable {
private boolean dragOver;
private Point dragPoint;
public DragUpdate(boolean dragOver, Point dragPoint) {
this.dragOver = dragOver;
this.dragPoint = dragPoint;
}
#Override
public void run() {
DropPane.this.dragOver = dragOver;
DropPane.this.dragPoint = dragPoint;
DropPane.this.repaint();
}
}
}
}
You need to experiment with Drag & Drop and see exactly what flavors are available when you try to drag files. If you do this in your custom TransferHandler you'll be pleasantly surprised one Flavor is the DataFlavor.javaFileListFlavor, which indicates that the item can be used simply as a List. Try it and you'll see that it works!
Note on review of your posted code, I don't see any code for your attempt at using a TransferHandler, so it is hard to say what you could be doing wrong here.
Edit 1
You seem to be trying to use a MouseListener for your drag and drop, and I'm not familiar with this usage. Can you show a reference to a tutorial that tells you to do this?
Edit 2
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
private JList list = new JList();
public FileDragDemo() {
list.setDragEnabled(true);
list.setTransferHandler(new FileListTransferHandler(list));
add(new JScrollPane(list));
}
private static void createAndShowGui() {
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame("FileDragDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;
public FileListTransferHandler(JList list) {
this.list = list;
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean canImport(TransferSupport ts) {
return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
public boolean importData(TransferSupport ts) {
try {
#SuppressWarnings("rawtypes")
List data = (List) ts.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
if (data.size() < 1) {
return false;
}
DefaultListModel listModel = new DefaultListModel();
for (Object item : data) {
File file = (File) item;
listModel.addElement(file);
}
list.setModel(listModel);
return true;
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
}
}
I have a problem in embedding a resource (media file) in jar file. what i have done is i have created a java player that will play the media when i select the JButton i have passed a URL in action event and calling the player everything is working fine but the problem here is i have created resoures folder in netbeans workspace where my java files are located ,that is i thought when i make a jar and distribute it to my customers they can also play the video files as all the resources are embedded in jar so when i run the application in Netbeans everything works fine but when i make a jar file it is not playing the media files that too when all the resources i m packing in jar.
Below is my Source Code that contains main
Manish.java
package javamedia;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Manish implements ActionListener {
JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12;
JFrame frame;
JLabel label;
JPanel panel;
ImageIcon img1;
boolean flag = true;
public Manish() {
frame = new JFrame();
panel = new JPanel();
panel.setLayout(null);
frame.setSize(800, 500);
frame.setTitle("Practical Video's");
panel.setBackground(Color.GRAY);
//label settng
label.setBounds(0, 0, 785, 75);
panel.add(label);
btn1.setBounds(500, 100, 100, 25);
panel.add(btn1);
btn1.addActionListener(this);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new Manish();
}
public void actionPerformed(ActionEvent evt) {
Client2 cl;
if (evt.getSource() == btn1) {
cl = new Client2();
URL mediaURL = this.getClass().getResource("resources/z.mpg");
String file = mediaURL.toString();
cl.show();
cl.VedioAudioPlayer(file);
}
}
}
Client2.java(Player Code)
package javamedia;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.media.*;
import javax.swing.*;
import java.awt.*;
public class Client2 extends javax.swing.JFrame implements
ControllerListener, Runnable {
String filepath;
Player player;
Component visualComponent;
Component controlComponent;
Component progressBar;
boolean firstTime;
long CachingSize;
int controlPanelHeight;
int videoWidth;
int videoHeight;
/**
* Creates new form Client2
*/
public Client2() {
initComponents();
// setBounds(50,50,880,600);
setBounds(0, 0, 400, 325);
}
public void run() {
while (true) {
}
}
private void initComponents() {//GEN-BEGIN:initComponents
jPanel1 = new javax.swing.JPanel();
getFile = new javax.swing.JButton();
panel = new java.awt.Panel();
getContentPane().setLayout(null);
setTitle("Falcon Video Player");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(null);
jPanel1.setBackground(new java.awt.Color(51, 51, 51));
getFile.setBackground(new java.awt.Color(204, 255, 204));
getFile.setForeground(new java.awt.Color(51, 51, 255));
getFile.setText("PlayFile");
getFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
getFileActionPerformed(evt);
}
});
getFile.setBounds(260, 130, 72, 26);
panel.setLayout(null);
panel.setName("panel");
jPanel1.add(panel);
panel.setBounds(15, 15, 700, 650);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 880, 580);
pack();
}
private void FilesActionPerformed(java.awt.event.ActionEvent evt) {
}
private void peersActionPerformed(java.awt.event.ActionEvent evt) {
}
private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void getFileActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* Exit the Application
*/
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
player.stop();
new Manish().frame.setVisible(false);
}
public void VedioAudioPlayer(String file) {
System.out.println("The Asking File is ready to Play");
player = null;
visualComponent = null;
controlComponent = null;
progressBar = null;
firstTime = true;
CachingSize = 0L;
controlPanelHeight = 0;
videoWidth = 0;
videoHeight = 0;
filepath = file;
init(filepath);
}
public void init(String filepath) {
MediaLocator medialocator = null;
Object obj = null;
if (filepath == null) {
Fatal("Invalid media file parameter");
}
try {
if ((medialocator = new MediaLocator(filepath)) == null) {
Fatal("Can't build URL for " + filepath);
}
try {
player = Manager.createPlayer(medialocator);
player.start();
player.addControllerListener(this);
player.realize();
} catch (NoPlayerException noplayerexception) {
System.out.println(noplayerexception);
Fatal("Could not create player for " + medialocator);
}
} catch (MalformedURLException _ex) {
Fatal("Invalid media file URL!");
} catch (IOException _ex) {
Fatal("IO exception creating player for " + medialocator);
}
}
public synchronized void controllerUpdate(ControllerEvent controllerevent) {
if (player == null) {
return;
}
if (controllerevent instanceof RealizeCompleteEvent) {
if (progressBar != null) {
panel.remove(progressBar);
progressBar = null;
}
int i = 320;
int j = 0;
if (controlComponent == null && (controlComponent = player.getControlPanelComponent())
!= null) {
controlPanelHeight = controlComponent.getPreferredSize().height;
panel.add(controlComponent);
j += controlPanelHeight;
}
if (visualComponent == null && (visualComponent = player.getVisualComponent()) != null) {
panel.add(visualComponent);
Dimension dimension = visualComponent.getPreferredSize();
videoWidth = dimension.width;
videoHeight = dimension.height;
i = videoWidth;
j += videoHeight;
visualComponent.setBounds(0, 0, videoWidth, videoHeight);
}
if (controlComponent != null) {
controlComponent.setBounds(0, videoHeight, i, controlPanelHeight);
controlComponent.invalidate();
}
} else if (controllerevent instanceof CachingControlEvent) {
if (player.getState() > 200) {
return;
}
CachingControlEvent cachingcontrolevent = (CachingControlEvent) controllerevent;
CachingControl cachingcontrol = cachingcontrolevent.getCachingControl();
if (progressBar == null && (progressBar = cachingcontrol.getControlComponent()) != null) {
panel.add(progressBar);
panel.setSize(progressBar.getPreferredSize());
validate();
}
} else if (controllerevent instanceof EndOfMediaEvent) {
player.setMediaTime(new Time(0L));
player.stop();
} else if (controllerevent instanceof ControllerErrorEvent) {
player = null;
Fatal(((ControllerErrorEvent) controllerevent).getMessage());
} else if (controllerevent instanceof ControllerClosedEvent) {
panel.removeAll();
}
}
void Fatal(String s) {
System.err.println("FATAL ERROR: " + s);
throw new Error(s);
}
public void destroy() {
if (player != null) {
player.close();
}
}
public void start() {
if (player != null) {
player.start();
}
}
public void stop() {
if (player != null) {
player.stop();
player.deallocate();
}
}
private javax.swing.JButton getFile;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
public java.awt.Panel panel;
// End of variables declaration//GEN-END:variables
}
Fisrt make sure you have indeed your resources packaged correctly in the jar file.
Then have in mind that when reading files from within a jar things may be slightly different. I think the problem is in the following lines.
URL mediaURL = this.getClass().getResource("resources/z.mpg");
String file = mediaURL.toString();
The mediaURL.toString() may not be a proper solution. Perhaps you should consider getting an InputStream to the file like:
URL mediaURL = getClass().getResource("/resources/z.mpg");
InputStream file = mediaURL.openStream();
Then try to use the InputStream insted of a String to refer to the resource you want