gpt4 book ai didi

java - 使用计时器刷新 JLabel 中的图像

转载 作者:行者123 更新时间:2023-11-30 03:22:16 25 4
gpt4 key购买 nike

我目前正在开发一个小程序,它可以在小型 Swing GUI 中显示网站上的图片。问题是,每次图片更改时都会弹出一个新框架,而不是刷新 JLable。

在尝试了几次不同的方法后,我不知道如何实现这一点。

如果你能给我一点提示,那就太好了。

import java.awt.BorderLayout;
import java.awt.Image;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;


public class PageReader extends JFrame {

JLabel picture;
static String[] viewable;
int counter;
static String urlString;
Image image;
URL url;

public PageReader(int pos) throws IOException
{
urlString = "http:"+viewable[pos];

url = new URL(urlString);
image = ImageIO.read(url);

ImageIcon icon = new ImageIcon(image);

picture = new JLabel();
picture.setIcon(icon);


int breite = icon.getImage().getWidth(this);
int hoehe = icon.getImage().getHeight(this);


do
{
if(hoehe>400)
{
breite *= 0.75;
hoehe *= 0.75;
icon.setImage(icon.getImage().getScaledInstance(breite, hoehe, image.SCALE_DEFAULT));
}

if(hoehe<400)
{
hoehe *= 1.2;
breite *=1.2;
icon.setImage(icon.getImage().getScaledInstance(breite, hoehe, image.SCALE_DEFAULT));
}
}while(hoehe>400&&hoehe<300);


icon.setImage(icon.getImage().getScaledInstance(breite, hoehe, image.SCALE_DEFAULT));


JPanel anzeige = new JPanel();
anzeige.add(picture, BorderLayout.CENTER);

setContentPane(anzeige);


pack();
setResizable(false);
setVisible(true);
}



public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub

String meineURL = "http://www.pr0gramm.com/static/";

URL url = new URL(meineURL);

InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream());
BufferedReader br = new BufferedReader(isr);

// Kompletten Seiteninhalt auslesen
String line ="";
String quelltext ="";

while((line = br.readLine()) != null)
{
quelltext += line + "\r\n";
}

// Reader Schließen
br.close();
isr.close();

String test = quelltext.substring(1708);
String[] parts = test.split("<a href=");


for(int i=1; i<parts.length; i++)
{
parts[i]=parts[i].substring(1,15);
}

viewable = new String[parts.length];

for(int i = 1; i<(parts.length-1); i++)
{
String sitePath = "http://pr0gramm.com"+parts[i];

meineURL = sitePath;

url = new URL(meineURL);

isr = new InputStreamReader(url.openConnection().getInputStream());
br = new BufferedReader(isr);

// Kompletten Seiteninhalt auslesen
line ="";
quelltext ="";

while((line = br.readLine()) != null)
{
quelltext += line + "\r\n";
}

CharSequence picPath = quelltext.subSequence(quelltext.indexOf("//img.pr0gramm.com/"), quelltext.indexOf("//img.pr0gramm.com/")+50);

viewable[i] = picPath.toString();

// Seiteninhalt ausgeben
//System.out.println(quelltext);
System.out.println(viewable[i]);
}

System.out.println("\nLink-Counter: "+viewable.length);
//System.out.println("//img.pr0gramm.com/2015/06/25/87fd872bde0ab593.jpg");

new PageReader(4);
//System.out.println("\n \n \n Sub \n \n"+test);
for(int i = 1; i<viewable.length; i++)
{
if(!(viewable[i].contains(".web")))
{
url = new URL("http:"+viewable[i]);

new PageReader(i);

System.out.println("test"+i);
urlString = "http:"+viewable[i];
Thread.sleep(5000);
}
}


}

}

这是我当前的代码。

最佳答案

首先查看 Concurrency in SwingWorker Threads and SwingWorker

您可能还想看看 jsoup因为使用 String#substring 等来解析 html 是一个非常糟糕的主意

Swing 是单线程的,这意味着您不能通过阻塞或长时间运行的进程(例如 Thread.sleep )来阻塞事件调度线程,但它也不是线程安全的,这意味着您不应该'也不要从 EDT 外部修改它。

为此,SwingWorker 提供了一个合理的解决方案,因为它可以处理 EDT 之外的 html 和图像下载,但提供了多种将更新重新同步到 EDT 的方法。

首先,您需要更新 JLabelicon 属性,而不是创建 PageReader 的新实例,这是一个我们通常阻止人们从 JFrame 进行扩展的(许多)原​​因。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JLabel label;

public TestPane() {
setLayout(new BorderLayout());
label = new JLabel("Loading...");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
ImageWorker worker = new ImageWorker(label);
worker.execute();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}

public class ImageWorker extends SwingWorker<Object, Image> {

private JLabel output;

public ImageWorker(JLabel output) {
this.output = output;
}

@Override
protected void process(List<Image> chunks) {
output.setText(null);
output.setIcon(new ImageIcon(chunks.get(chunks.size() - 1)));
}

@Override
protected Object doInBackground() throws Exception {
String meineURL = "http://www.pr0gramm.com/static/";

URL url = new URL(meineURL);

String quelltext = "";
try (InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream()); BufferedReader br = new BufferedReader(isr)) {

// Kompletten Seiteninhalt auslesen
String line = "";

while ((line = br.readLine()) != null) {
quelltext += line + "\r\n";
}

}

String test = quelltext.substring(1708);
String[] parts = test.split("<a href=");

for (int i = 1; i < parts.length; i++) {
parts[i] = parts[i].substring(1, 15);
}

String[] viewable = new String[parts.length];

for (int i = 1; i < (parts.length - 1); i++) {
String sitePath = "http://pr0gramm.com" + parts[i];

meineURL = sitePath;

url = new URL(meineURL);

try (InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream()); BufferedReader br = new BufferedReader(isr)) {

// Kompletten Seiteninhalt auslesen
String line = "";
quelltext = "";

while ((line = br.readLine()) != null) {
quelltext += line + "\r\n";
}

CharSequence picPath = quelltext.subSequence(quelltext.indexOf("//img.pr0gramm.com/"), quelltext.indexOf("//img.pr0gramm.com/") + 50);

viewable[i] = picPath.toString();

}
}

System.out.println("\nLink-Counter: " + viewable.length);

for (int i = 1; i < viewable.length; i++) {
if (!(viewable[i].contains(".web"))) {
url = new URL("http:" + viewable[i]);

System.out.println("Reading " + url);
BufferedImage original = ImageIO.read(url);
Image image = original;

if (original.getWidth() > original.getHeight()) {
image = original.getScaledInstance(400, -1, Image.SCALE_SMOOTH);
} else {
image = original.getScaledInstance(-1, 400, Image.SCALE_SMOOTH);
}

publish(image);

System.out.println("test" + i);
Thread.sleep(5000);
}
}

return null;

}

}

}

}

还应该看看The try-with-resources Statement有关如何管理资源的更好想法

我不想在示例中引入更多代码,但如果可以的话,您应该避免使用 getScaledInstance,请参阅 The Perils of Image.getScaledInstance()了解更多详情。

您可以看看Java: maintaining aspect ratio of JPanel background imageQuality of Image after resize very low -- Java替代方案

关于java - 使用计时器刷新 JLabel 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31066606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com