有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以让JLabel根据变量值更改其文本?

我创建了一个JLabel,如果变量计数==-1,
如果变量计数=0,则为“文本B”;如果变量计数=1,则为“文本C”

我使用Swing创建了我的界面,您可以在下面看到

TempConverter

enter image description here

红色矩形显示JLabel应该在哪里

我尝试创建3个JLabel,并在变量计数值条件适用时更改setVisible(布尔值)。这不起作用,因为我遇到以下错误:

线程“main”java中出现异常。lang.NullPointerException 在坦佩鲁伊。温度转换器。main(TempConverter.java:354) C:\Users\x\AppData\Local\NetBeans\Cache\8.1\executor snippets\run。xml:53:Java返回:1

而且JLabel不能放在GUI中的同一位置(不可能重叠)

我试过使用jLabel。setText()以在变量条件应用时更改JLabel中显示的文本。我得到了一个与上面类似的错误(如果不是相同的话)

我已经阅读了其他一些帖子并进行了进一步的研究,发现有些人建议设置ActionListeners,但我不确定它们是否能与简单的变量一起工作,而不是GUI中的组件

我的代码如下:

package tempconverterUI;

import javax.swing.JOptionPane;
import messageBoxes.UserData;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.WString;

public class TempConverter extends javax.swing.JFrame {

public interface someLib extends Library
{
      public int engStart(); 
      public int endStop();
      public int engCount();
      public WString engGetLastError();
      public int engSetAttribute(WString aszAttributeID, WString aszValue);

}

/**
 * Creates new form TempConverter
 */
public TempConverter() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

布局是在这里创建的,后面是温度转换方法和无关组件的功能(我认为这与本例无关)

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {

/**This is where the Login form gets created*/              
    UserData.popUp();

/**After this the Library functions are called, which will return the variable count value*/    
    someLib lib = (someLib) Native.loadLibrary("someLib", someLib.class);

    int startResult = lib.engStart(); 
    System.out.println(startResult);
    if (startResult < 0)
    {
        System.out.println(lib.engGetLastError());
    }

    System.out.println(UserData.getAcInput());
    int setAtResult = lib.engSetAttribute(new WString("CODE"), UserData.getAcInput());
    System.out.println(setAtResult);
    if (setAtResult < 0)
    {
        System.out.println(lib.engGetLastError());
    }

接下来是一段代码,我应该从中控制要显示的JLabel文本

    int count = lib.engCount();
    System.out.println(count);
    if (count == -1)
    {
        System.out.println(lib.engGetLastError());

    }
    else if (count == 0)
    {

    }
    else
    {

    }

    new TempConverter().setVisible(true);  
}

// Variables declaration - do not modify                     
private javax.swing.JPanel bottomPanel;
private javax.swing.JButton convertButton;
private static javax.swing.JButton button;
private javax.swing.JTextField from;
private javax.swing.JComboBox<String> fromCombo;
private javax.swing.JLabel fromLabel;
private javax.swing.JLabel title;
private javax.swing.JTextField to;
private javax.swing.JComboBox<String> toCombo;
private javax.swing.JLabel toLabel;
private javax.swing.JPanel topPanel;
// End of variables declaration                   

}

在此方面的任何帮助都将不胜感激。如果您还可以包含一个简单的代码示例,这将是非常棒的,因为我对Java(以及编程)是新手


共 (1) 个答案

  1. # 1 楼答案

    问题:

    1. 不要将JLabel设置为可见,而是将其最初添加到GUI中,默认情况下保持可见,只需通过setText(...)设置其文本即可
    2. 为包含JLabel公共方法的类提供允许外部类设置标签文本的能力。类似于public void setLabelText(String text),在JLabel上的方法调用setText(text)
    3. 像调试任何其他NPE一样调试NullPointerException查看stacktrace,找到抛出它的行,然后回顾代码,查看该行上的键变量为何为null
    4. 何时以及如何更改JLabel将取决于您想要收听的事件。如果是用户输入,那么您将希望响应该输入,无论是添加到JButton或JTextField的ActionListener,还是添加到JRadioButton的itemListener
    5. 如果您想监听变量状态的变化,不管变量如何变化,那么使用PropertyChangeSupport和PropertyChangeListener将其设置为“绑定属性”(tutorial

    关于后者的一个例子:

    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    
    import javax.swing.*;
    import javax.swing.event.SwingPropertyChangeSupport;
    
    @SuppressWarnings("serial")
    public class ShowCount extends JPanel {
        private static final int TIMER_DELAY = 1000;
        private JLabel countLabel = new JLabel("                 ");
        private CountModel model = new CountModel();
    
        public ShowCount() {
            model.addPropertyChangeListener(CountModel.COUNT, new ModelListener(this));
    
            setPreferredSize(new Dimension(250, 50));
            add(new JLabel("Count:"));
            add(countLabel);
    
            Timer timer = new Timer(TIMER_DELAY, new TimerListener(model));
            timer.start();
        }
    
        public void setCountLabelText(String text) {
            countLabel.setText(text);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    
        private static void createAndShowGui() {
            ShowCount mainPanel = new ShowCount();
            JFrame frame = new JFrame("ShowCount");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    }
    

    class CountModel {
        public static final String COUNT = "count"; // for count "property"
    
        // support object that will notify listeners of change
        private SwingPropertyChangeSupport support = new SwingPropertyChangeSupport(this);
        private int count = 0;
    
        public int getCount() {
            return count;
        }
    
        public void setCount(int count) {
            int oldValue = this.count;
            int newValue = count;
            this.count = count;
    
            // notify listeners that count has changed
            support.firePropertyChange(COUNT, oldValue, newValue);
        }
    
        // two methods to allow listeners to register with support object
        public void addPropertyChangeListener(PropertyChangeListener listener) {
            support.addPropertyChangeListener(listener);
        }
    
        public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
            support.addPropertyChangeListener(propertyName, listener);
        }
    
    }
    

    class ModelListener implements PropertyChangeListener {
        private ShowCount showCount;
    
        public ModelListener(ShowCount showCount) {
            super();
            this.showCount = showCount;
        }
    
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            int newValue = (int) evt.getNewValue();
            showCount.setCountLabelText(String.format("%03d", newValue));
        }
    }
    

    class TimerListener implements ActionListener {
        private CountModel model;
    
        public TimerListener(CountModel model) {
            super();
            this.model = model;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            int oldCount = model.getCount();
            int newCount = oldCount + 1;
            model.setCount(newCount);
        }
    }