gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:28:07 26 4
gpt4 key购买 nike

我创建了一个 JLabel,如果变量 count == -1,则应显示“TextA”,
如果变量计数 == 0,则为“Text B”;如果变量计数 == 1,则为“TextC”。

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

TempConverter

enter image description here

红色矩形显示 JLabel 应该在的位置。

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

线程“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

并且 JLabels 无法放置在 GUI 中的同一位置(不可能重叠)。

每当应用变量条件时,我都尝试使用 jLabel.setText() 更改 JLabel 中显示的文本。我遇到了与上面类似的错误(如果不相同)。

我阅读了其他一些帖子并进行了进一步研究,发现有些人建议设置 ActionListener,但我不确定这些是否适用于简单变量,而不是 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. 不要将 JLabel 设置为可见,而是首先将其添加到 GUI,默认情况下使其可见,然后只需通过 setText(...) 设置其文本。
  2. 为持有 JLabel 公共(public)方法的类提供允许外部类设置标签文本的能力。类似于 public void setLabelText(String text),并在方法中调用 JLabel 上的 setText(text)
  3. 像调试任何其他 NPE 一样调试 NullPointerException - 查看堆栈跟踪,找到引发它的行,然后回顾代码以了解为什么该行上的关键变量为 null。
  4. 何时以及如何更改 JLabel 将取决于您想要监听的事件。如果是用户输入,那么您将需要响应该输入,无论是添加到 JButton 或 JTextField 的 ActionListener,还是添加到 JRadioButton 的 itemListener。
  5. 如果您想监听变量状态的变化,无论变量如何更改,请使用 PropertyChangeSupport 和 PropertyChangeListener 将其设为“绑定(bind)属性”( 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);
}
}

关于java - JLabel 是否可以根据变量值更改其文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com