2 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是一個(gè)從 100 個(gè)按鈕到6,400個(gè)按鈕添加到 GUI 的 MCVE / SSCCE ,每個(gè)按鈕都有自己的圖標(biāo)。
這里的典型輸出:
It took 14 milliseconds for 100 buttons.
It took 110 milliseconds for 1600 buttons.
It took 138 milliseconds for 6400 buttons.
它可能看起來(lái)像一個(gè)框架。
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附近沒(méi)有任何地方,我猜您會(huì)這樣做..不同。除非該源(以上)可以幫助您解決問(wèn)題,否則我建議準(zhǔn)備并發(fā)布一個(gè)熱鏈接到圖像的 MCVE / SSCCE,就像上面的源代碼一樣,將是解決問(wèn)題的最佳舉措。

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的問(wèn)題可能出在 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);
}
為每個(gè) TileButton 創(chuàng)建新的 TileSet。此圖塊集從文件中讀取 - 這可能會(huì)導(dǎo)致相當(dāng)大的延遲。然后你忽略這個(gè)瓦片集并使用在構(gòu)造函數(shù)中傳遞的瓦片集。
因此,您不應(yīng)該每次都創(chuàng)建新的 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);
}
添加回答
舉報(bào)