Opening, Editing and Saving text in JTextArea to .txt file - java

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();
}
}

Related

Refresh JTextArea in method

I have the following problem:
in my JTextArea I inserted a default string, which must be updated with the new wording once the file is uploaded.
I have the problem that a live refresh of JTextArea is not done, but if I log out and log in I will see the changed string.
public void createWindow()
{
// some code...
JTextArea textArea = new JTextArea(1,1);
String all = "Nothing Infractions";
try {
all = new Scanner (file).useDelimiter("\\A").next();
textArea =new JTextArea(100,1);
} catch (FileNotFoundException e1) {
textArea =new JTextArea(1,1);
}
JScrollPane scroll = new
JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textArea.setText(all);
frmUser.getContentPane().add(textArea);
Update:
the text area was thought to have been written without infraction, then passed the program going on randomly and assigning it to each user, the problem and that when assigning them all the logged in user does not automatically update that part of text where no infraction was written.
I Use Java 8
Use revalidate() and repaint().
Here is an MCVE (Minimal, Complete and Verifiable example, see https://stackoverflow.com/help/mcve) from which you cut and paste as needed for your question. The example below is not fundamentally different from your question, but it allows other users on StackOverflow to replicate the problem and pass along suggestions or solutions.
In addition to modifying the question, please indicate which version of Java you are running.
Based on what you have said, you will probably need to implement some type of listener to determine when the contents of the file change -- or does it get created and never changed?
190418 1646Z: Added a refresh button per your last comment. Let me know if you would prefer the window to update without having to click a button.
package javaapplication7;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FileWatcher extends JFrame {
static final File WATCH_FILE = new File("c:\\temp\\java7.txt");
static final String DELIMITER = "\n";
private JPanel panel = new JPanel();
private JTextArea textArea = new JTextArea(20, 20);
public FileWatcher() {
JFrame frame = new JFrame();
frame.setSize(600, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setTitle("File Watcher");
frame.add(createPanel());
frame.pack();
}
private JPanel createPanel() {
// some code...
JPanel tempPanel = getPanel();
GridBagConstraints gbc = new GridBagConstraints();
tempPanel.setLayout(new GridBagLayout());
JButton button = new JButton("Refresh");
button.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
getUpdatedText();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
gbc.anchor = GridBagConstraints.NORTH;
getPanel().add(button, gbc);
getTextArea().setFont(new Font("Verdana", Font.BOLD, 16));
getTextArea().setBorder(BorderFactory.createEtchedBorder());
getTextArea().setLineWrap(true);
getTextArea().setWrapStyleWord(true);
getTextArea().setOpaque(true);
getTextArea().setVisible(true);
getUpdatedText();
JScrollPane scroll = new JScrollPane(getTextArea(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBorder(BorderFactory.createLineBorder(Color.blue));
scroll.setVisible(true);
// frmUser.getContentPane().add(textArea);
gbc.gridy = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
tempPanel.add(scroll, gbc);
return tempPanel;
}
public void getUpdatedText() {
String all = new String();
try (Scanner scanner = new Scanner(WATCH_FILE).useDelimiter(DELIMITER)) {
while (scanner.hasNext()) {
all = all.concat(scanner.next()).concat(DELIMITER);
}
} catch (FileNotFoundException ex) {
// swallow, next line covers it
}
if (all.isEmpty()) {
all = "No Infractions";
}
getTextArea().setText(all);
}
public JPanel getPanel() {
return panel;
}
public void setPanel(JPanel panel) {
this.panel = panel;
}
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
public static void main(String[] args) {
FileWatcher javaApplication7 = new FileWatcher();
}
}

Type mismatch: cannot convert from Inventory to JPanel

Line 132 JPanel bookInventory = new Inventory(); of the attached code is reporting the error "Type mismatch: cannot convert from Inventory to JPanel" - any suggestions what's causing this please?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.SystemColor;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import java.awt.GridLayout;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
public class LibSys extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
//private JPanel panelContent;
private static LibSys frame;
private JPanel panelTools;
private JScrollPane scrollPane;
public static int level = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibSys(0);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LibSys(int n) {
level = n;
setTitle("Library Management System");
setIconImage(Toolkit.getDefaultToolkit().getImage(LibSys.class.getResource("/resources/Books-2-icon64.png")));
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 744);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
JSeparator sep = new JSeparator();
JMenuItem logout = new JMenuItem("Logout");
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
login.setVisible(true);
dispose();
}
});
menu.add(exit);
menu.add(sep);
menu.add(logout);
menuBar.add(menu);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.text);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panelTools = new JPanel();
contentPane.add(panelTools, BorderLayout.WEST);
JButton btnToolBookLending = new JButton("Book Lending");
btnToolBookLending.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookLend = new BookLending();
//scrollPane.repaint();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookLend);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
panelTools.setLayout(new GridLayout(8, 1, 0, 20));
btnToolBookLending.setHorizontalAlignment(SwingConstants.LEFT);
btnToolBookLending.setIcon(new ImageIcon(LibSys.class.getResource("/resources/book-48.png")));
panelTools.add(btnToolBookLending);
//panelContent = new JPanel();
//contentPane.add(panelContent, BorderLayout.CENTER);
//panelContent.setLayout(new FlowLayout(BorderLayout.CENTER, 5, 5));
JButton btnToolInventory = new JButton("Inventory");
btnToolInventory.setHorizontalAlignment(SwingConstants.LEFT);
btnToolInventory.setIcon(new ImageIcon(LibSys.class.getResource("/resources/Inventory-icon-32.png")));
btnToolInventory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookInventory = new Inventory();
scrollPane.getViewport().removeAll();
//System.out.println(bookInventory);
scrollPane.setViewportView(bookInventory);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
panelTools.add(btnToolInventory);
//panelTools.add(btnNewButton_1, "2, 2, left, center");
JButton btnBooksReg = new JButton("Book Registration");
btnBooksReg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookReg = new BookRegistration();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookReg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnBooksReg.setHorizontalAlignment(SwingConstants.LEFT);
btnBooksReg.setIcon(new ImageIcon(LibSys.class.getResource("/resources/book-add-icon-32.png")));
panelTools.add(btnBooksReg);
JButton btnToolMemberProfile = new JButton("Member Profile");
btnToolMemberProfile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookMemberProfile = new MemberProfile();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookMemberProfile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolMemberProfile.setIcon(new ImageIcon(LibSys.class.getResource("/resources/App-login-manager-icon32.png")));
btnToolMemberProfile.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolMemberProfile);
JButton btnToolMemberReg = new JButton("Member Registration");
btnToolMemberReg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel MemberReg = new Registration();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(MemberReg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolMemberReg.setIcon(new ImageIcon(LibSys.class.getResource("/resources/user_male_2_add.png")));
btnToolMemberReg.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolMemberReg);
JButton btnToolConfig = new JButton("Configuration");
btnToolConfig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel adminPanel = new AdminPanel();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(adminPanel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolConfig.setIcon(new ImageIcon(LibSys.class.getResource("/resources/settings.png")));
btnToolConfig.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolConfig);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
login.setVisible(true);
dispose();
}
});
btnLogout.setIcon(new ImageIcon(LibSys.class.getResource("/resources/12345678.png")));
btnLogout.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnLogout);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBackground(SystemColor.window);
lblNewLabel.setIcon(new ImageIcon(LibSys.class.getResource("/resources/top-banner.png")));
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
contentPane.add(lblNewLabel, BorderLayout.NORTH);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
scrollPane.setColumnHeaderView(panel);
panel.setLayout(new BorderLayout(0, 0));
JButton btnClose = new JButton("");
btnClose.setPreferredSize(new Dimension(33, 33));
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(scrollPane.getViewport().getComponentCount()>0){
scrollPane.getViewport().remove(scrollPane.getViewport().getComponent(0));
scrollPane.getViewport().repaint();
}
}
});
btnClose.setIcon(new ImageIcon(LibSys.class.getResource("/resources/2015.png")));
panel.add(btnClose, BorderLayout.EAST);
}
}
make sure that Inventory extends JPanel
this makes Inventory to behave as a subclass of a JPanel, and thus you can use it in the same way.

Having Trouble to use jbutton to open a new window

i modified my code but still faced problem ,i want to MyPanel2 inside open to MyPanel by clicking button , how do i do that , here is my code given which is pop open after clicking button of Myplanel..
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.jpedal.PdfDecoder;
import org.jpedal.examples.viewer.Viewer;
import org.jpedal.gui.GUIFactory;
import org.jpedal.utils.LogWriter;
public class Button extends Viewer {
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Button().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
jcomp4 = new JButton("openNewWindow");
// adjust size and set layout
setPreferredSize(new Dimension(315, 85));
setLayout(null);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
a.setupViewer();
}
});
add(jcomp4);
}
}
class MyPanel2 extends Viewer {
public MyPanel2() {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
}
public MyPanel2(int modeOfOperation) {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
commonValues.setModeOfOperation(modeOfOperation);
}
}
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
// we need to increase the size of the panel so when we switch views we can see the viewer
frame.setPreferredSize(new Dimension(2000, 700));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
Now in the button event handler
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
// inform the viewer of where it is to be displayed
a.setRootContainer(contentPane);
// hide the curently visible panel
MyPanel.this.setVisible(false);
// show the viewer
a.setupViewer();
}
});

Impossible to play several sounds when I pressed several Jbuttons

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();
}
}
}

Loading a textfile into a JtextArea

I've been trying for hours to trying to load the contents of a text file into a JTextArea. I'm able to load the text into the console but not into the JTextArea I don't know what I'm doing wrong. Any help is appreciated thanks!
The class for the program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class LoadClass extends JPanel
{
JPanel cards;
private JPanel card1;
private JTextArea textarea1;
private int currentCard = 1;
private JFileChooser fc;
public LoadClass()
{
Font mono = new Font("Monospaced", Font.PLAIN, 12);
textarea1 = new JTextArea();
textarea1.setFont(mono);
card1 = new JPanel();
card1.add(textarea1);
cards = new JPanel(new CardLayout());
cards.add(card1, "1");
add(cards, BorderLayout.CENTER);
setBorder(BorderFactory.createTitledBorder("Animation here"));
setFont(mono);
}
public void Open()
{
textarea1 = new JTextArea();
JFileChooser chooser = new JFileChooser();
int actionDialog = chooser.showOpenDialog(this);
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File( chooser.getSelectedFile( ) + "" );
if(fileName == null)
return;
if(fileName.exists())
{
actionDialog = JOptionPane.showConfirmDialog(this,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION)
return;
}
try
{
String strLine;
File f = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(f));
while((strLine = br.readLine()) != null)
{
textarea1.append(strLine + "\n");
System.out.println(strLine);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
}
The Main Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LoadMain extends JFrame
{
private LoadClass canvas;
private JPanel buttonPanel;
private JButton btnOne;
public LoadMain()
{
super("Ascii Art Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
canvas = new LoadClass();
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
add(canvas, BorderLayout.CENTER);
pack();
setSize(800, 800);
setVisible(true);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
btnOne = new JButton("Load");
buttonPanel.add(btnOne);
btnOne.addActionListener(new btnOneListener());
}
private class btnOneListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btnOne)
{
canvas.Open();
}
}
}
public static void main(String[] args)
{
new LoadMain();
}
}
public void Open()
{
textarea1 = new JTextArea();
Change that to:
public void Open()
{
//textarea1 = new JTextArea(); // or remove completely
The second field created is confusing things.

Categories