2 回答
TA贡献1797条经验 获得超4个赞
这是一个从 100 个按钮到6,400个按钮添加到 GUI 的 MCVE / SSCCE ,每个按钮都有自己的图标。
这里的典型输出:
It took 14 milliseconds for 100 buttons.
It took 110 milliseconds for 1600 buttons.
It took 138 milliseconds for 6400 buttons.
它可能看起来像一个框架。
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.net.*;
import javax.swing.*;
import javax.imageio.*;
public class LotsOfButtons {
public final JComponent getUI(int pts) {
JComponent ui = new JPanel(new GridLayout(0, pts));
try {
BufferedImage image = ImageIO.read(new URL(
"https://i.stack.imgur.com/OVOg3.jpg"));
int wT = image.getWidth() / pts;
int hT = image.getHeight() / pts;
Insets insets = new Insets(0, 0, 0, 0);
long t1 = System.currentTimeMillis();
for (int jj = 0; jj < pts; jj++) {
for (int ii = 0; ii < pts; ii++) {
int x = ii * wT;
int y = jj * hT;
JButton b = new JButton(new ImageIcon(
image.getSubimage(x, y, wT, hT)));
b.setMargin(insets);
ui.add(b);
}
}
long t2 = System.currentTimeMillis();
System.out.println(String.format(
"It took %1s milliseconds for %1s buttons.",
(t2 - t1), pts*pts));
} catch (IOException ex) {
ex.printStackTrace();
}
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
JOptionPane.showMessageDialog(
null, new LotsOfButtons().getUI(10));
JOptionPane.showMessageDialog(
null, new LotsOfButtons().getUI(40));
JOptionPane.showMessageDialog(
null, new LotsOfButtons().getUI(80));
};
SwingUtilities.invokeLater(r);
}
}
因此,鉴于“(> 30秒)”14 milliseconds附近没有任何地方,我猜您会这样做..不同。除非该源(以上)可以帮助您解决问题,否则我建议准备并发布一个热链接到图像的 MCVE / SSCCE,就像上面的源代码一样,将是解决问题的最佳举措。
TA贡献1878条经验 获得超4个赞
您的问题可能出在 TileButton 类中:
class TileButton extends JButton {
private int id;
private TileSet ts = new TileSet("Content/Graphics/tileSets/12x12x3 - tileSet.png", 12, 12, 3);
private int size = 50;
public TileButton(int id, TileSet tileSet) {
super();
this.ts = tileSet;
this.id = id;
loadImage(id);
}
为每个 TileButton 创建新的 TileSet。此图块集从文件中读取 - 这可能会导致相当大的延迟。然后你忽略这个瓦片集并使用在构造函数中传递的瓦片集。
因此,您不应该每次都创建新的 TileSet:
class TileButton extends JButton {
private int id;
private final TileSet ts;
private int size = 50;
public TileButton(int id, TileSet tileSet) {
super();
this.ts = tileSet;
this.id = id;
loadImage(id);
}
添加回答
举报