I have three buttons in my java program that can play three different sounds. Look at my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
import java.awt.datatransfer.*;
public class VueEditeurEmail extends JFrame implements ActionListener {
private JPanel container = new JPanel();
private JPanel containerHaut = new JPanel();
private JPanel containerAction = new JPanel();
private JButton boutonEnvoyer = new JButton("Envoi");
private JButton boutonAnnuler = new JButton("Annuler");
private JButton contacts = new JButton("Contacts");
private JButton coller = new JButton("Coller");
private JTextArea textArea = new JTextArea();
private ChampsTexte champs1 = new ChampsTexte("Expéditeur :", "");
private ChampsTexte champs2 = new ChampsTexte("Destinataire :", "");
private ChampsTexte champs3 = new ChampsTexte("Objet :", "");
private JOptionPane jop1 = new JOptionPane();
private JOptionPane jop2 = new JOptionPane();
private JOptionPane jop3 = new JOptionPane();
final Clipboard clipboard = container.getToolkit().getSystemClipboard();
public VueEditeurEmail() {
this.setTitle("Expéditeur de Message");
this.setSize(500, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
containerHaut.setLayout(new BoxLayout(containerHaut, BoxLayout.Y_AXIS));
containerHaut.add(champs1);
containerHaut.add(champs2);
containerHaut.add(contacts);
containerHaut.add(coller);
containerHaut.add(champs3);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPan = new JScrollPane(textArea);
container.setLayout(new BorderLayout());
container.setBackground(Color.white);
container.add(containerHaut, BorderLayout.NORTH);
container.add(scrollPan, BorderLayout.CENTER);
container.add(containerAction, BorderLayout.SOUTH);
containerAction.add(boutonEnvoyer, BorderLayout.EAST);
containerAction.add(boutonAnnuler, BorderLayout.WEST);
contacts.addActionListener(this);
boutonEnvoyer.addActionListener(this);
boutonAnnuler.addActionListener(this);
coller.addActionListener(this);
this.setContentPane(container);
this.setVisible(true);
containerHaut.setBackground(Color.GRAY);
champs1.setBackground(Color.GRAY);
champs2.setBackground(Color.GRAY);
champs3.setBackground(Color.GRAY);
textArea.setBackground(Color.YELLOW);
boutonEnvoyer.setBackground(Color.GRAY);
boutonAnnuler.setBackground(Color.GRAY);
}
public void playSound(String soundName){
try{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}catch(Exception ex){
System.out.println("Erreur lors de la lecture du son");
ex.printStackTrace( );
}
}
public void actionPerformed(ActionEvent E) {
if(E.getSource() == boutonEnvoyer){
playSound("Envoyé.wav");
Email monEmail = new Email(champs1.getTexte(), champs2.getTexte(), champs3.getTexte(), textArea.getText());
monEmail.EnvoiSMTP("admpcsrv1.uha.fr", 25);
ImageIcon img1 = new ImageIcon("Images/succès.png");
jop1.showMessageDialog(null, "L'Email a bien été envoyé", "Envoi réussi", JOptionPane.INFORMATION_MESSAGE, img1);
System.exit(0);
}
else if(E.getSource() == boutonAnnuler){
playSound("Annulé.wav");
ImageIcon img2 = new ImageIcon("Images/annuler.png");
jop2.showMessageDialog(null, "Appuyer sur OK pour confirmer l'annulation", "Annulation", JOptionPane.INFORMATION_MESSAGE, img2);
System.exit(0);
}
else if (E.getSource() == contacts){
playSound("OuvertureContacts.wav");
ImageIcon img3 = new ImageIcon("Images/OuvertureContacts.png");
jop3.showMessageDialog(null, "Ouverture de la liste des contacts, appuyer sur Ok pour fermer ce popup", "Liste des contacts", JOptionPane.INFORMATION_MESSAGE, img3);
File file = new File("Fichiers/InfosContacts.xls");
try{
Desktop.getDesktop().open(file);
}catch(IOException e){
System.out.println("Ouverture du fichier impossible");
}
}
else if (E.getSource() == coller){
Transferable clipData = clipboard.getContents(clipboard);
try{
if(clipData.isDataFlavorSupported(DataFlavor.stringFlavor)){
String s = (String)(clipData.getTransferData(DataFlavor.stringFlavor));
champs2.fieldTexte.replaceSelection(s);
}
}catch(Exception ufe){}
}
}
public static void main(String[] args) {
VueEditeurEmail monEditeur = new VueEditeurEmail();
}
}
When I press the "contacts" button, the sound "OuvertureContacts.wav" is well played. But after, when I press the "boutonEnvoyer" button or the "boutonAnnuler" button, their sounds are not played ... What is the problem , I use the same code for the three buttons but when I press one button, the other doesn't play sounds after the first press !
I really appreciate your help, thanks in advance !
Your fragment raises several issues:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
Give each distinct sound its own stream and clip; initialize each clip just once, rather than every time the clip is played.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(…);
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
Although the audio system plays the clip in a separate thread, you may want to position and start() the clip in a separate thread; this will minimize latency on the EDT and enhance liveness.
private void playSound() {
Runnable soundPlayer = new Runnable() {
#Override
public void run() {
try {
clip.setMicrosecondPosition(0);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(soundPlayer).start();
}
See also the javasound tag info and this related example.
Addendum: SSCCE
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* #see https://stackoverflow.com/a/17130160/230513
* #see http://pscode.org/media/
* #see http://www.soundjay.com/beep-sounds-1.html
*/
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.add(new JButton(new SoundAction("Play 1",
"http://pscode.org/media/leftright.wav")));
f.add(new JButton(new SoundAction("Play 2",
"http://www.soundjay.com/button/beep-1.wav")));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
class SoundAction extends AbstractAction {
private Clip clip;
public SoundAction(String name, String location) {
super(name);
try {
URL url = new URL(location);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
#Override
public void actionPerformed(ActionEvent e) {
// Runnable optional
Runnable soundPlayer = new Runnable() {
#Override
public void run() {
try {
clip.setMicrosecondPosition(0);
clip.start();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
};
new Thread(soundPlayer).start();
}
}
}
Related
I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.
I have a program that requires selecting a character, in this case a gender. When the 'female' button is pressed, on the same JFrame,in class Genders, a female ImageIcon is displayed on the label 'Avatar'. The same with male. If it's clicked, a male ImageIcon is displayed on the JFrame. On another JFrame, I have the class StartGame, with my selected gender displaying in the label playerbattle. I don't know how to make it that the selected gender is displayed. Please help, here's my code:
Class Genders:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.prism.Image;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Genders extends JFrame {
public JPanel contentPane;
protected ImageIcon avtMale = new ImageIcon("male warrior.png");
protected ImageIcon avtFemale = new ImageIcon("female warrior.png");
/**
* Launch the application.
*/
public static void main(String[] args) throws IOException{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Genders frame = new Genders();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
/*String[] imageList =
{
"female warrior.jpg", "male warrior.jpg"
};
*/
public Genders() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
ImageIcon maleicon = new ImageIcon("male warrior.png");
JLabel Avatar = new JLabel();
Avatar.setBounds(0, 0, 227, 261);
contentPane.add(Avatar);
ImageIcon femaleicon = new ImageIcon("female warrior.png");
JButton btnFemale = new JButton("Female");
btnFemale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ex) {
//play sound:
try {
// Open an audio input stream.
File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
Avatar.setIcon(avtFemale);
}
});
btnFemale.setBounds(335, 11, 89, 23);
contentPane.add(btnFemale);
JButton btnMale = new JButton("Male");
btnMale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//play sound:
try {
// Open an audio input stream.
File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
}
Avatar.setIcon(avtMale);
}
});
btnMale.setBounds(335, 45, 89, 23);
contentPane.add(btnMale);
JButton btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//play sound:
try {
// Open an audio input stream.
File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
}
{
}
// go to Start Game class:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
dispose();
new StartGame().setVisible(true);
}
});
}
});
//set playericon:
btnOkay.setBounds(335, 227, 89, 23);
contentPane.add(btnOkay);
JButton btngenderback = new JButton("<");
btngenderback.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//play sound:
try {
// Open an audio input stream.
File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
}
//go to ProfileHome class:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
dispose();
new ProfileHome().setVisible(true);
}
});
}
});
btngenderback.setBounds(0, 0, 41, 15);
contentPane.add(btngenderback);
JLabel Genderbg = new JLabel("");
Genderbg.setIcon(new ImageIcon("C:\\Users\\WhiteFringe\\Pictures\\Wallpapers\\9gag\\Gifs\\llkokigiphy.gif"));
Genderbg.setBounds(0, 0, 434, 261);
contentPane.add(Genderbg);
}
}
Class StartGame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.JLabel;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class StartGame extends JFrame {
public JPanel contentPane;
//protected ImageIcon playerMale = new ImageIcon("male warrior.png");
//protected ImageIcon playerFemale = new ImageIcon("female warrior.png");
protected ImageIcon playericon = new ImageIcon();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StartGame frame = new StartGame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public StartGame() {
String[] gametext = new String[100];
String t1, t2;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent Escape) {
}
});
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenuItem mntmPause = new JMenuItem("Pause");
mntmPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//play sound:
try {
// Open an audio input stream.
File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/pausesfx.wav"); //you could also get the sound file with a URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
//go to PauseMenu class:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
setVisible(false);
new PauseMenu().setVisible(true);
}
});
}
});
menuBar.add(mntmPause);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel playerbattle = new JLabel();
playerbattle.setIcon(playericon);
playerbattle.setBounds(0, 0, 194, 250);
contentPane.add(playerbattle);
JButton btnNext = new JButton("Attack");
btnNext.setFont(new Font("Tahoma", Font.PLAIN, 9));
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNext.setBounds(355, 219, 69, 18);
contentPane.add(btnNext);
ImageIcon enemyicon = new ImageIcon("enemy1.png");
JLabel enemybattle = new JLabel(enemyicon);
enemybattle.setBounds(309, 79, 94, 147);
contentPane.add(enemybattle);
JLabel battle1bg = new JLabel("");
battle1bg.setIcon(new ImageIcon("C:\\My Awesome Stuff\\Personal\\Carman\\My Eclipse Programs\\Game\\battle1.jpg"));
battle1bg.setBounds(0, 0, 434, 237);
contentPane.add(battle1bg);
}
}
If something's still unclear, here are screenshots of the JFrames:
Genders:
Image link:
StartGame:
ImageLink: My playerbattle label should show on the left hand side (I've already inserted the label there)
Minimal, Complete, Verifiable e.g.:
Genders:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MDVGenders extends JFrame {
private JPanel contentPane;
//Initialise ImageIcons:
protected ImageIcon avtMale = new ImageIcon("male warrior.png");
protected ImageIcon avtFemale = new ImageIcon("female warrior.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MDVGenders frame = new MDVGenders();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MDVGenders() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Avatar = new JLabel("");
Avatar.setBounds(10, 11, 134, 239);
contentPane.add(Avatar);
JButton btnMale = new JButton("Male");
btnMale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Avatar.setIcon(avtMale);
}
});
btnMale.setBounds(335, 45, 89, 23);
contentPane.add(btnMale);
JButton btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// go to MDVStartGame class:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
dispose();
new MDVStartGame().setVisible(true);
}
});
}
});
btnOkay.setBounds(335, 227, 89, 23);
contentPane.add(btnOkay);
JButton btnFemale = new JButton("Female");
btnFemale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Avatar.setIcon(avtFemale);
}
});
btnFemale.setBounds(335, 11, 89, 23);
contentPane.add(btnFemale);
}
}
StartGame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class MDVStartGame extends JFrame {
private JPanel contentPane;
protected ImageIcon playericon = new ImageIcon();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MDVStartGame frame = new MDVStartGame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MDVStartGame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel playerbattle = new JLabel(playericon);
playerbattle.setBounds(10, 11, 119, 239);
contentPane.add(playerbattle);
}
}
Creating a new Constructor for the StartGame Class
public StartGame(ImageIcon genderImage){
if(genderImage==null){
genderImage= //An Image to use when user select no gender before
//pressing okay button
}
initComponents();
playerBattle.setIcon(genderImage);
}
in your Gender Class
//declare an ImageIcon object inUseGender
ImageIcon inUseGender;
After each of the line
Avatar.setIcon(avtMale);
Avatar.setIcon(avtFemale);
//add this line:
inUseGender = avtMale;
Main Method :
#override
public void run() {
dispose();
new StartGame(inUseGender).setVisible(true);
}
package pkgnew;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class bob
{
JButton test = new JButton("");
JButton test1 = new JButton("");
JButton test2 = new JButton("");
JButton test3 = new JButton("");
JPanel panel = new JPanel();
public void playSound(String soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
public bob() {
JFrame frame = new JFrame("Movie Stars");
test.setIcon(new ImageIcon("C:\\Users\\bob\\Desktop\\Leonardo.jpg"));
test1.setIcon(new ImageIcon("C:\\Users\\bob\\Desktop\\Bruce.jpg"));
test2.setIcon(new ImageIcon("C:\\Users\\bob\\Desktop\\Jim.jpg"));
test3.setIcon(new ImageIcon("C:\\Users\\bob\\Desktop\\Robert.jpg"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.add(panel);
frame.setSize(1000, 800);
frame.setResizable(true);
frame.setVisible(true);
panel.add(test);
panel.add(test1);
panel.add(test2);
panel.add(test3);
panel = new JPanel(new GridLayout(2,2));
test.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("Leonardo.wav");
}
}
);
}
public static void main(String[] args)
{
bob t = new bob();
}
}
So basically I have a grid with 4 buttons of pictures, and I'm trying to make it so when you click each picture a sound plays. I implemented it for one of the buttons however everything I have tried so far to make it work for the other 3 buttons has not been successful. I thought I would just duplicate the test.addActionListener(new ActionListener() { and replace 'test' with 'test1' but that's not it I also tried to add an 'else if catch' to that play loop so that if e.getSource() == test then it would play one of the sounds, else if e.getSource() == test2 it would play another but did not work
As others have said in the comments, your code works just fine.
I downloaded Netbeans just to check it out for you :p
Here is the code working as intended:
Here is the ActionListener code I used (tested with 2 different sounds):
test.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("C:\\Users\\DT\\Music\\Beep.wav");
JOptionPane.showMessageDialog(null, "Beep1 Just Went Off");
}
});
test1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("C:\\Users\\DT\\Music\\Beep2.wav");
JOptionPane.showMessageDialog(null, "Beep2 Just Went Off");
}
});
test2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("C:\\Users\\DT\\Music\\Beep.wav");
JOptionPane.showMessageDialog(null, "Beep3 (Beep.wav) Just Went Off");
}
});
test3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("C:\\Users\\DT\\Music\\Beep.wav");
JOptionPane.showMessageDialog(null, "Beep4 (Beep.wav) Just Went Off");
}
});
I did pretty much the same thing and it also works for me. I also made some improvements in the sound loading.
package helloworld;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Created by matt on 4/4/16.
*/
public class PlaySounds {
Map<String, Clip> sounds = new HashMap<>();
public PlaySounds(){
loadResources("A.wav");
loadResources("B.wav");
}
public void loadResources(String soundName){
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
sounds.put(soundName, clip);
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton a = new JButton("A");
JButton b = new JButton("B");
PlaySounds sounds = new PlaySounds();
a.addActionListener(evt->{
sounds.playSound("A.wav");
});
b.addActionListener(evt->{
sounds.playSound("B.wav");
});
panel.add(a, BorderLayout.WEST);
panel.add(b, BorderLayout.EAST);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void playSound(String soundName){
Clip c = sounds.get(soundName);
c.setFramePosition(0);
c.start();
}
}
Instead of loading the sound again each time it is click, I loaded the sounds when I started the program.
To answer your question in the title. I added two action listeners, one to each button that plays the different sounds.
I am making a Smart ATM application for my college project using Swing which can be used by people with visual disabilities as well.
I have added mouse over listeners to every button so that the program plays a clip which speaks about the operation of that button.
The problem is when user hovers over multiple buttons in a short period of time when a clip about previous button is already getting played, two clips get played simultaneously which is not what I want.
My code so far for the current frame is:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.InputMismatchException;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
public class InitialInput extends JFrame implements ActionListener {
JLabel logo;
JPanel logoPanel = new JPanel();
JPanel askPanel = new JPanel();
JPanel pinPanel = new JPanel();
//For adding span
JPanel emptyPanel = new JPanel();
JTextField accountNumberField = new JTextField(10);
JLabel askAccountNumber = new JLabel("Please enter your account Number : ");
public int userAccountNumber;
JTextField pinField = new JTextField(10);
JLabel askPin = new JLabel("Please enter your Pin : ");
public int userPin;
JPanel submitPanel = new JPanel();
JButton submit = new JButton("SUBMIT");
JButton createAccount = new JButton("CREATE NEW ACCOUNT");
JPanel mainPanel = new JPanel(new GridBagLayout());
Clip clipAccountNumberField,clipPinField,clipWelcome,clipSubmit;
InitialInput() {
//Play welcome Music
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(Welcome.class.getResource("WelcomeMusic.wav"));
clipWelcome = AudioSystem.getClip();
clipWelcome.open(audioIn);
clipWelcome.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play deposit music!");
}
buildGUI();
}
//TODO Work on this
/*
public void stopAllClips() {
//Clip clipAccountNumberField,clipPinField,clipWelcome,clipSubmit;
if(clipWelcome.isActive())
clipWelcome.stop();
if(clipAccountNumberField.isActive())
clipAccountNumberField.stop();
if(clipPinField.isActive())
clipPinField.stop();
if(clipSubmit.isActive())
clipSubmit.stop();
}*/
public void buildGUI() {
//Properties of Frame
setSize(400,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
BufferedImage logoI = ImageIO.read(this.getClass().getResource("logo.png"));
logo = new JLabel(new ImageIcon(logoI));
}
catch(Exception e) {
e.getMessage();
}
//On Hover Action for Deposit Button
accountNumberField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickAndEnterAccountNumber.wav"));
clipAccountNumberField = AudioSystem.getClip();
clipAccountNumberField.open(audioIn);
// stopAllClips();
clipAccountNumberField.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play account number music!");
}
}
});
pinField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickAndEnterPin.wav"));
clipPinField = AudioSystem.getClip();
clipPinField.open(audioIn);
// stopAllClips();
clipPinField.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play pin music!");
}
}
});
submit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickToSubmit.wav"));
clipSubmit = AudioSystem.getClip();
clipSubmit.open(audioIn);
// stopAllClips();
clipSubmit.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play submit music!");
}
}
});
//TODO Add music to create account button
//Adds gap between create account and submit button
FlowLayout flow = new FlowLayout(); // Create a layout manager
flow.setHgap(35);
submitPanel.setLayout(flow);
//Adds symbiosis logo to panel
logoPanel.add(logo);
//Adds action listener to text fields
accountNumberField.addActionListener(this);
pinField.addActionListener(this);
//Adds action listener to Create Account Button
createAccount.addActionListener(this);
//Adds labels to panel
askPanel.add(askAccountNumber);
askPanel.add(accountNumberField);
//Adds textfields to panel
pinPanel.add(askPin);
pinPanel.add(pinField);
//Adds buttons to panels
submitPanel.add(createAccount);
submitPanel.add(submit);
//Specifies constraints for grid layout
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
mainPanel.add(logoPanel,c);
c.gridx=0;
c.gridy=1;
mainPanel.add(askPanel,c);
c.gridx=0;
c.gridy=2;
mainPanel.add(emptyPanel,c);
c.gridx=0;
c.gridy=3;
mainPanel.add(pinPanel,c);
c.gridx=0;
c.gridy=4;
mainPanel.add(emptyPanel,c);
c.gridx=0;
c.gridy=5;
mainPanel.add(submitPanel,c);
add(mainPanel);
setVisible(true);
}
//Action listener
public void actionPerformed(ActionEvent e) {
if(e.getSource()==accountNumberField) {
try {
userAccountNumber = Integer.parseInt(accountNumberField.getText());
int numberOfDigitsInAccountNumber = String.valueOf(userAccountNumber).length();
if(numberOfDigitsInAccountNumber !=6) {
throw new InputMismatchException();
}
if(userAccountNumber <= 0) {
throw new Exception();
}
//TODO if(accountNumber) not present in database
}
catch(InputMismatchException e1) {
accountNumberField.setText("");
JOptionPane.showMessageDialog(accountNumberField,"Please enter a 6 digit account number.");
}
catch(Exception e1) {
accountNumberField.setText("");
JOptionPane.showMessageDialog(accountNumberField,"Invalid input.");
}
}
else if(e.getSource()==pinField) {
try {
userPin = Integer.parseInt(pinField.getText());
int numberOfDigitsInAccountNumber = String.valueOf(userPin).length();
if(numberOfDigitsInAccountNumber !=4) {
throw new InputMismatchException();
}
if(userPin <= 0) {
throw new Exception();
}
//TODO if(accountNumber) not match in database
}
catch(InputMismatchException e1) {
pinField.setText("");
JOptionPane.showMessageDialog(pinField,"Please enter a 4 digit pin.");
}
catch(Exception e1) {
pinField.setText("");
JOptionPane.showMessageDialog(pinField,"Invalid input.");
}
}
else if(e.getSource()==createAccount) {
CreateAccount a = new CreateAccount();
this.setVisible(false);
a.setVisible(true);
}
}
}
Override the mouseExited method for each MouseListener, stopping the Clip in the implementation
#Override
public void mouseExited(MouseEvent e){
theClipIManage.stop();
}
I am messing around with java swing and am trying to open a text file containing existing data with a JTextArea. It doesn't seem to be saving any changes regardless of the different things I have tried.
Below is code that reads the text file fine, but doesn't write it (obviously).
If someone could please advise me as to how I could successfully save changes to the JTextArea I would be greatful.
package funwithswing;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AllDataGUI extends JFrame{
public AllDataGUI(){
fileRead();
panels();
}
private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
private JTextArea textArea = new JTextArea(storeAllString,0,70);
private JButton getCloseButton(){
return closeButton;
}
private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
private void fileWrite(){
try{
FileWriter write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void saveBtn(){
}
}
You need to close FileWriter. Use try-with-resource of Java-7 or finally block to close resource properly.
private void fileWrite(){
FileWriter write=null;
try{
write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
finally{
if(write != null)
write.close();
}
}
There are some mistakes in your code, I have modified those. Compile and run the below code This will solv your problem.
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AllDataGUI extends JFrame{
public AllDataGUI(){
fileRead();
panels();
}
private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
// private JTextArea textArea = new JTextArea(storeAllString,0,70);
private JTextArea textArea = new JTextArea();
private JButton getCloseButton(){
return closeButton;
}
private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
textArea.setText(storeAllString);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
// JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
saveCloseBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveBtn();
frame.dispose();
}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void saveBtn(){
File file = null;
FileWriter out=null;
try {
file = new File("CompleteData.txt");
out = new FileWriter(file);
out.write(textArea.getText());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] arg)
{
new AllDataGUI();
}
}