Vaadin TextField action at every key pressed - java

In Vaadin 7 there are no KeyListener in TextField only on EnterKey press.
I'm looking for an add-on which contains a SuperImmediateTextField but compatible with Vaadin 7.
I use Vaadin version 7.1.8

You can use TextChangeListener.
For example:
// Text field with maximum length
final TextField tf = new TextField("My Eventful Field");
tf.setValue("Initial content");
tf.setMaxLength(20);
// Counter for input length
final Label counter = new Label();
counter.setValue(tf.getValue().length() +
" of " + tf.getMaxLength());
// Display the current length interactively in the counter
tf.addTextChangeListener(new TextChangeListener() {
public void textChange(TextChangeEvent event) {
int len = event.getText().length();
counter.setValue(len + " of " + tf.getMaxLength());
}
});
// The lazy mode is actually the default
tf.setTextChangeEventMode(TextChangeEventMode.LAZY);

Related

JavaFX shows formatted text in different format that has passed to show

I'm trying to write a JavaFX app that shows in UI formatted text. The problem is showed text is a bit different from what i passed to show. Seems like less spaces, that it is supposed to be.
What can i do wrong?
#FXML
public ListView<HBox> buyList;
#FXML
public ListView<HBox> sellList;
. . .
private ObservableList<HBox> ordersToListItems(List<Order> orders)
{
ObservableList<HBox> items = FXCollections.observableArrayList();
orders.forEach(order -> {
final String assetVolume = order.getAssetVolume() + "$";
final String limits = order.getLimitFiatMin() + "-" + order.getLimitFiatMax();
Label priceLabel = new Label(String.format("%-7s", order.getPrice()));
Label limitsLabel = new Label(String.format("%-12s", limits));
Label volumeLabel = new Label(String.format("%-20s", assetVolume));
Label nameLabel = new Label(String.format("%-20s", order.getAdvertiserName()));
System.out.println(priceLabel.getText() + limitsLabel.getText() + volumeLabel.getText() + nameLabel.getText());
HBox hbox = new HBox(priceLabel, limitsLabel, volumeLabel, nameLabel);
items.add(hbox);
});
return items;
}
. . .
buyList.setItems(ordersToListItems(buyOrders));
sellList.setItems(ordersToListItems(sellOrders));
Output in console:
Ouput in JavaFX app:

How to hide or remove javafx tooltip when it is triggered manually?

I have been trying to figure out a way to hide this tooltip when it is triggered by a function and shown in the scene. This is my function.
private void ValidateRequired(TextField field){
Tooltip errorTip = null;
if(field.getText().equals("")){
field.getStyleClass().add("errorField");
errorTip = new Tooltip("This is required");
errorTip.getStyleClass().removeAll();
Scene scene = field.getScene();
scene.getStylesheets().add(this.getClass().getResource("../css/sale.css").toExternalForm());
errorTip.getStyleClass().add("errorTip");
Point2D p = field.localToScene(0.0, 0.0);
errorTip.show(field,p.getX()
+ field.getScene().getX() + field.getScene().getWindow().getX(), p.getY()
+ field.getScene().getY() + field.getScene().getWindow().getY()+field.getHeight()+2);
}
else{
errorTip.hide();
}
}
This function is called when Textfield lose focus. This function get called by the following listener.
currentField.focusedProperty().addListener((ov, oldV, newV) -> {
if (!newV) {
ValidateRequired(currentField);
}
else{
}
});
You are creating a new Tooltip every time the ValidateRequired method (BTW please use proper naming conventions) is called. So when the method is called with non-empty text, you are not hiding the same tooltip you previously showed (and so the previously-showed one remains shown).
Instead, create one tooltip and show/hide it:
private final Tooltip errorTip = new Tooltip();
// ...
private void ValidateRequired(TextField field){
if(field.getText().equals("")){
field.getStyleClass().add("errorField");
errorTip.setText("This is required");
errorTip.getStyleClass().removeAll();
Scene scene = field.getScene();
scene.getStylesheets().add(this.getClass().getResource("../css/sale.css").toExternalForm());
errorTip.getStyleClass().add("errorTip");
Point2D p = field.localToScene(0.0, 0.0);
errorTip.show(field,p.getX()
+ field.getScene().getX() + field.getScene().getWindow().getX(), p.getY()
+ field.getScene().getY() + field.getScene().getWindow().getY()+field.getHeight()+2);
}
else{
errorTip.setText("");
errorTip.hide();
}
}

Calling specific methods between classes

Help! I dont know much about java but im trying to create a small program where people can buy items and the stock should update depending on their purchase. I have 2 different classes but what im trying to do is that i want to get the amount of items the user purchases from one class and use that number to update the stock in another class - Here is the section of my code in which i am struggling with
Code for Purchasing Item
public class PurchaseItem extends JFrame implements ActionListener {
JTextField ItemNo = new JTextField(5); //Adds a text field named ItemNo
JTextField AmountNo = new JTextField(5); //Adds a text field named AmountNo
TextArea information = new TextArea(6, 40); //Adds a text area named Information
TextArea reciept = new TextArea (10,50); //Adds a text area named Reciept
JButton Check = new JButton("Check"); //Adds a button named Check
JButton Buy = new JButton("Buy"); //Adds a button named Buy
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //For output to display in decimal and pounds format
public PurchaseItem() { //PurchaseItem class
this.setLayout(new BorderLayout()); //Adds a new layout for PurchaseItem
JPanel top = new JPanel(); //JPanel is a a container for other components
top.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
JPanel bottom = new JPanel(); //JPanel is a a container for other components
bottom.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
bottom.add(Buy); //Insert the "Buy" JButton on the frame
this.add(bottom, BorderLayout.SOUTH); //Button goes at the bottom of the frame
setBounds(100, 100, 450, 250); //Sets the bounds of the frame
setTitle("Purchase Item"); //Sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //Default option to exit frame is through button and not X sign
top.add(new JLabel("Enter Item Key:")); //Add a new JLabel at the top of the frame
top.add(ItemNo); //Set the ItemNo Text Field at the top of the frame
top.add(new JLabel ("Enter Amount:")); //Add a new JLabel at the top of the frame
top.add(AmountNo); //Set the AmountNo Text Field at the top of the frame
top.add(Check); //Set the Check Button at the top of the frame
Buy.setText("Buy"); Buy.setVisible(true); //Makes the text of the Buy Button visible
Check.addActionListener(this); //Add an ActionListener to the Check Button
Buy.addActionListener(this); //Add an ActionListener to the Buy Button
add("North", top);
JPanel middle = new JPanel(); //JPanel is a a container for other components
middle.add(information); //Set the Information Text Area at the middle of the frame
add("Center", middle);
setResizable(false); //Makes the frame not resizeable
setVisible(true); //Makes the frame visible
}
#Override //Overrides the method of the PurchaseItem class to identify mistakes and typos
public void actionPerformed(ActionEvent e) { //actionPerformed class. This is called when the actionListener event happens
String ItemKey = ItemNo.getText(); //String for getting the user input from the ItemNo Text Field
String ItemAmount = AmountNo.getText(); //String for getting the user input from the AmountNo Text Field
String Name = StockData.getName(ItemKey); //String for getting the name of the item from StockData
int Amount = Integer.parseInt(ItemAmount); //Convert String ItemAmount into an Integer variable named Amount
int NewStock = StockData.getQuantity(ItemKey) - Amount; //Integer named NewStock. NewStock is the current stock(from StockData) minus the Amount
double Total = Amount * StockData.getPrice(ItemKey); //Double named Total. Total is the Amount multiplied by the price of the item(from StockData)
Calendar cal = Calendar.getInstance(); //Calendar named cal. getInstance is used to get the current time
SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yyyy"); //SimpleDateFormat named Date. It is used to display the date
SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss"); //SimpleDateFormat named Time. It is used to display the time
if (Name == null){ //If the Name is invalid and has no return value
information.setText("There is no such item"); //Display the message on the Information Text Area
}
else if (Amount > StockData.getQuantity(ItemKey)) { //Else if the Amount(User Input) is more than the quantity of the item(from StockData)
information.setText("Sorry there is not enough stock available"); //Display the message on the Information Text Area
}
else { //Otherwise
information.setText(Name + " selected: " + Amount); //Add the Name and the Amount of the item on the Information Text Area
information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey))); //On a new line add the individual price of the item on the Information Text Area in a pound format(£)
information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey)); //On a new line add the current quantity available according to StockData on the Information Text Area
information.append("\nNew Stock After Sale: " + NewStock); //On a new line add the NewStock on the Information Text Area
information.append("\n\nTotal: " + Amount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On two new lines add the Amount plus the item price(from StockData). This becomes the Total
information.append("\n= " + pounds.format(Total)); //On a new line display the Total in a pounds format(£) on the Information Text Area
}
if (e.getSource() == Buy) { //If the user clicks the Buy Button
int response = JOptionPane.showConfirmDialog(null, "Buy " + Amount + " Units" + " for " + pounds.format(Total) + "?"); //Show a confirm dialog asking the user to confirm the purchase with a Yes, No, or Cancel option
if (response == JOptionPane.YES_OPTION) { //If the user clicks Yes on the confirm dialog
JFrame frame2 = new JFrame(); //Add a new JFrame called frame2
TextArea Reciept = new TextArea ("Receipt For Your Purchase", 20,40); //Add the Receipt Text Area onto frame2 and show the message
Reciept.append("\n\nTime: " + Time.format(cal.getTime())); Reciept.append("\nDate: " + Date.format(cal.getTime())); //On seperate lines add the Time and the Date (from Calendar)
Reciept.append("\n\nYou Have Purchased The Following Item(s): "); //Display the message
Reciept.append("\n\n" + Name + "\n" + Amount + " Units" + "\n" + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On a line add the Name and Item Amount followed by the item price (from StockData) on a new line
Reciept.append("\n\n\n" + Amount + " Unit(s)" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each" + "\nTotal = " + pounds.format(Total)); //After 3 lines display the Item Amount and the item price on the same line. On a new line display the Total in a pounds format
Reciept.append("\n\n\nThank You For Your Purchase" + "\n\nGoodbye :)"); //Show a message on two seperate lines
frame2.pack(); frame2.setSize(375, 380); frame2.setLocation(250, 250); ;frame2.setTitle("Receipt"); //Sets the size, the location, and the title of frame2
frame2.setVisible(true); frame2.setResizable(false); //sets frame2 so that it is visible and not resizable
frame2.add(Reciept); //Display the Reciept Text Area on frame2
frame2.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
}else{ //Otherwise
if (response == JOptionPane.NO_OPTION){ //If the user clicks No or Cancel on the confirm dialog
//Do nothing
}
}
Code for Checking Stock
public class CheckStock extends JFrame implements ActionListener {
JTextField stockNo = new JTextField(7); //adds a text field for user input
JTextField AmountNo = new JTextField(5);
TextArea information = new TextArea(6, 40); //adds a text area for the output
JButton check = new JButton("Check Stock"); //adds a button with the text "Check Stock"
JButton Clear = new JButton();
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //for output to display in decimal and pound format
public CheckStock() { //"CheckStock" class
setLayout(new BorderLayout()); //adds a new frame for "CheckStock"
setBounds(100, 100, 450, 220); //sets the size and location of the frame
setTitle("Check Stock"); //sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //user has to click on "Exit" button instead of X sign
check.addActionListener(this); //adds an action listener for the "check" button so when clicked by user, "actionPerformed" class is called
JPanel top = new JPanel(); //JPanel is a a container for other components. It is used at the top of the frame
add("North", top);
top.add(new JLabel("Enter Item Key:")); //adds a label at the top of tne frame
top.add(stockNo); //adds the "stockNo" text field to the top of the frame
top.add(check); //adds the "check" button to the top of the frame
JPanel middle = new JPanel(); //JPanel is a a container for other components. It is used at the middle of the frame
add("Center", middle);
middle.add(information); //in the middle of the frame, add the "information" text area
setResizable(false); //frame is not resizable
setVisible(true); //frame is visible
}
public void actionPerformed(ActionEvent e) { //this code is fired once the user runs the ActionListener
String key = stockNo.getText(); //string named "key" for the stockNo
String name = StockData.getName(key); //string named "name" for the stockData
int Quantity = StockData.getQuantity(key);
int NewStock;
if (name == null) { //if there is no input in the text field
information.setText("Enter Item Key"); //display the message on the text area
}
else if (e.getSource() == check) {
StockData.getQuantity(key);
information.append( "" + StockData.getName(key));
information.append("\n New Stock: " + StockData.getQuantity(key)); //otherwise
information.setText(name); //display the name of the item
information.append("\nPrice: " + pounds.format(StockData.getPrice(key))); //display the price of the item using pound format
information.append("\nPrevious Stock: " + Quantity); //display the amount in stock for the item according to StockData
}
}
}
You didn't initialise the object Update: your line of code should be
PurchaseItem Update = new PurchaseItem();
(As another point I can't see any code that adds the JComponent you created (e.g. the buttons, the text fields,...) to the two frames of the respective classes or that displays the two frames; if it isn't included in your code be sure to add these pieces of code).
Finally, if you need a code that checks for changes in the value of Updated, here's the simplest (but not the only) technique you can use, creating a thread (see the Oracle documentation to know what are threads and how to use them):
int refreshTime = 1000; // Refresh time in milliseconds
boolean running = true; // Set it to false if you want to stop the thread
Runnable r = new Runnable({
#Override
public void run() {
while(running) {
Thread.sleep(refreshTime);
// Put here your code to update your frames or your variables
}
});

Swing check boxes

When the code below is run and the Beta check box is selected, then the Alpha check box, the text reads "Selected check boxes: Alpha, Beta" not "Selected check boxes: Beta, Alpha". Why do they appear in the opposite order to how they were selected?
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CBDemo implements ItemListener {
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(280, 120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected = new JLabel("");
jlabChanged = new JLabel("");
// Make check boxes.
jcbAlpha = new JCheckBox("Alpha");
jcbBeta = new JCheckBox("Beta");
jcbGamma = new JCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes.
public void itemStateChanged(ItemEvent ie) {
String str = "";
// Obtain a reference to the check box that
// caused the event.
JCheckBox cb = (JCheckBox) ie.getItem();
// Report what check box changed.
if(cb.isSelected())
jlabChanged.setText(cb.getText() + " was just selected.");
else
jlabChanged.setText(cb.getText() + " was just cleared.");
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
jlabSelected.setText("Selected check boxes: " + str);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CBDemo();
}
});
}
}
When any check box is clicked itemStateChanged() is called, the order of the string is driven by the order of your str+= statements in the code, not the temporal order of the clicks.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
To achieve the desired behaviour
store the selection events in some kind of ordered structure, e.g. a List that itemStateChanged updates and then displays.
Use different ItemListener instances for each checkbox, or use the ItemEvent parameter to determine where the event came from to update the structure accordingly
Try changing the 3 ifs to a single:
if (cb.isSelected()) {
selectionOrder.add(cb.getText()); // will return Alpha, Beta depending which is selected
}
jlabSelected.setText("Selected check boxes: " + selectionOrder);
Where selectionOrder is a field at the top of your CBDemo class
private List<String> selectionOrder = new ArrayList<String>();
This will obviously keep growing the list indefinitely, but fine for a demo.
Since Your order of Appending value to String is
Alpha --then-->Beta--then-->Gamma
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
So No Matter in which order you select the checkbox .
To achieve your desired output Use
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
jcbAlpha.setSelected(false);// So when Next Time you click on other checkbox this condtion does not append result to Str
}
if(jcbBeta.isSelected()) {
str += "Beta ";
jcbBeta.setSelected(false);
}
if(jcbGamma.isSelected()) {
str += "Gamma";
jcbGamma.setSelected(false);
}

SWT StyledText getCaretOffset giving wrong line number

I'm trying to make the bullet of active line have a highlighted background. I'm using
int activeLine = styledText.getLineAtOffset(styledText.getCaretOffset());
To get the like that is currently active. This seems to work except when I hit enter and get a new line.
getCaretOffset returns 35 and getCharCount returns 36.
However, if I click on the last line (for now I call redraw() on clicks) the line highlights correctly and getCaretOffset returns 36.
Here is the relevant code
public void lineGetStyle(LineStyleEvent event) {
// Set the line number
int activeLine = styledText.getLineAtOffset(styledText.getCaretOffset());
System.out.println("Offset " + styledText.getCaretOffset() + " max " + styledText.getCharCount());
int currentLine = styledText.getLineAtOffset(event.lineOffset);
event.bulletIndex = currentLine;
// Set the style, 12 pixles wide for each digit
StyleRange style = new StyleRange();
style.metrics = new GlyphMetrics(0, 0, 36);
if (activeLine == currentLine) {
style.background = highlightedLine;
if (curActiveLine != activeLine){
System.out.println("ActiveLine " + activeLine + " old " + curActiveLine);
int redrawLine = curActiveLine;
curActiveLine = activeLine;
styledText.redraw(0, styledText.getLinePixel(redrawLine), 36, styledText.getLineHeight(),true);
}
}
style.foreground = mainBackground;
// Create and set the bullet
event.bullet = new Bullet(ST.BULLET_NUMBER, style);
event.styles = matchKeywords(event);
}
I just realized that you can set a CaretListener to get notifications for each move of the caret. By issuing the redraws from that it works great now.

Categories

Resources