【发布时间】:2015-07-20 05:06:18
【问题描述】:
所以目前我正在自学 Java,我想使用 Swing 编写一个带有小按钮和文本字段的简单计算器。虽然我设法实际创建了一个填充了文本变量的文本字段,但我无法通过按钮更改字段中的文本。我不断收到关于内部类无法更改外部变量的错误。我实现目标的最佳方式是什么?为什么?
提前致谢,代码如下:
查看我的第一个按钮 (addButton) 的操作在哪里,这是我测试更改文本字段能力的地方。
/**
* Created by Ray on 7/19/2015.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class main extends JFrame {
double x = 0;
double y = 0;
double z = 0;
public main() {
initUI();
}
private void initUI() {
setLayout(null);
JPanel text = new JPanel();
text.setLayout(new BorderLayout());
text.setBounds(100, 10, 200, 25);
JScrollPane pane = new JScrollPane();
JTextArea area = new JTextArea();
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setBounds(100, 10, 200, 25);
pane.getViewport().add(area);
text.add(pane);
String contents = "Test";
area.setText(contents);
JButton addButton = new JButton("Add");
addButton.setToolTipText("Addition operation.");
addButton.setBounds(10, 10, 80, 25);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
contents = "Pressed";
}
});
JButton subButton = new JButton("Sub");
subButton.setToolTipText("Subtraction operation.");
subButton.setBounds(10, 40, 80, 25);
subButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JButton mulButton = new JButton("Mul");
mulButton.setToolTipText("Multiplication operation.");
mulButton.setBounds(10, 70, 80, 25);
mulButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JButton divButton = new JButton("Div");
divButton.setToolTipText("Division operation.");
divButton.setBounds(10, 100, 80, 25);
divButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
add(text);
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
setTitle("Simple example");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main ex = new main();
ex.setVisible(true);
}
});
}
}
【问题讨论】:
-
只是变量
contents是initUI方法的局部变量,所以你只需要在使用前声明为final即可。\ -
避免使用
null布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正 -
您是否尝试过使用
area.append("some new text");? -
@nIcEcOw
final将意味着 OP 无法为变量分配新值... -
contents = "Pressed";->area.setText("Pressed");
标签: java swing class variables calculator