gpt4 book ai didi

java - Eclipse Java 8 错误 : Label cannot be resolved

转载 作者:行者123 更新时间:2023-12-02 01:58:05 25 4
gpt4 key购买 nike

我正在尝试编写一个“英寸到厘米计算器”。我的 umrechnen() 方法有问题。无法解析标签 lblCenti。我的代码等于解决方案代码。我很感激我得到的每一个答案或提示。

我不知道应该在描述中添加什么,但 StackOverflow 迫使我写更多内容,所以我写了这篇文章。

package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.text.DecimalFormat;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ZollZentimeter extends JFrame {

private JPanel contentPane;
private JTextField tfInch;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZollZentimeter frame = new ZollZentimeter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public ZollZentimeter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 359, 157);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnCalculate = new JButton("Umrechnen");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
umrechnen();
}
});
btnCalculate.setBounds(12, 77, 116, 25);
contentPane.add(btnCalculate);

JButton btnEnde = new JButton("Ende");
btnEnde.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnEnde.setBounds(214, 77, 116, 25);
contentPane.add(btnEnde);

JLabel lblZoll = new JLabel("Zoll");
lblZoll.setBounds(12, 13, 56, 16);
contentPane.add(lblZoll);

tfInch = new JTextField();
tfInch.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){
umrechnen();
}
}
});

JLabel lblCenti = new JLabel("");
lblCenti.setBounds(214, 42, 116, 22);
contentPane.add(lblCenti);
tfInch.setBounds(12, 42, 116, 22);
contentPane.add(tfInch);
tfInch.setColumns(10);

}

private void umrechnen(){
DecimalFormat f=new DecimalFormat("#0.00");
double z, cm;
z=Double.parseDouble(tfInch.getText());
cm=z*2.54;
lblCenti.setText(f.format(cm+" cm"));
tfInch.requestFocus();
tfInch.selectAll();
}
}

最佳答案

JLabel lblCenti = new JLabel("");

“lblCenti” 被定义为本地 变量,因此只能在定义它的方法/构造函数中访问它。

如果您想在另一种方法中访问标签,则需要将其定义为实例变量,就像使用“tfInch”变量一样。

关于java - Eclipse Java 8 错误 : Label cannot be resolved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045023/

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