How to get a specific data from a look up website - java

I'm totally new to this section of networking with java.
What I'm trying to do is that, I want the user to add machine type and serial and when he press a button, this will extract the machine expiration date, model and country from a website and then put this data in a txt file automatically.
I'd like as well that the browser to be hidden but don't know how to do it.
I will really appreciate your help.
As well I would prefer to use JTextArea with a vertically only scroll pane to allow the user adding more than one machine (let's say 50 machines) at once , but as well, I don't know how to make the program read the type and serial from this JTextArea separatly
Here is my current code
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URI;
public class PEW_Frame extends JFrame {
private JPanel contentPane;
private JTextField type;
private JTextField serial;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PEW_Frame frame = new PEW_Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PEW_Frame() {
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);
type = new JTextField();
type.setBounds(121, 27, 86, 20);
contentPane.add(type);
type.setColumns(10);
serial = new JTextField();
serial.setBounds(121, 72, 86, 20);
contentPane.add(serial);
serial.setColumns(10);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(34, 30, 46, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(34, 75, 46, 14);
contentPane.add(lblNewLabel_1);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Desktop d = Desktop.getDesktop();
String getType = type.getText();
String getSerial = serial.getText();
//String getType1 = type1.getText();
//String getSerial1 = serial1.getText();
String url = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType+"&serial="+getSerial;
//String url1 = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType1+"&serial="+getSerial1;
try {
if (getType.isEmpty() || getSerial.isEmpty()) {
throw new Exception();
}
d.browse(new URI(url));
//d.browse(new URI(url1));
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,"You must select SLA and period","Error !", JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(176, 189, 89, 23);
contentPane.add(btnNewButton);
//type1 = new JTextField();
//type1.setBounds(229, 27, 86, 20);
//contentPane.add(type1);
//type1.setColumns(10);
//serial1 = new JTextField();
//serial1.setBounds(229, 72, 86, 20);
//contentPane.add(serial1);
//serial1.setColumns(10);
}
}

You can get some help from the following example:
https://github.com/dotKom/OnlineGuru/blob/master/onlineguru/src/main/java/no/ntnu/online/onlineguru/plugin/plugins/middag/UpdateMenu.java#L40
public void run() {
StringBuilder sb = new StringBuilder();
// This posts the required fields to the sit.no RESTful menu api.
try {
// Prepare post data
String postData = "diner="+ kantine.toLowerCase() +"&trigger=single";
// Open connection
java.net.URL url = new URL(URLTEXT);
URLConnection conn = url.openConnection();
// Write the post data
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
wr.close();
rd.close();
} catch (IOException e) {
logger.error("Failed to get JSON data from "+URLTEXT, e.getCause());
}
// Get the html content into a clean string
String json = new String(sb);
json = StringEscapeUtils.unescapeJava(json);
String html = json.split(":")[1].replaceAll("^\"|\"}$", "");
// Traverse html with Jsoup
String menu = findMenuItems(html);
setMenu(kantine, menu);
}

Related

How to connect textfield with function of open_button class

Currently, I learn Java guI, swing.
I would like to link the j1('open' button) in Yam class with a Open_Button Class's function.
If I write a file name in "textField" which is a global variable in Yam class, and press the 'open', the "TextArea" has to show an output the opened file's content.
but somehow it doesn't work. I think the open_button class's function is not connected with the "textField" in Yam class.
But I really can't find what's wrong.
(sorry for my poor Engish..;( i'll show you full code. I want to follow Minimal, Complete, and Verifiable rull but I really don't know where is wrong part..)
Yam class )
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File.*;
import java.io.*;
import java.nio.file.*;
public class Yam extends JFrame {
Container contentPane;
JButton j1, j2, j3, j4, j5, j6;
JTextField textField;
JTextField textField_1;
TextArea textArea, textArea_1;
public Yam() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(14, 12, 240, 24);
contentPane.add(textField);
textField.setColumns(20);
j1 = new JButton("Open");
j1.setBounds(294, 11, 105, 27);
j1.addActionListener(new AB());
contentPane.add(j1);
textField_1 = new JTextField();
textField_1.setBounds(14, 48, 240, 24);
contentPane.add(textField_1);
textField_1.setColumns(20);
j2 = new JButton("Save");
j2.setBounds(294, 47, 105, 27);
contentPane.add(j2);
textArea = new TextArea();
textArea.setBounds(10, 105, 405, 190);
contentPane.add(textArea);
j3 = new JButton("Compile");
j3.setBounds(10, 319, 87, 25);
j3.addActionListener(new AB());
contentPane.add(j3);
j4 = new JButton("Save Errors");
j4.setBounds(111, 319, 87, 25);
contentPane.add(j4);
j5 = new JButton("Delete");
j5.setBounds(217, 319, 87, 25);
contentPane.add(j5);
j6 = new JButton("Clear");
j6.setBounds(321, 319, 87, 25);
j6.addActionListener(new AB());
contentPane.add(j6);
textArea_1 = new TextArea();
textArea_1.setBounds(10, 391, 405, 253);
contentPane.add(textArea_1);
setSize(506, 698);
setVisible(true); }
class AB implements ActionListener {
private TextArea args;
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
CmdClass cmd = new CmdClass();
Open_button open = new Open_button();
JFrame f = new JFrame("what");
if(source == j1) {
}
else if(source == j2) {
}
else if(source == j3) {
if(cmd.main(args))
textArea_1.append("Compile Success\n");
}
else if(source == j4) { }
else if(source == j5) { }
else {
textField.setText(" ");
textField_1.setText(" ");
textArea.setText(" ");
textArea_1.setText(" "); }}}
public static void main(String[] args) {
new Yam();
}
public static String getFileName() {
// TODO Auto-generated method stub
return null;}}
Open_button class)
import java.io.*;
import java.nio.file.*;
import java.io.File;
public class Open_button {
Path Path;
public void main(String Str_paths){
Yam y = new Yam();
Str_paths = y.textField.getText();
Path = FileSystems.getDefault().getPath(Str_paths);
File file = Path.toFile();
if(Path.toFile() != null)
y.textArea.append("file exist!");
else {
y.textArea_1.append("file not exist");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(Str_paths));
String line;
while ((line = br.readLine()) != null) {
y.textArea.append(line);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
I think you want for some reason to open and read a file which the filepath is designated on the jtextfield; Simplest way would be:
JButton openButton = new JButton("Open File");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String thePath = textfield.getText();
File theFile = new File(thePath);
...read..write..
}
});
I would declare this directly on the Yam class;
From what I have seen, your code has two issues: first, there are two Yam (y) instances (the one declared in OpenButton class is different than the one located above) and, second, you assume that the file is readable and always located on Filesystem view...I think you should also consider a JFileChooser dialog.
Regards, André

java gui if else does no work with arraylist

My code with java GUI adds to an arraylist from a file.txt I have in a button the code that compares the code introduced in a textfield with the position in the araylist with an if else. But enter what you enter always goes through the else never through the if.
If I add the components manually as in Arraylist ArrayList <String> answer = new ArrayList <String> ();
then if else works.
But it seems that if I compare the text of the textfield with the
ArrayList <String> answer1 = new ArrayList <String> ();, the if does not work does not do well the comparison
The question is that I need to ask the user 266 questions The user must enter the answers, if the answer is not correct, an incorrect reply message should come out
but I can not get the if else to work with an arraylist loaded with a file.text 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.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class question_answer extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnAnswer;
private JLabel lblNewLabelcuestion;
private JLabel LabelTextF;
private JLabel labelArraylistPos;
private JLabel lblNewLabelTF;
private JLabel lblNewLabelAL;
static int count = 0;
private JLabel lblNewLabel_1;
private static JTextArea textArea;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
question_answer frame = new question_answer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public question_answer() {
File archive = null;
FileReader fr = null;
//This works
/*
* ArrayList<String> question = new ArrayList<String>();
* question.add("What is your name?");
* question.add("What is your surname?");
* question.add("What is your age?");
* ArrayList<String> answer = new ArrayList<String>();
* answer.add("Pedro");
* answer.add("Rodriguez");
* answer.add("46");
*/
ArrayList<String> answer1 = new ArrayList<String>();
try {
archive = new File("C:\\answer.txt");
String line;
fr = new FileReader(archive);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
answer1.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 567, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabelcuestion = new JLabel("New label");
lblNewLabelcuestion.setBounds(60, 56, 360, 24);
contentPane.add(lblNewLabelcuestion);
lblNewLabelTF = new JLabel("New label");
lblNewLabelTF.setBounds(60, 292, 56, 16);
contentPane.add(lblNewLabelTF);
LabelTextF = new JLabel("TextField");
LabelTextF.setBounds(60, 263, 56, 16);
contentPane.add(LabelTextF);
lblNewLabelAL = new JLabel("New label");
lblNewLabelAL.setBounds(170, 292, 56, 16);
contentPane.add(lblNewLabelAL);
labelArraylistPos = new JLabel("Arraylist Position");
labelArraylistPos.setBounds(170, 263, 110, 16);
contentPane.add(labelArraylistPos);
textField = new JTextField();
textField.setBounds(340, 139, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
lblNewLabelcuestion.setText(answer1.get(count));
btnAnswer = new JButton("answer");
lblNewLabelAL.setText(answer1.get(count));
btnAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line1;
for (int j = 0; j < answer1.size(); j++) {
line1 = answer1.get(j);
textArea.append(line1);
}
lblNewLabelcuestion.setText(answer1.get(count));
lblNewLabelAL.setText(answer1.get(count));
lblNewLabelTF.setText(textField.getText());
String c = answer1.get(count);
String Tf = textField.getText();
if (Tf.equals(c)) {
lblNewLabel_1.setText("Good");
} else {
lblNewLabel_1.setText("Wrong");
}
count += 1;
}
});
btnAnswer.setBounds(340, 198, 97, 25);
contentPane.add(btnAnswer);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(45, 153, 256, 16);
contentPane.add(lblNewLabel_1);
textArea = new JTextArea();
textArea.setBounds(345, 273, 181, 67);
contentPane.add(textArea);
lblNewLabel = new JLabel("achive.text content");
lblNewLabel.setBounds(340, 244, 116, 16);
contentPane.add(lblNewLabel);
}
}
`
In any text editor, when you press enter, the the editor enters what is called a line break. This character is invisible but it tells the editor where to make a new line. You need to remove these characters from your lines. Good news is you only have to add one line of code to achieve this! Where you have:
while ((line = br.readLine()) != null) {
answer1.add(line);
}
Replace it with:
while ((line = br.readLine()) != null) {
line = line.replace(System.getProperty("line.separator"), “”);
answer1.add(line);
}
The above code will replace any line separator defined by the OS with an empty string, thereby making your compared strings equal.
The solution was String c = answer1.get(count).trim();

Save From buffered reader to JTextArea

I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}
I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}

How to connect Java classes to GUI?

I'm designing a database that can be accessed through a GUI, I have three classes Main, Database and GUI, When I run the main I get an error and the GUI closes followed by a brief error message which I cannot read, not sure where this is going wrong as i believe it can be a number of issues. Thanks for all your help :)
Here is my main class
public class MainApplication {
#SuppressWarnings("unused")
public static void main(String[] args) {
VideoStoreGUI window = new VideoStoreGUI();
}
}
My Database Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JOptionPane;
#SuppressWarnings("unused")
public class DataBase {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
static Scanner in = new Scanner(System.in);
public void close_connection() {
try
{
con.close();
System.out.println("Database Connections Succesully Closed.");
}
catch (SQLException sqle)
{
System.out.println("Error: failed to close the database");
}
}
public static void addMember(int member_id, String name, String address) // Adding a Member to the Database.
{
try {
String str = "INSERT INTO members (member_id, name, address) values(" + member_id + ", '" + name + "', '"
+ address + "');";
int rows = stmt.executeUpdate(str);
System.out.println("Success in adding member");
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
}
public static void initialize_database() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/videostore";
con = DriverManager.getConnection(url, "root", "admin");
stmt = con.createStatement();
} catch (Exception e) {
System.out.println("Error: Failed to connect to database\n" + e.getMessage());
}
}
public DataBase()
{
initialize_database();
}
}
and my GUI class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
public class VideoStoreGUI extends JFrame {
private JFrame frame;
DataBase my_database;
private JPanel contentPane;
private JTextField textMemberID;
private JTextField textMemberName;
private JTextField textMemberAddress;
/**
* Create the frame.
*/
public VideoStoreGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 400);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 31, 232, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Members", null, panel, null);
panel.setLayout(null);
JLabel labelMemberID = new JLabel("Members ID");
labelMemberID.setBounds(10, 11, 85, 14);
panel.add(labelMemberID);
JLabel labelMemberName = new JLabel("Members Name");
labelMemberName.setBounds(10, 36, 85, 14);
panel.add(labelMemberName);
JLabel labelMemberAddress = new JLabel("Members Address");
labelMemberAddress.setBounds(10, 61, 85, 14);
panel.add(labelMemberAddress);
textMemberID = new JTextField();
textMemberID.setBounds(131, 8, 86, 20);
panel.add(textMemberID);
textMemberID.setColumns(10);
textMemberName = new JTextField();
textMemberName.setColumns(10);
textMemberName.setBounds(131, 33, 86, 20);
panel.add(textMemberName);
textMemberAddress = new JTextField();
textMemberAddress.setColumns(10);
textMemberAddress.setBounds(131, 58, 86, 20);
panel.add(textMemberAddress);
JButton buttonAddMember = new JButton("Add Member");
buttonAddMember.setBounds(10, 86, 102, 23);
panel.add(buttonAddMember);
JButton buttonRemoveMember = new JButton("Add Member");
buttonRemoveMember.setBounds(115, 86, 102, 23);
panel.add(buttonRemoveMember);
JButton buttonSearchMember = new JButton("Add Member");
buttonSearchMember.setBounds(66, 120, 102, 23);
panel.add(buttonSearchMember);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Products", null, panel_1, null);
}
}
I see only one place where you can get popup. You can keep it if you like but add system output and be sure about your message:
catch (SQLException sqle) {
System.out.writeln("Exception:"+sqle);
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
Based on place of this message I think you have wrong sql or database. I would suggest that you print your sql and results of it too.
The main reason this was not working for me was because I had removed setVisable(true) from the GUI and forgot to add it back to the method, I was then receiving an Error "AWT-EventQueue-0" this was to do with the way my database connection was set up, removing and adding the JDBC driver again resolved this.

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.

Categories

Resources