I'm trying to make a small application where U input ID (with help of JButton -from 0 to 9 - ) and then pass the number that have been pressed to putText-Method and then display it in JTextField-the problem is that every time I press new number the one I pressed before disapears:s . Could anyone help me with that pls?
public class IdPanel extends JPanel {
private JTextField idField;
private JLabel idLabel;
public IdPanel() {
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(500, 70));
idField = new JTextField(20);
idField.setFont(new Font("Serif", Font.PLAIN, 20));
idLabel = new JLabel("Enter ID:");
idLabel.setFont(new Font("Serif", Font.PLAIN, 20));
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.insets = new Insets(9, 9, 9, 9);
gc.anchor = GridBagConstraints.CENTER;
add(idLabel, gc);
gc.gridx = 1;
gc.anchor = GridBagConstraints.CENTER;
add(idField, gc);
}
public void putText(String number) {
idField.setText(number);
}
}
try:
idField.setText(idField.getText()+number);
with help of JButton -from 0 to 9 -
Here is an example with 9 buttons:
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 );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), 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();
}
});
}
}