【问题标题】:Adding an image in jpanel inside of a action listener在动作侦听器内的 jpanel 中添加图像
【发布时间】:2013-04-29 23:43:42
【问题描述】:

女士们,先生们,你们好, 我再次无法弄清楚对您来说可能很简单的事情。 我正在尝试加载 3 个图像 space.jpeg、treefrog.jpeg 和 yosemite.jpeg(当您单击显示相应图像的单选按钮时)并尝试调整我能找到的每个示例。如果有人想指出我正确的方向,我将不胜感激。

package guiprogramming;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class ChooseImage extends JPanel {
   private JPanel panel1;
   private SimplePanel drawingPanel;
   JRadioButton button1, button2, button3;

public ChooseImage() {
   setLayout(new BorderLayout());
   panel1 = new JPanel();
   drawingPanel = new SimplePanel();
   button1 = new JRadioButton("Scenery");
   panel1.add(button1);
   button2 = new JRadioButton("Space");
   panel1.add(button2);
   button3 = new JRadioButton("Tree Frog");
   panel1.add(button3);

   ButtonGroup group = new ButtonGroup();
    group.add(button1);
    group.add(button2);
    group.add(button2);

  this.add(panel1, BorderLayout.NORTH);
  this.add(drawingPanel, BorderLayout.CENTER);


  button1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
     //This is where I am trying to get the images to load
     }});

  button2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
     //This is where I am trying to get the images to load
     }});

  button3.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
    //This is where I am trying to get the images to load
    }});








  }

  public static void main(String[] args) {
  JFrame window = new JFrame("Choose Image");
  ChooseImage panel = new ChooseImage();
  window.setContentPane(panel);
  window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  window.setSize(500, 500);
  window.setVisible(true);
  }
  }

【问题讨论】:

  • 代码运行时会发生什么?是否显示任何图像?另外,您能否改进您的代码格式,以便我们更容易阅读和理解它?您没有显示加载图像的尝试 - 为什么?
  • //This is where I am trying to get the images to load 很好。你有什么尝试(我的意思是除了提出研究要求然后问我们)?
  • 我将如何改进我的格式我目前是一名学生,还没有这样的课程,所以非常感谢建议。
  • 请阅读正确的 Java 代码格式。可以在 Google 上找到链接。一个关键是使用一致且规则的缩进,以便单个块上的所有代码均等缩进,通常为 3 个空格。你有一些没有任何缩进的代码,很难阅读。
  • 图像 image=new ImageIcon("space.jpeg").getImage(); g.drawImage(image) 这是我在这里找到的信息的第一次尝试(StackOverflow)

标签: java


【解决方案1】:
  1. 不要在每次调用 ActionListener 时加载图像。
  2. 在程序启动时加载一次图像。
  3. 使用ImageIO.read(...) 读取图像。你可以找到ImageIO API here
  4. 将图像放入 ImageIcons。
  5. 在 ActionListeners 中,通过其 setIcon(...) 方法交换 JLabel 的图标。
  6. 在实现复杂功能时,请逐步独立地执行此操作。换句话说,首先创建一个显示图像的小程序,并且只有在成功创建一个按下按钮时交换的小程序。
  7. 今后,请向我们展示您实现功能的尝试。这样做可以让我们更好地了解您的误解或问题。

【讨论】:

  • “通过 setIcon(...) 方法交换 JLabel 的图标” 示例参见 ImageViewer
  • 谢谢,朝着正确的方向迈出了一步!完成后将发布我的小程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 2011-08-21
  • 2013-04-28
相关资源
最近更新 更多