按下按钮时 Java 更改 JPanel 中的图像

问题描述 投票:0回答:1

我很清楚其他几篇类似性质的帖子。我一直在尝试使用它们来帮助我,但是要么我只是忽略了某些东西,要么我的代码缺少正常工作所必需的东西。我有一个主 JPanel,我试图在每次按下按钮时更改图像(并且我开始认为我的计划在按下不同按钮时更改布局会困难得多),但是当它来到@Override部分,我发现图标无法更改,或者当我尝试实现从stackOverflow或VSCode中建议的东西时,它会导致很多红线。

我想要的是有一个可用的图像数组,这样当按下按钮时,它会运行一个随机数生成器并输出一个数字,该数字可以从数组中随机抓取图片。不用担心,我希望我在随机数生成部门受过良好的教育。

是的,我知道这是一团糟。在过去的几周里,我已经尝试了好几次来解决这个问题(开始时每天只花几个小时保持理智,最后以不间断的 72 小时课程结束,从睡梦中醒来尝试不同的想法)

这是我的代码的一些部分,我包括了我认为必要的部分,因为我已经写了很多并且导航是一场噩梦。

private JPanel topRow, leftPane, mainPane, bottomRow, mPane1;
private JButton btnOne, btnTen, btnHun, btnTho;
private JTextArea mPane2, test;
private String imagePath, name;
private ImageIcon image;

public  WSgui() {
    super("Character Wish Simulator");
    this.setSize(900, 600);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());

    this.mainPane = new JPanel();
    this.mainPane.setBackground(Color.ORANGE);
    this.mainPane.setMinimumSize(new Dimension(650, 400));
    this.mainPane.setBorder(new EmptyBorder(40,40,40,40));
    this.mainPane.setLayout(new BorderLayout());

    //buttons
    this.btnOne = new JButton("x1 wish");
    this.btnOne.setSize(200, 100);

    //setting panes for main
    this.mPane1 = new JPanel();
    int xSize = ((int) mainPane.getSize().getWidth());  
    int ySize = ((int) mainPane.getSize().getHeight());  
    int height = (int)(Math.round(ySize * 0.80));
    int width = (int)(Math.round(xSize * 0.80));
    this.mPane1.setPreferredSize(new Dimension(width, height));
    this.mPane1.setMinimumSize(new Dimension(xSize, ySize));
    this.mPane1.setMaximumSize(new Dimension(1000, 1000));

    this.mPane2 = new JTextArea();
    this.mPane2.setText("This should be below the picture");
    this.mPane2.setFont(new Font("Dialog", Font.PLAIN, 15));
    this.mPane2.setMaximumSize(new Dimension(width, 50));
    this.mPane2.setWrapStyleWord(true);
    this.mPane2.setLineWrap(true);
    this.mPane2.setEditable(false);

    this.btnTen = new JButton("x10 wish");
    this.btnTen.setSize(200, 50);
    this.btnTen.addActionListener(this);
    //This idea (action listener) came from StackOverflow, but sadly is not working

    this.btnHun = new JButton("x100 wish");
    this.btnHun.setSize(200, 50);
    this.btnHun.addActionListener(this);

    this.btnTho = new JButton("x1000 wish");
    this.btnTho.setSize(200, 50);
    this.btnTho.addActionListener(this);

    //Test image for Main Pane
    image = new ImageIcon(bnr);//some more ideas I found
    JLabel image5 = new JLabel(image);
    JLabel image2 = new JLabel(new ImageIcon(lpImage));
    JLabel image3 = new JLabel(new ImageIcon(mImage));
    JLabel image4 = new JLabel(new ImageIcon(xtra));
    this.mPane1.add(image3);
    this.leftPane.add(image2);
    this.topRow.add(image5);
    this.bottomRow.add(image4);
    this.mainPane.add(this.mPane1, BorderLayout.CENTER);
    this.mainPane.add(this.mPane2, BorderLayout.SOUTH);
    this.btnOne.addActionListener(e -> image5.setIcon(images[3]));
    ImageIcon[] images = new ImageIcon[] {//my pathetic attempt at an array
        new ImageIcon("img/t1.png"), new ImageIcon("img/t2.png"), new ImageIcon("img/t3.jpg"),
        new ImageIcon("img/t4.jpg"), new ImageIcon("img/t5.png")
    };

    String[] image8 = new String[] {
        "img/t1.png"//idk how to explain this one
    };  

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == btnOne) {
            String image9 = image8[0];//and this is what I struggle with
            ImageIcon icon9 = new ImageIcon(image9);
            icon9.getImage().flush();
            image.setIcon(icon9);
        }
    }
}

如果你需要我,我可能正忙于这段代码。它一个人呆得够久了。我必须再次关注它。

java swing
1个回答
0
投票

Oracle 有一个有用的教程,使用 Swing 创建 GUI。 跳过使用 NetBeans IDE 学习 Swing 部分。

我尝试将您的代码复制到我的 IDE 中并运行它。 我不能。我重新开始并创建了这个 GUI。

Character

我使用了来自互联网的两张图像,因此任何人都可以运行此代码。

我将代码分解为单独的类和方法。这使我能够单独测试每个部分。

我创建了一个

ImageCollection

 类来读取互联网上的图像。  您可以修改此类以从资源目录中读取。

我创建了一个

JFrame

 和两个 
JPanels
。  我使用 
Swing 布局管理器 来管理两个 JPanel
 布局。

这是完整的可运行代码。 我将 ImageCollection 类设置为一个内部类,这样我就可以将代码作为一个块发布。

import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class MultipleImageDisplay implements ActionListener, Runnable { public static void main(String[] args) { SwingUtilities.invokeLater(new MultipleImageDisplay()); } private int imageIndex; private final ImageCollection imageCollection; private JLabel imageLabel; public MultipleImageDisplay() { this.imageCollection = new ImageCollection(); this.imageIndex = 0; } @Override public void run() { JFrame frame = new JFrame("Character Wish Simulator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(createMainPanel(), BorderLayout.CENTER); frame.add(createButtonPanel(), BorderLayout.EAST); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } private JPanel createMainPanel() { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); imageLabel = new JLabel(); imageLabel.setIcon( new ImageIcon(imageCollection.getImages()[imageIndex])); panel.add(imageLabel); return panel; } private JPanel createButtonPanel() { JPanel panel = new JPanel(new FlowLayout()); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JPanel innerPanel = new JPanel(new GridLayout(0, 1, 5, 5)); JButton btnTen = new JButton("x10 wish"); btnTen.addActionListener(this); innerPanel.add(btnTen); JButton btnHun = new JButton("x100 wish"); btnHun.addActionListener(this); innerPanel.add(btnHun); JButton btnTho = new JButton("x1000 wish"); btnTho.addActionListener(this); innerPanel.add(btnTho); panel.add(innerPanel); return panel; } @Override public void actionPerformed(ActionEvent event) { imageIndex = ++imageIndex % imageCollection.getImagesLength(); imageLabel.setIcon( new ImageIcon(imageCollection.getImages()[imageIndex])); } public class ImageCollection { private Image[] images; public ImageCollection() { this.images = new Image[2]; this.images[0] = readImage("https://www.goodfreephotos.com/" + "albums/other-landscapes/mountains-and-pond-landscape" + "-with-majestic-scenery.jpg"); this.images[1] = readImage("https://cdn1.epicgames.com/ue/" + "product/Screenshot/RealisticLandscapes" + "%20125-1920x1080-a125dbb0885e785c4" + "fdafbf130b056b8.png?resize=1&w=1920"); } @SuppressWarnings("deprecation") private Image readImage(String urlString) { URL url; try { url = new URL(urlString); Image image = ImageIO.read(url); return image.getScaledInstance(960, 540, Image.SCALE_SMOOTH); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public Image[] getImages() { return images; } public int getImagesLength() { return images.length; } } }
    
© www.soinside.com 2019 - 2024. All rights reserved.