Setting wallpaper on Windows 7 with Java - java

I have been experimenting with a small program to set the desktop image to the current "Astronomy Picture of the Day". I have been using the JNA suggestion to set the wallpaper from a similar question (). However, my code is not working. I am not sure what's wrong - I have little experience with JNA. Here is the code. Please ignore the completely misleading class names - I started with another project to get me going. The part that is not working is the final setting of the wallpaper - no errors get thrown it just doesn't do anything. The image saves fine.
Edit - I have decided to make a batch file that sets the registry keys and run that. The batch file works sometimes then refuses to work other times. So far it's a partial success! The program is now:
Edit 2- I imported the wallpaper code from Can I change my Windows desktop wallpaper programmatically in Java/Groovy? and once I remembered to close the output file (doh!) it worked fine.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.Iterator;
import javax.imageio.*;
import javax.imageio.stream.*;
public class RSSReader {
private class HTMLParse extends HTMLEditorKit
{
/**
* Call to obtain a HTMLEditorKit.Parser object.
*
* #return A new HTMLEditorKit.Parser object.
*/
public HTMLEditorKit.Parser getParser()
{
return super.getParser();
}
}
private class HREFCallback extends ParserCallback
{
private String base;
public HREFCallback(String base)
{
this.base = base;
}
#Override
public void handleStartTag(Tag t,
MutableAttributeSet a,
int pos)
{
if (t == HTML.Tag.A)
{
String href = (String)(a.getAttribute(HTML.Attribute.HREF));
if (href.endsWith("jpg") && href.startsWith("image"))
{
URL u_img;
try
{
u_img = new URL(base + href);
System.out.println(u_img.toString());
Image img = ImageIO.read(u_img);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
double aspectScreen = dim.getWidth() / dim.getHeight();
double aspectImage = img.getWidth(null) / img.getHeight(null);
System.out.println(Double.toString(aspectScreen)
+ " " + Double.toString(aspectImage));
if (aspectScreen / aspectImage > 1.1 || aspectScreen / aspectImage < 0.9)
{
int x = 0;
int y = 0;
int w = (int)img.getWidth(null);
int h = (int)img.getHeight(null);
if (aspectScreen > aspectImage)
{
// Image needs to be letterboxed
double newHeight = img.getWidth(null) / aspectScreen;
y = (int)((img.getHeight(null) - newHeight) / 2);
h = (int)newHeight;
}
else
{
double newWidth = img.getHeight(null) / aspectScreen;
x = (int)(img.getWidth(null) - newWidth / 2);
w = (int)newWidth;
}
img = Toolkit.getDefaultToolkit().createImage((new FilteredImageSource(img.getSource(),
new CropImageFilter(x,y,w,h))));
}
Image scaled = img.getScaledInstance(dim.width, dim.height, Image.SCALE_DEFAULT);
String l_appdata = System.getenv("APPDATA");
System.out.println(l_appdata);
if (!l_appdata.equals(""))
{
try {
BufferedImage bufImage =
new BufferedImage(scaled.getWidth(null), scaled.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D bufImageGraphics = bufImage.createGraphics();
bufImageGraphics.drawImage(scaled, 0, 0, null);
String dirname = l_appdata + "\\" + "APOD Wallpaper";
(new File(dirname)).mkdir();
String fname = dirname + "\\" + "apod_wallpaper1.jpg";
File outputfile = new File(fname);
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
File file = new File(fname);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(bufImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
String scriptName = dirname + "\\" + "setwallpaper.bat";
File s = new File(scriptName);
BufferedWriter wr = new BufferedWriter(new FileWriter(s));
wr.write(":: Configure Wallpaper");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V Wallpaper /T REG_SZ /F /D \"" + fname + "\"");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V WallpaperStyle /T REG_SZ /F /D 0");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V TileWallpaper /T REG_SZ /F /D 2");
wr.newLine();
wr.write(":: Make the changes effective immediately");
wr.newLine();
wr.write("%SystemRoot%\\System32\\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");
wr.newLine();
wr.close();
String cmd = "cmd /C start /D\"" + dirname + "\" setwallpaper.bat ";
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
try
{
p.waitFor();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private static RSSReader instance = null;
private RSSReader() {
}
public static RSSReader getInstance() {
if(instance == null) {
instance = new RSSReader();
}
return instance;
}
public void writeNews() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String base = "http://apod.nasa.gov/apod/";
URL u = new URL(base + "astropix.html"); // your feed url
BufferedReader in = new BufferedReader(new InputStreamReader(u
.openStream()));
HTMLEditorKit.Parser parse = new HTMLParse().getParser();
parse.parse(in,new HREFCallback(base),true);
}
catch (Exception ex)
{
//do nothing
}
}
public static void main(String[] args) {
RSSReader reader = RSSReader.getInstance();
reader.writeNews();
}
}

You can take a look and see how JAWC does it.
FTS:
Jawc stands for Just Another Wallpaper Changer or, if you prefer, JAva Wallpaper Changer.
It is a Plugin-Based Wallpaper Changer and can change your desktop background picture from a > lot of different sources like your PC's folders, or Flickr, or VladStudio, just depending on > which plugins you enable.
Jawc is written using Java and it has been tested to work on Windows, Linux and Mac Os X systems.

Further to Rodrigo's answer, see these classes in particular: http://jawc-wallpaperc.svn.sourceforge.net/viewvc/jawc-wallpaperc/trunk/Jawc/src/it/jwallpaper/platform/impl/

Related

Variable Not Changing in If Statement with Sarxos Motion Detection

I'm trying to have my program print a few "funny" images whenever it detects motion. Everything works by itself but when I put the if(detection == true) statement into the program, the variable doesn't update. How could I get it to update inside of the motionDetected function?
I've tried using boolean and int for the variable but I think it could be with the way I've structured it.
package printstuff;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.function.Function;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
/**
* Detect motion.
*
* #author Bartosz Firyn (SarXos)
*/
public class DetectMotion implements WebcamMotionListener {
public static boolean detection = false;
public DetectMotion() {
//creates a webcam motion detector
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms
detector.addMotionListener(this);
detector.start();
}
#Override
public void motionDetected(WebcamMotionEvent wme) {
//detects motion and should change the detection variable
System.out.println("Detected motion");
detection = true;
}
public static void main(String[] args) throws IOException, Exception {
new DetectMotion();
System.in.read(); // keep program open
final String[] catImages = new String[4];
//all the images
catImages[0] = "https://i.ytimg.com/vi/3v79CLLhoyE/maxresdefault.jpg";
catImages[1] = "https://i.imgur.com/RFS6RUv.jpg";
catImages[2] = "https://kiwifarms.net/attachments/dozgry5w4ae3cut-jpg.618924/";
catImages[3] = "https://www.foodiecrush.com/wp-content/uploads/2017/10/Instant-Pot-Macaroni-and-Cheese-foodiecrush.com-019.jpg";
//statement does not work..
if(detection == true)
{
for(int i=0; i<4; i++)
{
//saves the picture inside of the array to image.jpg
String imageUrl = catImages[i];
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
//sends print job to printer
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("image.jpg");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
java.util.concurrent.TimeUnit.SECONDS.sleep(15);
}
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
//converts url into image
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}

JAVA How to append a list and TableView trought a while in java?

Iam new into java coding, iam learning and to learn i propose to me create a traceroute program that keep testing the ping response on the route traced.
The first step is get the IP from user and make the traceroute, getting all ip address to be pinged, but iam stuck on this, when i try to add a parsed return of traceroute output to the Jtable, it dont acumullate it, just add the last entry of my while.
Please dont blame my by the bad coding, iam learning.
Iam trying to figure out how to add data to a list and a JTable from a while.
This program get informations from other class, this other class runs a tracert to a ip address and return to Main the tracert results in this format:
13ms;14ms;23ms;192.168.2.3
13ms;14ms;23ms;192.168.2.1
13ms;14ms;23ms;200.122.222.22
this is my table fields: ping1,ping2,ping3,hop
I need to put this data in the table but need to be all ips of the list but iam getting only the last one.
I made alot of tests and commented it because did not workd.
Main.java
package application;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import application.Main.Pinge;
import application.NetworkDiagnostics;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
// Layout
FlowPane noRaiz = new FlowPane();
// Cena
Scene minhaCena = new Scene(noRaiz, 400, 500);
// Nós
TextField ip = new TextField();
// Tables
// List lista = new ArrayList<String>();
// lista.add("1;2;3;4");
// List<Pinge> lista = Arrays.asList();
// List<Pinge> lista = Arrays.asList(
// new Pinge("OK","OK","OK","OK")
// );
TableView<Pinge> tabela = new TableView<>();
TableColumn colunahop = new TableColumn<>("Hop");
TableColumn colunaping1 = new TableColumn<>("Ping1");
TableColumn colunaping2 = new TableColumn<>("Ping2");
TableColumn colunaping3 = new TableColumn<>("Ping3");
colunahop.setCellValueFactory(new PropertyValueFactory<>("hop"));
colunaping1.setCellValueFactory(new PropertyValueFactory<>("ping1"));
colunaping2.setCellValueFactory(new PropertyValueFactory<>("ping2"));
colunaping3.setCellValueFactory(new PropertyValueFactory<>("ping3"));
tabela.getColumns().addAll(colunahop, colunaping1, colunaping2, colunaping3);
Button vai = new Button();
vai.setText("vai");
Label texto = new Label();
texto.setText("");
TextArea resultadow = new TextArea();
// Adicionar elementos na cena
noRaiz.getChildren().add(ip);
noRaiz.getChildren().add(vai);
noRaiz.getChildren().add(texto);
noRaiz.getChildren().add(tabela);
// noRaiz.getChildren().add(resultadow);
vai.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#SuppressWarnings("null")
#Override
public void handle(ActionEvent envent) {
String resultado = new String();
ip.setText("registro.br");
vai.setFocusTraversable(true);
texto.setText("Rastreando: " + ip.getText());
resultadow.setText("Rastreando: " + ip.getText());
resultado = application.NetworkDiagnostics.traceRoute(ip.getText());
// tabela.getItems().add(lista);
String[] result = resultado.split("\n");
String payload = null;
// lista.add(resultado);
int x1 = 0;
// lista.add(lista.lastIndexOf(lista)+1, new Pinge("TESTE","TESTE","TESTE","TESTE"));
List<Pinge> lista = null;
while (x1 < result.length) {
System.out.println(x1 + ": " + result[x1]);
String[] result1 = result[x1].split(";");
// payload = payload + result1[3] + ":" + result1[0] + ":" + result1[1] + ":" + result1[2] + "\n";
lista = Arrays.asList(new Pinge(result1[3],result1[0],result1[1],result1[2]));
// lista.add(new Pinge(result1[3],result1[0],result1[1],result1[2]));
resultadow.appendText(result1[3] + ":" + result1[0] + ":" + result1[1] + ":" + result1[2] + "\n");
//resultadow.setText(result[x1]);
x1++;
}
//List<Pinge> lista = Arrays.asList(new Pinge("TESTE","TESTE","TESTE","TESTE"));
tabela.setItems(FXCollections.observableArrayList(lista));
}
});
primaryStage.setScene(minhaCena);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static class Pinge {
private String hop;
private String ping1;
private String ping2;
private String ping3;
public Pinge(String hop, String ping1, String ping2, String ping3) {
this.hop = hop;
this.ping1 = ping1;
this.ping2 = ping2;
this.ping3 = ping3;
}
public String getHop() {
return hop;
}
public void setHop(String hop) {
this.hop = hop;
}
public String getPing1() {
return ping1;
}
public void setPing1(String ping1) {
this.ping1 = ping1;
}
public String getPing2() {
return ping2;
}
public void setPing2(String ping2) {
this.ping2 = ping2;
}
public String getPing3() {
return ping3;
}
public void setPing3(String ping3) {
this.ping3 = ping3;
}
}
public static void main(String[] args) {
launch(args);
}
}
This is the class where do the tracert command
NetworkDiagnostics.java
package application;
import java.io.BufferedWriter;
import application.Main;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetworkDiagnostics {
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private final String os = System.getProperty("os.name").toLowerCase();
public static String traceRoute(String string) {
String route = "";
String res = "";
int ms = 0;
File arquivo = new File("c:/pedro/tracert.log");
try {
Process traceRt;
traceRt = Runtime.getRuntime().exec("tracert " + string);
// read the output from the command
route = convertStreamToString(traceRt.getInputStream());
route = route.trim().replaceAll(" ", " ").replaceAll(" ", " ").replaceAll(" ms", "ms").replaceAll(" ", ",");
String[] split = route.trim().split("\n");
//regex ip and domain
String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
String DOMAIN_PATTERN = "^(www\\.|)(([a-zA-Z0-9])+\\.){1,4}[a-z]+$";
Pattern patternIP = Pattern.compile(IPADDRESS_PATTERN);
// Pattern patternDo = Pattern.compile(DOMAIN_PATTERN);
int x = 1;
while (x < split.length) {
// debug
System.out.println(split[x]);
int y = 0;
String[] details = split[x].split(",");
while (y < details.length) {
Matcher matcherIP = patternIP.matcher(details[y]);
// Matcher matcherDO = patternDo.matcher(details[y]);
if (details[y].contains("ms"))
{
res = res + details[y] + ";";
}
if (matcherIP.find()) {
res = res + matcherIP.group() + "\n";
}
y++;
}
x++;
}
convertStreamToString(traceRt.getErrorStream());
} catch (IOException e) {
}
try {
if (!arquivo.exists()) {
// cria um arquivo (vazio)
arquivo.createNewFile();
}
// caso seja um diretório, é possível listar seus arquivos e diretórios
File[] arquivos = arquivo.listFiles();
// escreve no arquivo
FileWriter fw = new FileWriter(arquivo, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(route.replaceAll("\\s", " "));
bw.newLine();
bw.close();
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
}

JavaFX label set to Variable problems

Im trying to build an Installer/Updater for a project im working on.
My only problem im facing is that my variable of my progess bar doesn't want to be displayed in a label :C.
I already looked up and found an answer from Sebastian who said
myLabel.textProperty().bind(valueProperty); should work but ... well you guess the outcome.
Eclipse says I have to change the type of my int to: ObservableValue<? extends String> and when I changed it it says I have to change it back to int. I dont know what I have to do now ://
EDIT: Full code of my controller class
package application;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
public class Controller {
#FXML
ProgressBar pb;
Label progText;
public void install(){
new Thread(new Runnable() {
#Override public void run() {
download();
}}).start();
};
public void load(){
new Thread(new Runnable() {
#Override public void run() {
download();
Unzip.extract();
System.out.println("Finished");
}}).start();
};
public void download(){
try {
System.out.println("Start");
URL url = new URL("https://www.dropbox.com/s/27d4us64oqifuph/modpack.zip?dl=1");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"modpack.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
//calculate progress
int cp = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 10000);
DoubleProperty progress = new SimpleDoubleProperty(0);
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001);
progText.textProperty().bind(progress.asString());
bout.write(data, 0, x);
}
bout.close();
in.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
}
Create a DoubleProperty that is bound to the label and is updated when you update the progressbar.
DoubleProperty progress = new SimpleDoubleProperty(0);
progText.textProperty().bind(progress.asString());
...
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001)

send a ping to multiple ip addresses at the same time

i did a code wish send a ping to multiple ip adresses and get the value of time from each ping request and then print write the result in a from of a matrix in a text file....anyway my problem is that after i finished my code i figure out that i should send the ping to these adresses at the same time or in my code i did send it consecutively to the adresses.i really i hope if someone helps me with it...
code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Pinggg extends JFrame{
private boolean stop = false; // start or stop the ping
public Pinggg(){
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton btnStart=new JButton("demarrer le test");
cp.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
stop = false;
try {
final Formatter x = new Formatter("C:/Users/VAIO/workspace/tcc/gastoon/kkk.txt");
PrintWriter writer;
writer = new PrintWriter("C:Users/VAIO/workspace/tcc/gastoon/kkk.txt");
for (int m = 0; m < 10; m++) {
if (stop) break;
// check if STOP button has been pushed,
// which changes the stop flag to true
DocumentBuilderFactory BuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder db=BuilderFactory.newDocumentBuilder();
Document doc=db.parse("C:/Users/VAIO/workspace/tcc/gastoon/adresStore.xml");
doc.normalize();
NodeList rootNodes=doc.getElementsByTagName("connection");
Node rootNode=rootNodes.item(0);
Element rootElement=(Element) rootNode;
NodeList l=rootElement.getElementsByTagName("users");
Node users=l.item(0);
Element element=(Element) users;
NodeList nl=element.getElementsByTagName("user");
List<String> allIps = new ArrayList<String>();
for(int i=0;i<nl.getLength();i++){
Node user=nl.item(i);
Element ele=(Element) user;
String adrss=ele.getElementsByTagName("ipAdress").item(0).getTextContent();//+" -n 1";
//System.out.println(adrss);
allIps.add(i, adrss);
//writer.print(allIps.get(i)+" ");
// System.out.println(adrss);
//System.out.println(i);
// writer.format("%s ",i);
//writer.println( adrss);
}
// for(String n : allIps)
//{
// writer.print(allIps+" ");
//}
writer.println("\n");
for(int j=0;j<allIps.size();j++)
{
//writer.print(allIps.get(i)+" ");
String pingCmd = "ping " +allIps.get(j) +" -n 1";
String pingResult = "";
String str="";
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
// writer.println(inputLine);
//System.out.println(inputLine);
pingResult += inputLine;
}
String[] lines = pingResult.split("\n");
List<String> bb = new ArrayList<String>();
for (int k=0;k<lines.length;k++) {
String line=lines[k];
if ((line.contains("temps=") && (line.contains(allIps.get(j))))){
// Find the index of "time="
int index = line.indexOf("temps=");
String time = line.substring(index + "temps=".length(),line.indexOf("ms"));
//bb.add(time);
// writer.print(allIps.get(j)+" ");
writer.print(time);
//System.out.println(allIps.get(j)+" ");
System.out.println(time);
}
else {
writer.print("NON"+" ");
}
}
int[]tab=new int[allIps.size()];
for(int d=0;d<tab.length;d++ ){
}
}
catch (IOException ie) {
System.out.println(ie);
}
}}
writer.flush();
}//}
catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (ParserConfigurationException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
);
JButton btnStop = new JButton("Analyser le test ");
cp.add(btnStop);
btnStop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
stop = false; // set the stop flag
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cp.setBackground(Color.black);
setTitle("PING");
setSize(300, 120);
setVisible(true);
}
}
It depends on what you mean by "i should send the ping to these adresses [sic] at the same time".
1) Create a threadppol and send your requests through that. This will batch up your ping requests (to the size of the threadpool). However this is technically not "at the same time".
2) Ping the broadcast address. Whether or not this works (or rather works how you think it works) depends on your network setup. It won't work on the Internet, but it may work on a corporate LAN. So it depends on the nature of the IP addresses you are trying to ping.

How to change JFrame icon [duplicate]

This question already has answers here:
How to set Icon to JFrame
(12 answers)
Closed 6 years ago.
I have a JFrame that displays a Java icon on the title bar (left corner).
I want to change that icon to my custom icon. How should I do it?
Create a new ImageIcon object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame with setIconImage():
myFrame.setIconImage(img.getImage());
Also checkout setIconImages() which takes a List instead.
Here is an Alternative that worked for me:
yourFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
It's very similar to the accepted Answer.
JFrame.setIconImage(Image image) pretty standard.
Here is how I do it:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MainFrame implements ActionListener{
/**
*
*/
/**
* #param args
*/
public static void main(String[] args) {
String appdata = System.getenv("APPDATA");
String iconPath = appdata + "\\JAPP_icon.png";
File icon = new File(iconPath);
if(!icon.exists()){
FileDownloaderNEW fd = new FileDownloaderNEW();
fd.download("http://icons.iconarchive.com/icons/artua/mac/512/Setting-icon.png", iconPath, false, false);
}
JFrame frm = new JFrame("Test");
ImageIcon imgicon = new ImageIcon(iconPath);
JButton bttn = new JButton("Kill");
MainFrame frame = new MainFrame();
bttn.addActionListener(frame);
frm.add(bttn);
frm.setIconImage(imgicon.getImage());
frm.setSize(100, 100);
frm.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
and here is the downloader:
import java.awt.GridLayout;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
public class FileDownloaderNEW extends JFrame {
private static final long serialVersionUID = 1L;
public static void download(String a1, String a2, boolean showUI, boolean exit)
throws Exception
{
String site = a1;
String filename = a2;
JFrame frm = new JFrame("Download Progress");
JProgressBar current = new JProgressBar(0, 100);
JProgressBar DownloadProg = new JProgressBar(0, 100);
JLabel downloadSize = new JLabel();
current.setSize(50, 50);
current.setValue(43);
current.setStringPainted(true);
frm.add(downloadSize);
frm.add(current);
frm.add(DownloadProg);
frm.setVisible(showUI);
frm.setLayout(new GridLayout(1, 3, 5, 5));
frm.pack();
frm.setDefaultCloseOperation(3);
try
{
URL url = new URL(site);
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0.0F;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int i = 0;
while ((i = in.read(data, 0, 1024)) >= 0)
{
totalDataRead += i;
float prog = 100.0F - totalDataRead * 100.0F / filesize;
DownloadProg.setValue((int)prog);
bout.write(data, 0, i);
float Percent = totalDataRead * 100.0F / filesize;
current.setValue((int)Percent);
double kbSize = filesize / 1000;
String unit = "kb";
double Size;
if (kbSize > 999.0D) {
Size = kbSize / 1000.0D;
unit = "mb";
} else {
Size = kbSize;
}
downloadSize.setText("Filesize: " + Double.toString(Size) + unit);
}
bout.close();
in.close();
System.out.println("Took " + System.nanoTime() / 1000000000L / 10000L + " seconds");
}
catch (Exception e)
{
JOptionPane.showConfirmDialog(
null, e.getMessage(), "Error",
-1);
} finally {
if(exit = true){
System.exit(128);
}
}
}
}
Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());
Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.
Here's what worked for me:
import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')
frame.setIconImage(icon.getImage());
frame.setVisible(True)
This did the trick in my case super or this referes to JFrame in my class
URL url = getClass().getResource("gfx/hi_20px.png");
ImageIcon imgicon = new ImageIcon(url);
super.setIconImage(imgicon.getImage());
Add the following code within the constructor like so:
public Calculator() {
initComponents();
//the code to be added this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage()); }
Change "color.png" to the file name of the picture you want to insert.
Drag and drop this picture onto the package (under Source Packages) of your project.
Run your project.

Categories