【问题标题】:Changing Image on click with Java/Swing Jframe使用 Java/Swing Jframe 点击更改图像
【发布时间】:2013-09-27 04:34:00
【问题描述】:

好的,那里有类似的问题,但我遇到的问题是具体的。

我拥有的是一个带有 3 个按钮的简单 jFrame。当按下其中一个按钮时,它将计算一首歌曲的 BPM。它还将编辑 StringBuilder 对象以创建图像的 url 路径。这部分输出很好,这是我的控制台输出。

104.9      //Bpm of Song
One        //String representation of first char in array
Zero       //String representation of Second char in array
Four       //String representation of Third char in array
Nine       //String representation of Fifth char in array
res/1.png  // 
res/0.png  // New Url paths
res/4.png  //
res/9.png  //

我的问题出在代码中。

JButton tapButton = new JButton("Tap");
    tapButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            MathFunctions.tapBPM();
            ArrayComparison.stringCharArrays();

            String urlLocationOne = (ArrayComparison.urlLocationOneBuild.toString());
            String urlLocationTwo = (ArrayComparison.urlLocationTwoBuild.toString());
            String urlLocationThree = (ArrayComparison.urlLocationThreeBuild.toString());
            String urlLocationFive = (ArrayComparison.urlLocationFiveBuild.toString());

        }
    });
    tapButton.setBounds(100, 150, 120, 45);
    contentPane.add(tapButton);

urlLocation[number]Build 是一个 StringBuilder 对象。每次单击时,它都会检查模板 url,删除数字并替换它(我们知道这一点可以正常工作)。问题来自图像。如果我在它不加载的 tapButton ActionEvent 中创建一个新图像,我必须创建图像,因为它是自己的 JLabel(在按钮之外)

(这里是 JLabel 的代码(其中有五个,我只给你看一个))

JLabel locationOne = new JLabel("Image 1");
locationOne.setBackground(Color.WHITE); 
locationOne.setIcon(new ImageIcon(urlLocationOne));   //urlLocationOne not available outside of button
locationOne.setBounds(84, 38, 66, 100);
contentPane.add(locationOne);

所以如果 imageIcon 是在按钮内部创建的,它不起作用,如果它是在按钮外部创建的,它在“urlLocationOne”的范围之外,如果我创建一个字段,我会创建一个只在内部更改的不可变字符串点击按钮,当在 tapButton 方法之外调用时,它会显示原始字符串。放置图像的最佳方式是什么,以便图像响应每次点击时的路径变化。 (记住路径正在改变,我只是无法让 ImageIcon JLabel '听到'改变。)

【问题讨论】:

    标签: java jframe jbutton scope imageicon


    【解决方案1】:

    好吧,在坚持了两天的问题绘制图表和巨大的压力之后,答案似乎来自一个良好的睡眠。在这里

    final JLabel locationOne = new JLabel("Image 1");
        locationOne.setBackground(Color.WHITE);
        tapButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        String urlLocationOne = (ArrayComparison.urlLocationOneBuild.toString());
        locationOne.setIcon(new ImageIcon(urlLocationOne));
            }
        });
        locationOne.setBounds(84, 38, 66, 100);
        contentPane.add(locationOne);
    

    而不是尝试使用返回和废话访问在另一个方法中创建的字符串,因为某些原因无法正常工作。我在 jLabel 中为 Image 创建了一个新的动作侦听器。这听了同一个按钮,但只有一个动作 - 在本地创建字符串。 (事后看来很合乎逻辑!!!!!!)

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多