【问题标题】:How to add strings to textPane instead of setting them?如何将字符串添加到 textPane 而不是设置它们?
【发布时间】:2013-12-30 04:36:57
【问题描述】:
我正在尝试制作一个计算器。 http://i.imgur.com/exQLj4m.png
用户将在一行中按下他们想要计算的数字,然后是操作员,例如
'1+1-2+5'
然后Java会将其转换为它可以理解并得到答案的东西。
但是,当我尝试在将显示答案的 TextPane 上使用 setText() 时,它不会在其中放入更多数字,只会更改为指定的数字。当我按 1 时,它显示 1,但当我按 2 时,它不显示 12,它显示 2。有类似 addText() 方法吗?
这是我的数字 1 按钮的代码。
JButton btnNewButton = new JButton("1");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
answer.setText("1");
}});
【问题讨论】:
标签:
java
user-interface
jframe
int
calculator
【解决方案1】:
这是我的数字 1 按钮的代码。
不要为每个按钮创建自定义 ActionListener。使用通用侦听器。比如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
KeyStroke pressed = KeyStroke.getKeyStroke(text);
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(pressed, text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
// UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
上面的代码还展示了如何将文本附加到文本组件。
【解决方案2】:
使用
answer.setText(answer.getText()+"1");
而不是
answer.setText("1");
这肯定会解决你的问题。