我有一个关于使用设置的图标调整JLabel大小的问题。
我的解决方案是创建一个Timer,它通过调用Actionperformed() - ActionListener-Interface的方法来调整Label的大小。
有没有更好的解决方案?
package examples;
import images.MyImage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class examples2 {
private static JFrame frame = new JFrame();
private static JPanel panel = new JPanel(new BorderLayout());
private static class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Image image = resizeImage(MyImage.IMAGE_BLUE_BLACKGROUND,
panel.getWidth(), panel.getHeight());
label.setIcon(new ImageIcon(image));
}
}
private static ActionListener buttonhandler = new ButtonHandler();
private static Timer timer = new Timer(100, buttonhandler);
private static JLabel label = new JLabel(new ImageIcon(resizeImage(
MyImage.IMAGE_BLUE_BLACKGROUND, 1600, 100)));
public static void main(String[] args) {
JPanel northPanel = new JPanel(new BorderLayout());
JLabel text = new JLabel("Hakan Kiyar");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(northPanel, BorderLayout.NORTH);
frame.getContentPane().add(new JButton(), BorderLayout.CENTER);
frame.setVisible(true);
northPanel.add(Box.createVerticalStrut(10), BorderLayout.NORTH);
northPanel.add(Box.createHorizontalStrut(10), BorderLayout.WEST);
northPanel.add(Box.createHorizontalStrut(10), BorderLayout.EAST);
northPanel.add(Box.createVerticalStrut(10), BorderLayout.SOUTH);
northPanel.add(panel, BorderLayout.CENTER);
text.setForeground(Color.YELLOW);
label.setLayout(new GridBagLayout());
label.add(text);
panel.add(label);
frame.setSize(364, 300);
timer.start();
}
public static Image resizeImage(Image oldImage, int width, int height) {
Image newImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = newImage.getGraphics();
g.drawImage(oldImage, 0, 0, null);
g.dispose();
return newImage;
}
}
答案 0 :(得分:2)
您可以使用Darryl的Stretch Icon课程动态调整图标大小。
它将调整Icon的大小以填充标签可用的空间。您可以将类配置为拉伸图标以填充整个空间,或者在空间可用时尊重宽高比。