我想知道是否可以加载一个ImageIcon数组来加载来自在线源的图像,这样图像就不会存储在本地。是否有一种方法可以将动作侦听器添加到按钮数组中,以便在按下它们时打开一个新帧。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MenuView extends JFrame {
String[] names =
{"banana split", "chicken with rice", "rice", "noodles", "fried vermicelli", "smoothie"};
String[] namesImage = {"banana split.jpeg", "chicken with rice.jpeg", "rice.jpeg", "noodles.jpeg",
"fried vermicelli.jpeg", "smoothie.jpeg"};
ImageIcon[] foodImages = new ImageIcon[namesImage.length];
JButton[] jbtChoc = new JButton[names.length];
{
for (int i = 0; i < names.length; i++) {
jbtChoc[i] = new JButton(names[i]);
for (int x = 0; x < names.length; x++) {
foodImages[x] = new ImageIcon(namesImage[x]);
}
}
}
/**
* Constructor for the MenuView.
*/
public MenuView() {
Container cont = getContentPane();
cont.setLayout(new BorderLayout(5, 5));;
cont.setBackground(Color.white);
JPanel girdSetup = new JPanel(new GridLayout(2, 3, 5, 5));
for (int i = 0; i < foodImages.length; i++) {
jbtChoc[i].setIcon(foodImages[i]);
girdSetup.add(jbtChoc[i]);
jbtChoc[i].setVerticalTextPosition(AbstractButton.BOTTOM);
jbtChoc[i].setHorizontalTextPosition(AbstractButton.CENTER);
}
cont.add(girdSetup, BorderLayout.CENTER);
}
/**
* Main method for test.
*
* @param args Initial setup.
*/
public static void main(String[] args) {
MenuView frame = new MenuView();
frame.setTitle("MenuView");
frame.setSize(950, 400);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:2)
如果可以加载ImageIcon数组以加载来自在线源的图像
来自网址的图片图标
URL url = new URL("UrlPath");
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
在你的情况下
URL url = new URL(namesImage[x]);
BufferedImage img = ImageIO.read(url);
foodImages[x] = new ImageIcon(img);
有没有办法将动作侦听器添加到按钮数组
将动作侦听器添加到按钮数组
jbtChoc[i].addActionListener(this);
按下它们时会打开一个新框架。
您的行动执行方法
public void actionPerformed(ActionEvent e){
if( e.getSource() instanceof JButton) {
//do your action here
}
}