使用计时器在 JLabel 中刷新图像
Refresh Image in JLabel with Timer
我目前正在开发一个小程序 在一个小 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);
}
}
}
}
这是我当前的代码。
由于language.But不同,我无法理解变量命名约定,据我所知,我认为你不应该在每次更新时调用new PageReader()
。
相反,你应该调用 update(int pos)
public void update(int pos)
{
//The Code that went into your constructor
}
这将确保重复使用相同的 JFrame
而不是创建新的。
另外我认为你不应该每次都初始化一个新的 JLabel
或 JPanel
,相反你应该在构造函数中将 JLabel
添加到 JPanel
并且在 update
函数中,调用 picture.setIcon(icon);
而不创建新的 JLabel
.
您的构造函数应如下所示:
public PageReader()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
picture=new JLabel();
JPanel anzeige = new JPanel();
anzeige.add(picture, BorderLayout.CENTER);
setContentPane(anzeige);
pack();
setResizable(false);
setVisible(true);
}
构造函数中剩余的代码部分应该转到 update
编辑:
public void update(int pos) throws IOException
{
urlString = "http:"+viewable[pos];
url = new URL(urlString);
image = ImageIO.read(url);
ImageIcon icon = new ImageIcon(image);
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));
}
现在在主class中,你应该声明类似
的东西
PageReader pr=new PageReader
无论你在哪里使用 new PageReader(4)
,你都应该使用 pr.update(4)
@MegaCleptomaniac,我不是图像方面的专家,所以我认为你应该听听@MadProgrammer 关于不使用 getScaledInstance
的说法
先看看 Concurrency in Swing and Worker Threads and SwingWorker
您可能还想看看 jsoup,因为使用 String#substring
等来解析 html 是一个非常糟糕的主意
Swing 是单线程的,这意味着您不能使用阻塞或长 运行 进程(如 Thread.sleep
)来阻塞事件调度线程,但它也不是线程安全的,这意味着您应该' 从 EDT 外部修改它。
为此,SwingWorker
提出了一个合理的解决方案,因为它可以在 EDT 之外处理 html 和图像下载,但提供了多种方法可以将更新重新同步到 EDT .
首先,您需要更新 JLabel
的 icon
属性 而不是创建 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 image and Quality of Image after resize very low -- Java 的替代方案
我目前正在开发一个小程序 在一个小 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);
}
}
}
}
这是我当前的代码。
由于language.But不同,我无法理解变量命名约定,据我所知,我认为你不应该在每次更新时调用new PageReader()
。
相反,你应该调用 update(int pos)
public void update(int pos)
{
//The Code that went into your constructor
}
这将确保重复使用相同的 JFrame
而不是创建新的。
另外我认为你不应该每次都初始化一个新的 JLabel
或 JPanel
,相反你应该在构造函数中将 JLabel
添加到 JPanel
并且在 update
函数中,调用 picture.setIcon(icon);
而不创建新的 JLabel
.
您的构造函数应如下所示:
public PageReader()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
picture=new JLabel();
JPanel anzeige = new JPanel();
anzeige.add(picture, BorderLayout.CENTER);
setContentPane(anzeige);
pack();
setResizable(false);
setVisible(true);
}
构造函数中剩余的代码部分应该转到 update
编辑:
public void update(int pos) throws IOException
{
urlString = "http:"+viewable[pos];
url = new URL(urlString);
image = ImageIO.read(url);
ImageIcon icon = new ImageIcon(image);
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));
}
现在在主class中,你应该声明类似
的东西PageReader pr=new PageReader
无论你在哪里使用 new PageReader(4)
,你都应该使用 pr.update(4)
@MegaCleptomaniac,我不是图像方面的专家,所以我认为你应该听听@MadProgrammer 关于不使用 getScaledInstance
先看看 Concurrency in Swing and Worker Threads and SwingWorker
您可能还想看看 jsoup,因为使用 String#substring
等来解析 html 是一个非常糟糕的主意
Swing 是单线程的,这意味着您不能使用阻塞或长 运行 进程(如 Thread.sleep
)来阻塞事件调度线程,但它也不是线程安全的,这意味着您应该' 从 EDT 外部修改它。
为此,SwingWorker
提出了一个合理的解决方案,因为它可以在 EDT 之外处理 html 和图像下载,但提供了多种方法可以将更新重新同步到 EDT .
首先,您需要更新 JLabel
的 icon
属性 而不是创建 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 image and Quality of Image after resize very low -- Java 的替代方案