Issue with the order in which my code runs - java

I have posted two screenshots below of my GUI. The content of screenshot #1 opens before that of two (in other words, the user is given the ability to select a document before they are brought to the "main page" (with the buttons like mean gdp, and mean pop). How can I edit my code so that the user is shown the main page and they are only given the ability to select a document after they have clicked the button "select csv file"? I know that this has to do with nested code but I would like to have another eye look through what I've done.
Thanks
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class Frame1 {
private JFrame frame;
private JTextField txtCountryChosen;
/**
* Launch the application.
*/
public static void main(String[] args) {
File file;
Scanner fileIn;
int response;
JFileChooser chooser=new JFileChooser("");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
response= chooser.showOpenDialog(null);
if(response== JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
fileIn= new Scanner(file);
if(file.isFile()) {
while(fileIn.hasNextLine()) {
String line=fileIn.nextLine();
System.out.println(line);
}
}
else {
System.out.println("That wasn't a file!");
}
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(result==JFileChooser.APPROVE_OPTION) {
File file=jFileChooser.getSelectedFile();
try {
FileOutputStream fileoutputStream=
new FileOutputStream(file);
//fileoutputStream.flush();
//fileoutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
csv_select.setBounds(130, 62, 150, 25);
frame.getContentPane().add(csv_select);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(12, 100, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_4.setBounds(270, 99, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
JLabel lblNewLabel = new JLabel("Statistics Manager");
lblNewLabel.setBounds(158, 13, 157, 36);
frame.getContentPane().add(lblNewLabel);
}
}```

Related

Project works in IDE, but gives error after exported to Runnable JAR (The system cannot find the path specified)

I have been attempting to create a SoundBoard in JavaScript using Eclipse, and I was actually doing pretty well at first. After setting up the GUI and getting files linked up, the sounds actually played.
Unfortunately, my luck didn't last. I exported my project as a Runnable Jar File and I selected the "Extract required libraries into generated JAR" option. I exported the JAR to my desktop, ran it, but I kept getting an error which says:
src\main\SoundBoardTest\Sounds\Ping.wav (The system cannot find the path specified)
I have two classes inside the project, SoundBoardFrame (For the GUI and actionPerformed button action listeners, and PlaySound, where I keep all my methods to run specific sounds, based on the button you press.
Here is the code for my SoundBoardFrame class:
package main.SoundBoardTest;
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.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.TargetDataLine;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.Color;
import javax.sound.sampled.*;
public class SoundBoardFrame extends JFrame {
private JPanel contentPane;
static JTextField txtField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SoundBoardFrame frame = new SoundBoardFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SoundBoardFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSoundboard = new JLabel("----- SOUNDBOARD -----");
lblSoundboard.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 45));
lblSoundboard.setHorizontalAlignment(SwingConstants.CENTER);
lblSoundboard.setBounds(0, 0, 774, 72);
contentPane.add(lblSoundboard);
JButton btnSound = new JButton("Sound 1");
btnSound.setFocusPainted(false);
btnSound.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtField.setText("Played Sound: 1");
PlaySound.play();
}
});
btnSound.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound.setBounds(10, 93, 220, 80);
contentPane.add(btnSound);
JButton btnSound1 = new JButton("Air Horn");
btnSound1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtField.setText("Played Sound: Air Horn");
PlaySound.play2();
}
});
btnSound1.setFocusPainted(false);
btnSound1.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound1.setBounds(10, 183, 220, 80);
contentPane.add(btnSound1);
JButton btnSound2 = new JButton("Ping");
btnSound2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtField.setText("Played Sound: Ping");
PlaySound.play3();
}
});
btnSound2.setFocusPainted(false);
btnSound2.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound2.setBounds(10, 272, 220, 80);
contentPane.add(btnSound2);
JButton btnSound3 = new JButton("Sound 4");
btnSound3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent argo0) {
txtField.setText("Played Sound: 4");
PlaySound.play();
}
});
btnSound3.setFocusPainted(false);
btnSound3.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound3.setBounds(543, 93, 220, 80);
contentPane.add(btnSound3);
JButton btnSound4 = new JButton("Sound 5");
btnSound4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtField.setText("Played Sound: 5");
PlaySound.play();
}
});
btnSound4.setFocusPainted(false);
btnSound4.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound4.setBounds(543, 183, 220, 80);
contentPane.add(btnSound4);
JButton btnSound5 = new JButton("Sound 6");
btnSound5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtField.setText("Played Sound: 6");
PlaySound.play();
}
});
btnSound5.setFocusPainted(false);
btnSound5.setFont(new Font("Tw Cen MT", Font.PLAIN, 50));
btnSound5.setBounds(543, 272, 220, 80);
contentPane.add(btnSound5);
txtField = new JTextField();
txtField.setBorder(null);
txtField.setToolTipText("This text box displays a message if there is an error.");
txtField.setBackground(Color.WHITE);
txtField.setFont(new Font("Agency FB", Font.PLAIN, 30));
txtField.setText("Test");
txtField.setEditable(false);
txtField.setHorizontalAlignment(SwingConstants.CENTER);
txtField.setBounds(251, 93, 271, 259);
contentPane.add(txtField);
txtField.setColumns(10);
}
}
Also, ignore the code for buttons past "Ping", and any random path changes beyond the first couple of methods in the PlaySound class.
Here is the code for the PlaySound Class:
package main.SoundBoardTest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.annotation.Resource;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.TargetDataLine;
public class PlaySound {
public static void play() {
try {
AudioInputStream in = AudioSystem.getAudioInputStream(new File("src/main/SoundBoardTest/Sounds/Ping.wav"));
BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
AudioInputStream in2 = new AudioInputStream(bufferedInputStream, in.getFormat(), in.getFrameLength());
Clip clip = AudioSystem.getClip();
clip.open(in);
clip.start();
} catch (Exception e) {
SoundBoardFrame.txtField.setText(e.getMessage());
System.err.println(e.getMessage());
}
}
public static void play2() {
try {
File file = new File("src/main/SoundBoardTest/Sounds/Air Horn.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
SoundBoardFrame.txtField.setText(e.getMessage());
}
}
public static void play3() {
try {
File file = new File("src/main/SoundBoardTest/Sounds/Ping.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
SoundBoardFrame.txtField.setText("Error finding sound.");
}
}
public static void play4() {
try {
File file = new File("Sounds/Ping.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
SoundBoardFrame.txtField.setText("Error finding sound.");
}
}
}
That is all the code/classes I have. The hierarchy for my project is as follows:
Hierarchy for my project in Eclipse: "SoundBoardTest"
What could I do or try?

Syntax Error insert "}" to complete class block

I am making a program for my friend. I ran into an error while trying to create a write and save text into a .txt file. I should note this is the first time I have ever created something in Java Swing.
The error is marked with an asterisk.
package com.laganstoop.me;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
// Created by: Laganstoop (David L. Perez)
// Do Not Distribute!
public class Main implements ActionListener {
private JFrame frame;
public static String infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
return "";
}
public static void errorMessage(String errorMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, errorMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static final int HEIGHT = 800;
public static final int WIDTH = 600;
public static final int nHEIGHT = 400;
public static final int nWIDTH = 300;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(HEIGHT, WIDTH);
JButton btnNewButton = new JButton("Click To Add New");
btnNewButton.setBounds(10, 11, 132, 23);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnNewButton);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 764, 181);
panel.setBackground(Color.WHITE);
panel.setForeground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.hide();
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblName.setBounds(10, 11, 46, 14);
panel.add(lblName);
JLabel lblDate = new JLabel("Date:");
lblDate.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblDate.setBounds(10, 36, 46, 14);
panel.add(lblDate);
JLabel lblLocation = new JLabel("Time:\r\n");
lblLocation.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation.setBounds(10, 61, 60, 14);
panel.add(lblLocation);
JLabel lblLocation_1 = new JLabel("Location:");
lblLocation_1.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation_1.setBounds(10, 86, 60, 14);
panel.add(lblLocation_1);
JLabel lblRe = new JLabel("Referee");
lblRe.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblRe.setBounds(10, 111, 60, 14);
panel.add(lblRe);
textField = new JTextField();
textField.setBounds(76, 8, 127, 20);
panel.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(76, 33, 127, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(76, 58, 127, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(76, 86, 127, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(76, 108, 127, 20);
panel.add(textField_4);
JCheckBox checkBox = new JCheckBox("");
checkBox.setBounds(209, 7, 21, 23);
panel.add(checkBox);
JCheckBox checkBox_1 = new JCheckBox("");
checkBox_1.setBounds(209, 32, 21, 23);
panel.add(checkBox_1);
JCheckBox checkBox_2 = new JCheckBox("");
checkBox_2.setBounds(209, 57, 21, 23);
panel.add(checkBox_2);
JCheckBox checkBox_3 = new JCheckBox("");
checkBox_3.setBounds(209, 82, 21, 23);
panel.add(checkBox_3);
JCheckBox checkBox_4 = new JCheckBox("");
checkBox_4.setBounds(209, 107, 21, 23);
panel.add(checkBox_4);
JPanel panel_2 = new JPanel();
panel_2.setBounds(20, 290, 358, 210);
panel_2.setLayout(null);
JButton btnNewNote = new JButton("New Note");
btnNewNote.setFont(new Font("Yu Gothic", Font.BOLD, 16));
btnNewNote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame noteFrame = new JFrame();
noteFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noteFrame.setLocationRelativeTo(panel);
noteFrame.pack();
noteFrame.setSize(nHEIGHT, nWIDTH);
noteFrame.getContentPane().add(panel_2);
noteFrame.setVisible(true);
}
});
btnNewNote.setBounds(293, 16, 461, 151);
panel.add(btnNewNote);
JLabel lblNotes = new JLabel("Notes:");
lblNotes.setBounds(10, 0, 46, 23);
panel_2.add(lblNotes);
lblNotes.setFont(new Font("Yu Gothic", Font.BOLD, 13));
JButton btnSaveCreate = new JButton("Create & Save");
btnSaveCreate.setBounds(237, 177, 131, 23);
panel_2.add(btnSaveCreate);
JCheckBox checkBox_5 = new JCheckBox("");
checkBox_5.setBounds(210, 177, 21, 23);
panel_2.add(checkBox_5);
btnSaveCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String NAME = textField.getText();
String DATE = textField_1.getText();
String TIME = textField_2.getText();
String LOCATION = textField_3.getText();
String Referee = textField_4.getText();
if(checkBox.isSelected() && checkBox_1.isSelected() && checkBox_2.isSelected() && checkBox_2.isSelected() && checkBox_3.isSelected() && checkBox_4.isSelected() && checkBox_5.isSelected())
{
infoBox("Met with " + NAME + " on " + DATE + " #" + TIME + ", and went to " + LOCATION + ", then I was introduced by " + Referee, "Paragraph");
}
else {
errorMessage("Error: Please validate entries!", "Error!");
}
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton.hide();
panel.setVisible(true);
}
});
try {
String content = textField_5.getText();
File file = new File("/users/David/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); //step2: write it
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace(); **** *****
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Any Help is greatly appreciated!
You just forgot to add the } in this statement:
catch (IOException e) {
e.printStackTrace();
}
Just as Andrew Thompson said: simple indentation would have made this error a lot easier to spot if done properly, and should be used as common practice.

Not getting whole string when string has space in java

I'm still new to java, so dumb question is coming. I've been working on a simple software using JFrame, PrintWriter, File, and Scanner to create and read a text file, I save the file with the name you typed and then with the data you input into a JTextField, the problem is: As soon as you type one space it doesn't save the text after the space to the .txt file:
Input
waitFor it
WriteToFile(textarea.getText(), name.getText());
// my function input text name
Output:
waitFor
But if I input the text manually this way:
WriteToFile("waitFor it", name.getText());
// my function input text name
Output:
waitFor it
Which leads me to think that my function might not be causing this, but again I'm a noob.
Main.java
package creator;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import library.Database;
public class Main extends Database{
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Erase");
JButton button2 = new JButton("Add");
JButton button3 = new JButton("Save to Database");
Font font = new Font("Courier", Font.BOLD, 12);
Font font2 = new Font("Courier", Font.BOLD, 14);
final JTextField name = new JTextField();
final JTextField editorPane = new JTextField();
final JTextField textarea = new JTextField();
final JScrollPane scroll = new JScrollPane (textarea,
JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setTitle("Array Creator");
frame.setSize(401, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
frame.add(button);
frame.add(name);
frame.add(button2);
frame.add(button3);
frame.add(editorPane);
frame.add(scroll);
button.setBounds(0, 200, 80, 22);
name.setBounds(82, 200, 80, 22);
button2.setBounds(164, 200, 80, 22);
button3.setBounds(246, 200, 148, 22);
editorPane.setBounds(100,175,200,18);
scroll.setBounds(50, 10, 300, 160);
textarea.setEditable(false);
button.setFont(font);
name.setFont(font);
button2.setFont(font);
button3.setFont(font);
editorPane.setFont(font);
textarea.setFont(font2);
textarea.setText("[");
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText("[");
editorPane.setText("");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText(textarea.getText()+"["+editorPane.getText()+"],");
editorPane.setText("");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String temp = textarea.getText();
temp = temp.substring(0, temp.length()-1);
textarea.setText(temp+"]");
editorPane.setText("");
WriteToFile(textarea.getText(), name.getText());
}
});
name.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
textarea.setText(readFile(name.getText()));
}
public void keyPressed(KeyEvent arg0) {
}
});
}
}
Database.java
package library;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class Database {
public static String WriteToFile(String data, String name){
String output = "ERROR";
PrintWriter writer = null;
try {
writer = new PrintWriter(name+".txt", "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(data);
writer.close();
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return output;
}
public static String readFile(String name){
String output = "[";
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
}
return output;
}
}
May someone provide me an explanation on why this is?
Instead
output = sc.next();
use
output = sc.nextLine();
Reference: Scanner#next() vs Scanner#nextLine()

Reload a web page in a java application

I create a java application and now I have to reload a web page. I open the web page with this code:
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 java.awt.Font;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JProgressBar;
import java.io.*;
import java.util.*;
public class views extends JFrame {
private JPanel contentPane;
private JTextField txtHttpswwwyoutubecom;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
views frame = new views();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public views() {
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 707, 485);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPutTheUrl = new JLabel("Put the url of the video");
lblPutTheUrl.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPutTheUrl.setBounds(40, 93, 159, 24);
contentPane.add(lblPutTheUrl);
JLabel lblSelectTheNumber = new JLabel("Select the number");
lblSelectTheNumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectTheNumber.setBounds(40, 200, 203, 24);
contentPane.add(lblSelectTheNumber);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"5", "10", "15", "20"}));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 15));
comboBox.setBounds(322, 202, 121, 20);
contentPane.add(comboBox);
txtHttpswwwyoutubecom = new JTextField();
txtHttpswwwyoutubecom.setText("https://www.google.com/");
txtHttpswwwyoutubecom.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtHttpswwwyoutubecom.setBounds(322, 93, 332, 24);
contentPane.add(txtHttpswwwyoutubecom);
txtHttpswwwyoutubecom.setColumns(10);
JLabel lblPressOk = new JLabel("Press Ok ");
lblPressOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPressOk.setBounds(40, 298, 71, 24);
contentPane.add(lblPressOk);
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
private String views;
private int intViews;
public void actionPerformed(ActionEvent arg0) {
//trasformare il numero delle views in una stringa
views = comboBox.getSelectedItem().toString();
//trasformo stringa in int
intViews = Integer.parseInt(views);
System.out.println(intViews);
//campo url
String urls = txtHttpswwwyoutubecom.getText();
//apertura url
int cont=0;
int cont1=0;
//cont=intViews;
//System.out.println("cont");
//System.out.println(intViews);
/*
try {
Thread.sleep(millisecondi);
}
catch (Exception e) {}
*/
while(intViews>cont){
cont++;
cont1++;
String URL = urls;
//String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.exit(0);
}
if(cont1==5){
cont1=0;
try {
Thread.sleep(5500);
}
catch (Exception e1) {}
}
}
}
});
btnOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnOk.setBounds(322, 299, 121, 23);
contentPane.add(btnOk);
JLabel lblDevelopedByRiccardo = new JLabel("Developed by Riccardo Vecchiato");
lblDevelopedByRiccardo.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDevelopedByRiccardo.setBounds(464, 421, 237, 24);
contentPane.add(lblDevelopedByRiccardo);
JLabel lblAlpha = new JLabel("Alpha 1.0");
lblAlpha.setBounds(10, 428, 46, 14);
contentPane.add(lblAlpha);
}
}
Every 5 seconds I open five new web page. I open that web page using this code:
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There is a command that reload all the web page that I create with this code?
Do not use Thread.sleep() as it will freeze your Swing application.
Instead you should use a javax.swing.Timer.
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.

Way to save jList data into a txt file?

I am looking for a way to save the users input from a jlist into a txt file. It's for a homework project. I have the program set up to take user input from a textfield, then it goes into the jlist once they hit the add button. The jlist has a defaultlistmodel on it, and I'm wondering if there is a way to create a save button and allow it to save the complete jlist into a .txt file.
Also, here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
public class i extends JFrame {
private JPanel contentPane;
private JTextField jTextField;
DefaultListModel ListModel = new DefaultListModel();
ArrayList<String> arr = new ArrayList <String>();
String str;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i frame = new i();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public i() {
super("List");
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);
jTextField = new JTextField();
jTextField.setBounds(15, 80, 168, 20);
contentPane.add(jTextField);
jTextField.setColumns(10);
final JList jList = new JList(ListModel);
jList.setBorder(new LineBorder(new Color(0, 0, 0)));
jList.setBounds(289, 54, 135, 197);
contentPane.add(jList);
JButton jButton = new JButton("Add");
jButton.setBounds(190, 79, 89, 23);
contentPane.add(jButton);
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String str=jTextField.getText();
ListModel.addElement(str);
jTextField.setText("");
arr.add(str);
System.out.println(arr);
}
});
JButton delete = new JButton("DELETE");
delete.setBounds(190, 162, 89, 23);
contentPane.add(delete);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent k){
ListModel.removeElement(jList.getSelectedValue());
}
});
JButton btnUp = new JButton("UP");
btnUp.setBounds(190, 125, 89, 23);
contentPane.add(btnUp);
btnUp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = jList.getSelectedIndex();
if(index == -1){
JOptionPane.showMessageDialog(null, "Select something to move.");
} else if(index > 0) {
String temp = (String)ListModel.remove(index);
ListModel.add(index - 1, temp);
jList.setSelectedIndex(index -1);
}
}
});
JButton btnDown = new JButton("DOWN");
btnDown.setBounds(190, 196, 89, 23);
contentPane.add(btnDown);
btnDown.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
int index = jList.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog(null, "Select something to move.");
else if( index < ListModel.size() - 1 ){
String temp = (String)ListModel.remove( index );
ListModel.add( index + 1, temp );
jList.setSelectedIndex( index + 1 );
}
}
});
JLabel lblItems = new JLabel("Items:");
lblItems.setBounds(290, 37, 46, 14);
contentPane.add(lblItems);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(190, 228, 89, 23);
contentPane.add(btnPrint);
btnPrint.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
you need use File class to save your list in that
File file = new File("c:/test/myfile.txt");
now file's created and opened!
and for write some output to file
use Formatter Class:
public class CreateFile
{
private Formatter x;
void openFile()
{
try
{
x = new Formatter("c:/myfile.txt");
System.out.println("you created a file");
}
catch(Exception e)
{
System.err.println("error in opening file");
}
}
void addFile()
{
x.format("%s %s %s\n","20","Start","Today");
}
void closeFile()
{
x.close();
}
}
as you see,addFile method accept 3 String passed to write in the file
i passed "20" , "Start" , "Today"
you can use more/less than %s , and pass user input or a list in String to write in the file.
good luck

Categories

Resources