简体   繁体   English

在JButton OnclickListener中编辑JLabel文本

[英]Edit JLabel Text in JButton OnclickListener

I am fairly new to programming, and I have recently begun messing with the JFrame in java. 我是编程的新手,最近我开始使用Java中的JFrame。 I am creating a program where the user can scroll through a pokedex using two buttons. 我正在创建一个程序,用户可以使用两个按钮在pokedex中滚动。 I have two JLabels, showing the pokedex number, and the pokedex name. 我有两个JLabel,分别显示pokedex编号和pokedex名称。 I have hit a roadblock, not able to change the jlabel text, based on strings and ints, which are edited within the onclick listener. 我遇到了一个障碍,无法基于在onclick侦听器中编辑的字符串和整数来更改jlabel文本。 Please tell me what I am doing wrong. 请告诉我我在做什么错。

package window;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class RunWindow extends Canvas implements Runnable{

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final int SCALE = 1;
    public static final String NAME = "Pokedex";
    public int pokedexNum = 1;
    public String pokedexName = "Bulbasaur";
    private JFrame frame;
    private JPanel panel = new JPanel();
    private JButton b1;
    private JButton b2;
    private boolean update = true;

    JLabel label;
    JLabel label2;
    public boolean running = false;

    public RunWindow(){
        BufferedImage imgUP = null;
        do {
            switch(pokedexNum){
                case 1:
                    pokedexName = "Bulbasaur";
                    break;
                case 2:
                    pokedexName = "Ivysaur";
                    break;
                case 3:
                    pokedexName = "Venisaur";
                    break;

            }
            label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);
            label2 = new JLabel("#"+pokedexNum);
            update = false;
        }while (update);

        label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);
        label2 = new JLabel("#"+pokedexNum);

        label.setLocation(50, 50);
        frame = new JFrame(NAME);
        b1 = new JButton("Up");
        b2 = new JButton("Down");
        frame.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
        frame.setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(this,BorderLayout.CENTER);
        frame.setResizable(false);
        frame.add(label);
        frame.add(label2);
        frame.add(panel);
        frame.add(b1);
        frame.add(b2);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        b1.setBounds(300, 400, 40, 20);
        b1.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) { 

                System.out.println(pokedexNum);
                if(pokedexNum <= 3){
                pokedexNum++;
                switch(pokedexNum){
                case 1:
                pokedexName = "Bulbasaur";
                break;
                case 2:
                pokedexName = "Ivysaur";
                break;
                case 3:
                pokedexName = "Venisaur";
                break;

                }
                label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);
                label2 = new JLabel("#"+pokedexNum);
                update = false;
                System.out.println(pokedexName);
                label.setText("Pokemon #"+pokedexNum+"-"+pokedexName);
                label2.setText("#"+pokedexNum);
                label.setText(label.getText());

                }
                }

        } );
        b2.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) {
                pokedexNum--;
                System.out.println("Down");
                }
                } );
        b2.setBounds(300, 420, 40, 20);
        b1.setHorizontalTextPosition(JButton.CENTER);
        b1.setVerticalTextPosition(JButton.CENTER);
        label.setBounds(300, 50, 200, 24); 
        label2.setBounds(340,400,80,20);
        frame.add( label, BorderLayout.NORTH );
        frame.add( panel , BorderLayout.CENTER);

    }
    public void run() {

    }
    public synchronized void start(){
        running = true;
        new Thread(this).start();

    }
    public void updatePokedex(){
        do {
            switch(pokedexNum){
                case 1:
                    pokedexName = "Bulbasaur";
                    break;
                case 2:
                    pokedexName = "Ivysaur";
                    break;
                case 3:
                    pokedexName = "Venisaur";
                    break;

            }
            label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);
            label2 = new JLabel("#"+pokedexNum);
            update = false;
        }while (update);
    }
    public synchronized void stop(){
        running = false;
    }
    public static void main(String[] args){
        new RunWindow().start();
    }

}

I did not look at your code in full detail, but from what I've seen, you seem to be creating JLabels a lot, and this can be the cause of the problem, because the labels you have initially created are the ones which you added to your Swing components, and which are being displayed inside the JFrame. 我没有详细介绍您的代码,但是从我看到的结果来看,您似乎在创建JLabels,这可能是造成此问题的原因,因为最初创建的标签就是您所创建的标签添加到您的Swing组件中,并显示在JFrame中。

You should reuse these labels and simply use their setText methods, to change the text they are displaying. 您应该重用这些标签,并简单地使用它们的setText方法来更改它们显示的文本。

You already have 2 Label variables and you only want to change the text, but you create new labels everytime: 您已经有2个Label变量,并且只想更改文本,但是每次都创建新标签:

label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);

instead you should just do: 相反,您应该这样做:

label.setText("....");

As you do some lines later anyways. 无论如何,稍后再做几行。 The problem is that you never add the newly created labels to the frame (you add them at the start, but when you override "label" and "label2" those are NEW labels and you'd need to also add them to your frame, resulting in 2 labels added everytime you click a button) 问题在于,您永远不会将新创建的标签添加到框架(在开始时添加它们,但是当您覆盖“ label”和“ label2”时,它们是NEW标签,并且您还需要将它们添加到框架中,导致您每次单击按钮时都会添加2个标签)

Just remove: 只需删除:

    label = new JLabel("Pokemon #"+pokedexNum+"-"+pokedexName);
    label2 = new JLabel("#"+pokedexNum);

I would also advise you to not use switch statements, you should rather use a string array and just call 我还建议您不要使用switch语句,而应该使用字符串数组,而只需调用

setText(pokemonNames[pokedexNum]);

This way you don't need hundreds of codelines for different pokedex cases. 这样,您不需要为不同的pokedex案例使用数百条代码行。

You can create a String[] easily like this way: 您可以像这样轻松地创建String []:

private static String[] pokeNames = new String[]{"","Bulbasaur","Ivysaur"};

I included an empty String at the start so that the index of the array is the same as the number in the pokedex (index starts at 1 so to say). 我在开始处包含一个空String,以便数组的索引与pokedex中的数字相同(可以说索引从1开始)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM