int variable = 100;
label = new JLabel("<html><font color=red>variable</font><html>");
How do I make this display "100" on screen and not "variable"
By building a String with it included:-
label = new JLabel("<html><font color=red>" + variable + "</font><html>");
This will output <html><font color=red>100</font><html> (well, in a label it will be html formatted)
The reason yours didn't work is because almost anything inside quotes is treated as a String so adding a variable in there is just the same as adding the name of the variable.
Additionally
This will also work for objects, not just primitive types like int by calling their toString() method and adding the output from that.
You can use String.format method:
label = new JLabel(String.format("<html><font color=red>%d</font><html>", variable));
Related
I have an issue where I have a button and when clicked I want to update a value but I cannot update it because the lambda expression needs to be final. In this example I want to add to the current number the change number and save it, so there is a new current and every time I click the button, it takes it and add change. How can I get around this issue?
This is the class, I want when one of the buttons with an arrow is selected to either increase or decrease the value by 'int change'. Now, when you click the button it takes the current value and increases it by 'change' but it does not update it? How can I fix this?
And, also how can I add padding or margins to an imageView as I tried everything but it does not work? Or can I add padding to a specific part of a borderPane?
Image with buttons
private Pane getControls(String paneName, String imageName, String symbol, double min, double max, double def, double change) {
BorderPane borderPane = new BorderPane();
ImageView image = getImage(imageName);
image.setFitHeight(80);
image.setFitWidth(60);
Label defLabel;
int current = (int) def;
if (min > 20) {
int def1 = (int) def;
defLabel = new Label(def1 + "");
} else {
defLabel = new Label(def + "");
}
defLabel.setStyle("-fx-text-fill: #ff0000;");
defLabel.setFont(new Font(50));
Label symbolLabel = new Label(symbol);
symbolLabel.setStyle("-fx-text-fill: #ffffff;");
symbolLabel.setFont(new Font(24));
symbolLabel.setPadding(new Insets(30, 40, 0, 0));
borderPane.setRight(symbolLabel);
borderPane.setCenter(defLabel);
borderPane.setLeft(image);
ImageView imageUp = getImage("up-icon.png");
ImageView imageDown = getImage("down-icon.png");
imageUp.setFitHeight(50);
imageUp.setFitWidth(50);
imageDown.setFitHeight(50);
imageDown.setFitWidth(50);
Button buttonUp = new Button();
Button buttonDown = new Button();
buttonUp.setOnAction((ActionEvent event) -> {
defLabel.setText((current + (int) change) + "");
current += (int) change;
System.out.println((current + (int) change) + " Up button pressed.");
});
buttonUp.setGraphic(imageUp);
buttonDown.setGraphic(imageDown);
buttonUp.setPrefSize(50, 50);
buttonDown.setPrefSize(50, 50);
buttonUp.setStyle("-fx-background-color: #6b4218;");
buttonDown.setStyle("-fx-background-color: #6b4218;");
HBox hbox = new HBox(12);
hbox.getChildren().add(buttonUp);
hbox.getChildren().add(buttonDown);
hbox.setAlignment(Pos.CENTER);
hbox.setPadding(new Insets(0, 0, 24, 0));
borderPane.setBottom(hbox);
borderPane.setPadding(new Insets(100));
BorderedTitledPane borderedTitledPane = new BorderedTitledPane(paneName, borderPane, 300, 200);
return borderedTitledPane;
}
I'll try to explain it to you using an example
If you don't understand my explaination, then read this tutorial (it is really well explained there): https://www.baeldung.com/java-lambda-effectively-final-local-variables
You can only access a variable from within a lambda if you could set that variable to final:
int i = 5; // You could set this variable to final and it would still compile
runSomething(() -> {
System.out.println(i); // Will compile since i could be set final
});
and that's what happens when you change i again:
int i = 5; // i was defined
// ...
i = 10; // assigned new value to i therefore i could no longer be final
runSomething(() -> {
System.out.println(i); // Will NOT compile since i could not be final anymore after it got changed
});
before Java 1.8+ we had to declare variables final to use them when implementing an interface (/ lambda (only exists since 1.8)) like this.
Therefore to access a variable from outside, (unless it is a field of a class) inside of a lamda you would need to be able to make it final. You can never change such a value (like you tried to) since you can't change final variables. Your 'current' variable is 'final' inside of your lambda, even though you never set it to final (this is because the method containing the variable could have already finished its execution before the lamda is being called from somewhere else. Since you can't alter the past the variable is unchangable inside the lamda body).
btw. your 'defLabel' is also 'final' inside of your lambda's body, since it never got changed (that's also why you can access it inside of the lamda)
I want this totalSalesAmountProperty to display the value but even after it is updated, and has an actual value, it still doesn't display. I know this has a value because I system.out the getter method and I get a value. Why would that be happening?
Label lblTotalSales = new Label(String.valueOf(newSale.getTotalSalesAmount1()));
You need to bind the label's text property to the totalSalesAmountProperty:
label.textProperty().bind(totalSalesAmountProperty);
Then the label text will automatically update any time the totalSalesAmountProperty is modified.
try this (what is the return type of getTotalSalesAmount1() ?? Here I consider it double)
Label lblTotalSales = new Label(" " + newSale.getTotalSalesAmount1());
By using
Label lblTotalSales = new Label(String.valueOf(newSale.getTotalSalesAmount1()));
you set the text to the String returned by String.valueOf(newSale.getTotalSalesAmount1()) just before calling the Label constructor, i.e. it yields the same result as
String s = String.valueOf(newSale.getTotalSalesAmount1());
Label lblTotalSales = new Label(s);
Strings are neither mutable nor observable in java and therefore the text is not automatically updated.
To fix this bind the textProperty of the Label to the String version of the DoubleProperty. This will add listeners to the property that will update the text of the Label every time the DoubleProperty changes.
DoubleProperty propertyToShow = ...
Label label = new Label();
label.textProperty().bind(propertyToShow.asString());
Is it possible to determine the path of a chosen image with a variable? like this:
private JLabel label = new JLabel();
int number = 1;
label.setIcon(new ImageIcon(getClass().getResource("/image" + number + ".png")));
In this case it does not work, but my idea might be clear. In this case I could just simply change the variable name in order to change the path of my image. Does anybody know how to do so?
I'm having more "I'm hopeless at programming" problems.
I have a piece of code which uses StringBuilder to display elements of an array in a text panel of a GUI when the program starts. Here's the StringBuilder code:
// memory tab
StringBuilder mList = new StringBuilder();
memLocList = new Memory[MEM_LOCATIONS];
mem = new Memory();
for (int i = 0; i < memLocList.length; i++) {
memLocList[i] = mem;
memLocList[i].setOpCode(00);
mList.append(String.format("%10s %04x %10s %6s", "Address: ", i,
"Value: ", memLocList[i].getOpCode()));
mList.append("\n");
}
JComponent memTab = makeTextPanel(mList.toString());
tabs.addTab("Memory", new JScrollPane(memTab));
}
protected JComponent makeTextPanel(String t) {
text = t;
JPanel panel = new JPanel(false);
JTextPane filler = new JTextPane();
filler.setFont(new Font("Courier", Font.PLAIN, 14));
filler.setText(text);
filler.setAlignmentX(LEFT_ALIGNMENT);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
The GUI also has a text entry panel where a String of hex values can be entered.
On clicking a button, the user is prompted for another value, which corresponds to the position in the array where the first hex value should be inserted.
Once these values have been entered, I'd like the display to be updated / refreshed to reflect this but am unsure of how to go about it.
I found this question here, which is similar but I'm not sure if implementing Observer/Observable pattern is the right way to proceed, and even if it is, how I'd go about it:
Best Way to Constantly Update GUI Elements
My initial approach was to add an "updateDisplay()" method, which I could call after processing the button click and re-call the makeTextPanel method:
public void updateDisplay() {
makeTextPanel(text);
}
I thought this might refresh it but it has no effect of the display.
Any help appreciated.
You hold your array in a model class, and you allow other classes to "listen" to this by giving this class a SwingPropertyChangeSupport object as well as an addPropertyChangeListener(...) method. Then give the array a setXXX(...) method, and in that method fire the SwingPropertyChangeSupport object after updating the array. There are examples of just this sort of thing on this site, some written by me.
For example: here, here, here, ...
By the way, I'm not surprised that your call to makeTextPanel(text) doesn't work. It creates a JPanel, but you don't appear to do anything with the JPanel that is returned from the method. But nor should you. I don't think that creating new JPanels is the solution you want, but rather updating the Strings displayed by a component of some sort such as a JList or JTextArea using the listener framework that I've described above.
If any of this is confusing, please ask for clarification.
if I have a class with a private Label = new Label(""); in it and in some method i write:
private void setText(String text)
{
this.label.setText(text);
System.out.println("label size = " + this.label.getSize(0,0));
}
it will always print "label size = Dimension(0,0)". why is this? how can I obtain the size occupied by the label after setting its text? I also tried other solutions (here and method getTextBounds() as suggested in here ) but i either obtain again Dimension(0,0) or a NullPointerException, respectively.
do you have any suggestion? thanx :)
this.label.getPreferredSize() is what you're looking for. It returns the space your label would like to occupy.
But at this point the label doesn't know yet what font to use, hence the NullPointerException. Once your figure tree has been set e.g. as the content of a FigureCanvas the font should be available. Alternatively, you could explicitly set a font before calling getPreferredSize().
To add a rounded rectangle around your label, like you requested in your comment, you could do the following:
RoundedRectangle rr = new RoundedRectangle();
rr.setBorder(new MarginBorder(4));
rr.setLayoutManager(new StackLayout());
rr.add(new Label("label text"));