displaying jtextfield data in jlablel on keyPressed event - java

i need to erase data in jlabel via jtextfield whenever i pressed backspace or delete from current position.I figure out how to add data in jlable(numeric data) but don't know how to erase it or edit it.
//this is my code
String str = "";
private void jTextField1KeyPressed (java.awt.event.KeyEvent evt) {
char ch=evt.getKeyChar();
if(Character.isDigit(ch)
str += ch;
jLabel2.setText(str);
}
}

Use a DocumentListener instead of a KeyListener, it will be able to detect when the user pastes text into the field and/or is changed programmatically
When the Document is updated, get the text from the field and set the labels text. There is little benefit in trying to update another String when the information is already available in the field/Document. If you "really" have to, use a StringBuilder instead, it's more efficient and is mutable
For example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel mirrorLabel;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField field = new JTextField(10);
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
protected void updateLabel(Document document) {
try {
mirrorLabel.setText(document.getText(0, document.getLength()));
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
add(field, gbc);
mirrorLabel = new JLabel(" ");
add(mirrorLabel, gbc);
}
}
}

Related

Simple Java: How to make string replace and wait then replace again?

I am making something and there will be a "Calculating" page on Java on an Applet! so what i want it to do is first drawstring and display "Calculating." then after a second it replaces that string and says "Calculating.." then again replace that string with "Calculating..." and loop that about 5 times. Is there any simple way of doing this??
I want it to display it on the applet!
You either want to use a Swing Timer or SwingWorker. See How to use Swing Timers and Worker Threads and SwingWorker for more details.
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private JLabel label;
private static final String DOTS = "...";
private static final String TEXT = "Calculating";
private int counter;
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel(getText());
add(label);
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
if (counter > 3) {
counter = 0;
}
label.setText(getText());
}
});
timer.start();
}
protected String getText() {
String sufix = DOTS.substring(0, counter);
sufix = String.format("%-3s", sufix);
return TEXT + sufix;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Adding this to an applet is about as easy as adding to a JFrame

How to make a border around Jbutton thicker?

I have the following JButton on the GUI interface I'm building.
I want to make the border around the button more thicker so it will stand out from the background. Is it possible to do this in Java?
You could simply use a LineBorder
JButton btn = ...;
btn.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
Take a look at How to Use Borders for more details and ideas
Updating the border state based on the model state
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final Border NORMAL_BORDER = BorderFactory.createLineBorder(Color.BLACK, 4);
protected static final Border ROLLOVER_BORDER = BorderFactory.createLineBorder(Color.RED, 4);
public TestPane() {
JButton btn = new JButton("Click me!");
btn.setContentAreaFilled(false);
btn.setBorder(NORMAL_BORDER);
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (btn.getModel().isRollover()) {
btn.setBorder(ROLLOVER_BORDER);
} else {
btn.setBorder(NORMAL_BORDER);
}
}
});
setLayout(new GridBagLayout());
add(btn);
}
}
}
Create a Border first -
Border border = new LineBorder(Color.WHITE, 13);
Then create a JButton and set the Border -
JButton button = new JButton("Button Name");
button.setBorder(border);
Hope it will Help.
Thanks a lot.

Java - is it possible to apply setEditable(boolean b) to JSlider/

in my program I need to disable my JSlider under certain circumstances, but do not know how. I tried setFocusable(false) but that did not work... Thanks in advance!
You change/restrict user interactions with the JSlider through the use of the enabled property.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SliderTest {
public static void main(String[] args) {
new SliderTest();
}
public SliderTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JSlider slider = new JSlider();
final JCheckBox checkBox = new JCheckBox();
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
slider.setEnabled(checkBox.isSelected());
}
});
checkBox.setSelected(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(slider, gbc);
frame.add(checkBox, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try the setEnabled(boolean) method. All JComponents inherit it by default.

make enter key act like a tab key for jtextfield,jcombobox,jspinner in java

I want enter key to behave like tab key in my swing application.And this class is working fine for JTextFields.How can i do the same for JComboBox and Jspinner or for the other controls on the frame?kindly help.
class MyTextField extends JTextField {
MyTextField(int len) {
super(len);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
transferFocus();
}
});
}
}
Enter has special meaning for most components in Swing, for example JTextField will trigger actionPerformed on registered ActionListeners when Enter is pressed. Modifying this behaviour may have unexpected results for your application and may confuse many users...
Having said that, the best way to change the focus traversal keys is to provide a Set of KeyStrokes to the KeyboardFocusManager. This will (mostly) make the key's global.
Some component's supply there own focus traversal keys however, like JTextArea and JTable
Take a look at How to use Focus Subsystem for more details
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFocusTraversal {
public static void main(String[] args) {
new TestFocusTraversal();
}
public TestFocusTraversal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
for (int index = 0; index < 10; index++) {
JTextField tf = new JTextField(5);
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...");
}
});
add(tf);
}
add(new JScrollPane(new JTextArea(10, 10)));
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
KeyStroke ctrlTab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.CTRL_DOWN_MASK);
Set<KeyStroke> keys = new HashSet<>();
keys.add(enter);
keys.add(tab);
keys.add(ctrlTab);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, keys);
}
}
}

How To Take The Value From A JTextField And Move It Into A Int Variable

I have been trying to create a JFrame program that takes two numbers and an
operation(inside jcombobox) to calculate the answer. I need to take the user input for number 1 and 2 and assign the value to an int that can be used in the calculation of the answer. num1 is the int variable and num1field is the name of the textfield.
num1field.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
num1 = Integer.parseInt(num1field.getText());
num1field.setText(num1);
}
}
);
And yes the num1 int has already been declared at the top of the class. I am getting an error where it says setText.
Thanks for all the help :)
There is no method JTextField#setText(int), you can only supply a String
num1field.setText(String.valueOf(num1));
Should work
You may like to take a look at How to use Formatted Text Fields and How to use Spinners which may provide you with better functionality for what you are trying to achieve
Updated with example of idea how to calculate resulting value
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class QuickCalc {
public static void main(String[] args) {
new QuickCalc();
}
public QuickCalc() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField numField1;
private JTextField numField2;
private JComboBox cbModifier;
private JLabel lblResult;
private JButton equals;
public TestPane() {
numField1 = new JTextField(4);
numField2 = new JTextField(4);
cbModifier = new JComboBox();
equals = new JButton("=");
lblResult = new JLabel("?");
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("+");
model.addElement("-");
model.addElement("/");
model.addElement("x");
cbModifier.setModel(model);
setLayout(new GridBagLayout());
add(numField1);
add(cbModifier);
add(numField2);
add(equals);
add(lblResult);
equals.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(numField1.getText());
int num2 = Integer.parseInt(numField2.getText());
// Make your calculations here...
// Update the lblResult with the resulting value...
lblResult.setText(String.valueOf(42));
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
lblResult.setText("Bad numbers");
}
}
});
}
}
}

Categories