是否可以让JLabel根据变量值更改其Text?

时间:2016-07-21 14:43:03

标签: java swing

我创建了一个JLabel,它应该显示" TextA"如果变量count == -1,
"文字B"如果变量count == 0和" TextC"如果变量count == 1。

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

TempConverter

enter image description here

红色矩形表示JLabel的位置。

我尝试创建3个JLabel并在应用变量计数值条件时更改setVisible(布尔值)。这没有用,因为我收到了以下错误:

线程中的异常" main"显示java.lang.NullPointerException     在tempconverterUI.TempConverter.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 Text显示的代码片段

    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 个答案:

答案 0 :(得分:2)

的问题:

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

    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);
        }
    }