Togglegroup for buttons in javafx - java

I have the following code which is a grouping of buttons in javafx:
ToggleGroup groupLevelQ = new ToggleGroup();
class MyLevelButton extends ToggleButton {
public MyLevelButton(String name) {
super(name);
setPrefWidth(50.0);
setPrefHeight(50.0);
setStyle("-fx-font: 20 cornerstone; -fx-base: #17499F;");
setToggleGroup(groupLevelQ);
}
}
oneLevelButton = new MyLevelButton("1");
twoLevelButton = new MyLevelButton("2");
threeLevelButton = new MyLevelButton("3");
fourLevelButton = new MyLevelButton("4");
fiveLevelButton = new MyLevelButton("5");
sixLevelButton = new MyLevelButton("6");
sevenLevelButton = new MyLevelButton("7");
eightLevelButton = new MyLevelButton("8");
nineLevelButton = new MyLevelButton("9");
oneLevelButton.setUserData("1");
twoLevelButton.setUserData("2");
threeLevelButton.setUserData("3");
fourLevelButton.setUserData("4");
fiveLevelButton.setUserData("5");
sixLevelButton.setUserData("6");
sevenLevelButton.setUserData("7");
eightLevelButton.setUserData("8");
nineLevelButton.setUserData("9");
groupLevelQ.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
if (new_toggle != null) {
textLevelQ = (String) groupLevelQ.getSelectedToggle().getUserData();
}
}
});
addQButtonPane.add(oneLevelButton, 1, 9);
addQButtonPane.add(twoLevelButton, 2, 9);
addQButtonPane.add(threeLevelButton, 3, 9);
addQButtonPane.add(fourLevelButton, 4, 9);
addQButtonPane.add(fiveLevelButton, 5, 9);
addQButtonPane.add(sixLevelButton, 6, 9);
addQButtonPane.add(sevenLevelButton, 7, 9);
addQButtonPane.add(eightLevelButton, 8, 9);
addQButtonPane.add(nineLevelButton, 9, 9);
In fact I am creating buttons and I add them in a GridPane. I am trying to figure out how can I define the distance between the buttons. Basically as they are right now they have a default distance them and I want to change that.
EDIT:
addQButtonPane = new GridPane();
addQButtonPane.setHgap(10);
addQButtonPane.setVgap(10);
addQButtonPane.setPadding(new Insets(0, 50, 0, 50));
addQButtonPane.setStyle("-fx-background-color: #95CBE5;");
This is the way that my gridpane is formatted. But still I want to change this formation just for the specific mentioned buttons.
EDIT2:

Maybe the kind of layout you're trying to achieve could be better achieved by placing HBoxes containing the options and Text elements inside a VBox.
But if you're looking for a way to "take the buttons out of the usual layout", you could simply place them inside a HBox use a columnSpan that covers all remaining columns:
double buttonDistance = ...
int gridPaneColumnCount = ...
HBox buttonBox = new HBox(buttonDistance,
oneLevelButton,
twoLevelButton,
threeLevelButton,
fourLevelButton,
fiveLevelButton,
sixLevelButton,
sevenLevelButton,
eightLevelButton,
nineLevelButton);
addQButtonPane.add(buttonBox, 1, 9, gridPaneColumnCount-1, 1);

Related

How do I add a second line with a SECOND AXIS to an XDDFChart in POI 4.0.1?

I am unable to add a line on a second axis (right axis) on an existing chart. Is there a way to do this with the new implementation of Charts in POI 4.0.0/1?
Desired output will look like this (A simple excel chart with 2 axes):
. The associated data to that chart as an example:
Series 1/Axis1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Series 2/Axis2 = [200,300,400,500,600,700,800,900,1000]
Here is the code that I am trying so far in Java, it is mostly replicated from the LineChart.java example
//Initial code instantiates a document
XWPFDocument doc = new XWPFDocument();
...
// Generate Chart
// This was taken from the example https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java
XWPFChart prChart = doc.createChart();
//Values 1 on the Left Axis
//Values 2 on the Right Axis
String[] categories = dates.toArray(new String[dates.size()]);
BigDecimal[] values1 = prices1.toArray(new BigDecimal[prices1.size()]);
BigDecimal[] values2 = prices2.toArray(new BigDecimal[prices2.size()]);
XDDFChartAxis bottomAxis = prChart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setMajorTickMark(AxisTickMark.NONE);
XDDFValueAxis leftAxis = prChart.createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
leftAxis.setMajorTickMark(AxisTickMark.OUT);
/*
* Is this made correctly?
*/
XDDFValueAxis rightAxis = prChart.createValueAxis(AxisPosition.RIGHT);
rightAxis.setCrosses(AxisCrosses.MAX);
rightAxis.setMajorTickMark(AxisTickMark.IN);
final int numOfPoints = categories.length;
final String categoryDataRange = prChart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
final String valuesDataRange = prChart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
final String valuesDataRange2 = prChart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, 1);
final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, 2);
XDDFLineChartData line = (XDDFLineChartData) prChart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) line.addSeries(categoriesData, valuesData);
series1.setTitle("Price", null);
series1.setSmooth(true);
series1.setMarkerStyle(MarkerStyle.NONE);
solidLineSeries(series1, PresetColor.BLUE_VIOLET);
// Am I adding the rightAxis correctly here?
XDDFLineChartData line2 = (XDDFLineChartData) prChart.createData(ChartTypes.LINE, bottomAxis, rightAxis);
XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) line2.addSeries(categoriesData, valuesData2);
series2.setTitle("Index", null);
series2.setSmooth(true);
series2.setMarkerStyle(MarkerStyle.NONE);
solidLineSeries(series2, PresetColor.BLACK);
prChart.plot(line);
prChart.plot(line2); /// <- Does this add to the same plot correctly?
prChart.displayBlanksAs(DisplayBlanks.GAP);
Running this code doesn't produce any compile errors. But I do get errors when opening the document "Problem with its' contents."
I suppose I am not adding the 2nd line and 2nd axes correctly.
Is there a way to accomplish this?
Update w. Solution
Axel's solution below works perfectly. The additional info to know is exactly what was the issue.
I would also like to recognize the order in which you add to the plot, this will hopefully help others
Create first set of axis
Create first Line
Plot first Line
Create new Axis
Create 2nd line
Plot 2nd line
Update the axis ids!
When it comes to multiple different value axes in one chart, this is not fully implemented in XDDF until now. So we need correcting something using the low level ooxml-schemas-1.4 classes.
Needed knowledge:
In principle the series which shall be shown on second value axis are in a separate chart in the same plot area. So the series which shall be shown on second value axis needs it's own bottom axis too. But this bottom axis must be invisible.
Both the axes, the second bottom and the new right axis, must cross each other properly. This crossing apache poi does not properly until now. So we must correct here.
Because while adding to the chart, the apache poi code which adds the second line chart does not knows something about the already present line chart, it's IDs starts with 0 again. But this is wrong for an combined chart. So we need correct the id and order. It must not start with 0 again because there is a line series already in same plot area.
Complete example to be reproducible for others too:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Units;
import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
public class CreateWordXDDFChart {
public static void main(String[] args) throws Exception {
try (XWPFDocument document = new XWPFDocument()) {
// create the data
String[] categories = new String[]{"1","2","3","4","5","6","7","8","9"};
Double[] values1 = new Double[]{1d,2d,3d,4d,5d,6d,7d,8d,9d};
Double[] values2 = new Double[]{200d,300d,400d,500d,600d,700d,800d,900d,1000d};
// create the chart
XWPFChart chart = document.createChart(15*Units.EMU_PER_CENTIMETER, 10*Units.EMU_PER_CENTIMETER);
// create data sources
int numOfPoints = categories.length;
String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
String valuesDataRange1 = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
XDDFDataSource<String> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
XDDFNumericalDataSource<Double> valuesData1 = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange1, 1);
XDDFNumericalDataSource<Double> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, 2);
// first line chart
XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
XDDFChartData data = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
XDDFChartData.Series series = data.addSeries(categoriesData, valuesData1);
chart.plot(data);
solidLineSeries(data, 0, PresetColor.BLUE);
// second line chart
// bottom axis must be there but must not be visible
bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setVisible(false);
XDDFValueAxis rightAxis = chart.createValueAxis(AxisPosition.RIGHT);
rightAxis.setCrosses(AxisCrosses.MAX);
// set correct cross axis
bottomAxis.crossAxis(rightAxis);
rightAxis.crossAxis(bottomAxis);
data = chart.createData(ChartTypes.LINE, bottomAxis, rightAxis);
series = data.addSeries(categoriesData, valuesData2);
chart.plot(data);
// correct the id and order, must not be 0 again because there is one line series already
chart.getCTChart().getPlotArea().getLineChartArray(1).getSerArray(0).getIdx().setVal(1);
chart.getCTChart().getPlotArea().getLineChartArray(1).getSerArray(0).getOrder().setVal(1);
solidLineSeries(data, 0, PresetColor.RED);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("CreateWordXDDFChart.docx")) {
document.write(fileOut);
}
}
}
private static void solidLineSeries(XDDFChartData data, int index, PresetColor color) {
XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
XDDFLineProperties line = new XDDFLineProperties();
line.setFillProperties(fill);
XDDFChartData.Series series = data.getSeries().get(index);
XDDFShapeProperties properties = series.getShapeProperties();
if (properties == null) {
properties = new XDDFShapeProperties();
}
properties.setLineProperties(line);
series.setShapeProperties(properties);
}
}

How to set a fixed height for a JavaFX text field regardless of its contents?

I'm making a notepad application using JavaFX which includes a font selector window. The font selector includes a textfield within a gridpane layout which functions as a sample of what the selected font options will look like.
Font selector:
However, if the font chosen is taller than the text field, the field stretches to fit the text, distorting the window.
Distorted font selector:
I want the sample textfield to remain the same size even if the text contained is taller than the field, like the font selector shown below:
I've tried using the 'setPrefSize' and 'setMaxSize' textfield methods to force a maximum height.
public static final String display(String savedFamily, String savedStyle, String savedSize, String stylesheet) {
fontFamily = savedFamily;
fontSize = savedSize.substring(0, savedSize.length() - 2);
fontWeight = getChosenWeight(savedStyle);
fontStyle = getChosenStyle(savedStyle);
// Add stage
Stage window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
TextField sample = new TextField("AaBbYyZz");
sample.setEditable(false);
sample.getStyleClass().add("sample");
sample.setAlignment(Pos.CENTER);
sample.setStyle(getCSS());
sample.setPrefSize(200, 60);
sample.setMaxHeight(60);
// Add list view title labels
Label fontLabel = new Label("Font:");
Label fontStyleLabel = new Label("Font Style:");
Label fontSizeLabel = new Label("Font Size: ");
// Add font list view
ListView<String> fontView = new ListView<>();
String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (int i = 0; i < fonts.length; i++) {
fontView.getItems().add(fonts[i]);
}
fontView.getSelectionModel().select(fontFamily);
fontView.setMaxSize(200, 150);
fontView.getSelectionModel().selectedItemProperty().addListener((v) -> {
fontFamily = fontView.getSelectionModel().getSelectedItem();
sample.setStyle(getCSS());
});
// Add font style list view
ListView<String> fontStyleView = new ListView<>();
fontStyleView.getItems().addAll("Regular", "Italic", "Bold", "Bold Italic");
fontStyleView.getSelectionModel().select(savedStyle);
fontStyleView.setMaxSize(80, 150);
fontStyleView.getSelectionModel().selectedItemProperty().addListener((v) -> {
fontStyle = getChosenStyle(fontStyleView.getSelectionModel().getSelectedItem());
fontWeight = getChosenWeight(fontStyleView.getSelectionModel().getSelectedItem());
sample.setStyle(getCSS());
});
// Add font size list view
ListView<String> fontSizeView = new ListView<>();
fontSizeView.getItems().addAll("6", "7", "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28");
fontSizeView.getSelectionModel().select(fontSize);
fontSizeView.setMaxSize(80, 150);
fontSizeView.getSelectionModel().selectedItemProperty().addListener((v) -> {
fontSize = fontSizeView.getSelectionModel().getSelectedItem();
sample.setStyle(getCSS());
});
// Add OK button
Button okButton = new Button("OK");
okButton.setOnAction(e -> {
fontCssString = getCSS();
window.close();
});
// Add cancel button
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(e -> {
window.close();
});
// Add and configure grid pane
GridPane layout = new GridPane();
layout.setPadding(new Insets(15, 15, 15, 15));
layout.setVgap(20);
layout.setHgap(20);
// Set grid constraints for font list view and title
GridPane.setConstraints(fontLabel, 0, 0);
GridPane.setConstraints(fontView, 0, 1);
// Set grid constraints for font style list view and title
GridPane.setConstraints(fontStyleLabel, 1, 0);
GridPane.setConstraints(fontStyleView, 1, 1);
GridPane.setValignment(fontStyleView, VPos.TOP);
// Set grid constraints for font size list view and title
GridPane.setConstraints(fontSizeLabel, 2, 0);
GridPane.setConstraints(fontSizeView, 2, 1);
// Set grid constraints for sample title
GridPane.setConstraints(sample, 0, 2);
GridPane.setHalignment(sample, HPos.CENTER);
// set grid constraints and alignments for buttons
GridPane.setConstraints(okButton, 1, 2);
GridPane.setHalignment(okButton, HPos.RIGHT);
GridPane.setConstraints(cancelButton, 2, 2);
// Add items to grid pane layout
layout.getChildren().addAll(fontLabel, fontView, fontStyleLabel, fontStyleView, fontSizeLabel, fontSizeView,
sample, okButton, cancelButton);
// configure the scene and stage
Scene scene = new Scene(layout, 450, 300);
scene.getStylesheets().add(FontWindow.class.getResource(stylesheet).toExternalForm());
window.setScene(scene);
window.setTitle("Font Options");
window.showAndWait();
return fontCssString;
}
public static final String getChosenStyle(String s) {
String result = "normal";
if (s.contains("Italic")) {
result = "italic";
}
return result;
}
public static final String getChosenWeight(String s) {
String result = "normal";
if (s.contains("Bold")) {
result = "bold";
}
return result;
}
public static String getCSS() {
return "-fx-font-family: " + fontFamily + "; -fx-font-weight: " + fontWeight + "; -fx-font-style: " + fontStyle
+ "; -fx-font-size: " + Float.valueOf(fontSize) / 9.7 + "em;";
}
}
Edit: This has been solved! I was able to get the text field to function as I wanted by setting the maximum and minimum size as well as setting the preferred height and width to 'region.USE_COMPUTED_SIZE'.
This woks to me.
<TextField layoutX="151.0" layoutY="53.0" maxHeight="50.0" maxWidth="255.0" minHeight="50.0" minWidth="255.0" text="AaZz">
...and Pref Height/Pref Width are "USE_COMPUTED_SIZE"
All TextField has preferred padding in each side.
Tips: to change the TextField into the least size, make it sure change also the padding of the TextField to make the size you want.
in JavaFx:
TextField textDisplay = new TextField();
textDisplay.setPrefSize(100,5);
textDisplay.setPadding(new Insets(1,1,1,1));
if you want set the size of your textField base on the fontSize in textField ,just leave it a null "DONT USE" .setPrefSize(double,double); that will set the static size of your textField BUT set the max of your textfield using css/javafx
textDisplay.setMaxWidth(double);
textDisplay.setMaxHeiht(double);
or
textDisplay.setSize(double,double);
but if you use CSS much more easy to design your GUI just dont forget set an ID of your nodes.
textDisplay.setStyle("-fx-pref-width: 100"
+"\n-fx-pref-height: 100"
+"-fx-padding: 5 5 5 5;");
or
textDisplay.setId("idTextDisplay");
#idTextDisplay{
-fx-pref-width: 100;
-fx-pref-height: 100;
-fx-padding: 5 5 5 5;
}
in your case is:
TextField sample = new TextField("AaBbYyZz");
sample.setEditable(false);
sample.getStyleClass().add("sample");
sample.setAlignment(Pos.CENTER);
sample.setStyle(getCSS());
sample.setPrefSize(200, 60);
sample.prefHeight(Region.USE_COMPUTED_SIZE);
sample.prefwidth(Region.USE_COMPUTED_SIZE);

How can I use my text field and slider input in my Lambda expression?

I am currently making a tip calculator and I have hit a wall. My textbook, Big Java, Late Objects, did not have the answer. I scoured stack overflow and a bit of Reddit too but I was only able to partially solve my dilemma. I feel as though I am on the right track. The issue lies within the lambda expression calcTipClick connected to the calculateTipButton. EDIT How can I use the user input from the slider, split check, and checkAmtTextField to do my calculations of the GUI. Sorry
public class TipCalcApp extends Application {
// declare interface controls
Label titleLabel, checkAmtLabel, tipPercentLabel, splitLabel, tipAmtLabel;
Label totalLabel, amtPerPersonLabel;
TextField checkAmtText, tipAmtText, totalText, amtPerPersonText;
Slider tipPercentSlider;
ChoiceBox splitChoiceBox;
Button calcTipButton;
// declare a grid pane (8 rows and 2 columns)
GridPane grid;
#Override
public void start(Stage primaryStage) {
// instantiate labels and their properties
titleLabel = new Label("Tip Calculator");
titleLabel.setMaxWidth(Double.MAX_VALUE);
titleLabel.setAlignment(Pos.CENTER);
checkAmtLabel = new Label("Check Amount");
checkAmtLabel.setMaxWidth(Double.MAX_VALUE);
checkAmtLabel.setAlignment(Pos.CENTER_RIGHT);
tipPercentLabel = new Label("Tip Percent: ");
tipPercentLabel.setMaxWidth(Double.MAX_VALUE);
tipPercentLabel.setAlignment(Pos.CENTER_RIGHT);
splitLabel = new Label("Split");
splitLabel.setMaxWidth(Double.MAX_VALUE);
splitLabel.setAlignment(Pos.CENTER_RIGHT);
tipAmtLabel = new Label("Tip Amount");
tipAmtLabel.setMaxWidth(Double.MAX_VALUE);
tipAmtLabel.setAlignment(Pos.CENTER_RIGHT);
totalLabel = new Label("Total");
totalLabel.setMaxWidth(Double.MAX_VALUE);
totalLabel.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonLabel = new Label("Amount Per Person");
amtPerPersonLabel.setMaxWidth(Double.MAX_VALUE);
amtPerPersonLabel.setAlignment(Pos.CENTER_RIGHT);
// instantiate text fileds and their properties
checkAmtText = new TextField();
tipAmtText = new TextField();
tipAmtText.setEditable(false);
totalText = new TextField();
totalText.setEditable(false);
amtPerPersonText = new TextField();
amtPerPersonText.setEditable(false);
// instantiate a slider and its properties
tipPercentSlider = new Slider();
tipPercentSlider.setPrefWidth(300);
tipPercentSlider.setMin(0);
tipPercentSlider.setMax(25);
tipPercentSlider.setMajorTickUnit(5);
tipPercentSlider.setMinorTickCount(0);
tipPercentSlider.setBlockIncrement(5);
tipPercentSlider.setShowTickLabels(true);
tipPercentSlider.setShowTickMarks(true);
tipPercentSlider.setSnapToTicks(true);
tipPercentSlider.setOrientation(Orientation.HORIZONTAL);
tipPercentSlider.valueProperty().addListener(
(observable, oldvalue, newvalue) ->
{
// show integer values only
tipPercentLabel.setText(String.format("Tip Percent: %2d%s", newvalue.intValue(), "%"));
});
// instantiate a choice box and its properties
splitChoiceBox = new ChoiceBox();
splitChoiceBox.getItems().addAll("1", "2", "3", "4", "5");
splitChoiceBox.setValue("1");
// instantiate a button and its properties
calcTipButton = new Button("Calculate Tip");
calcTipButton.setMaxWidth(Double.MAX_VALUE);
calcTipButton.setOnAction(e -> calcTipClick());
// instantiate a grid pane and its properties
grid = new GridPane();
grid.setHgap(15);
grid.setVgap(15);
grid.setPadding(new Insets(10));
grid.add(titleLabel, 0, 0, 2, 1);
grid.addRow(1, checkAmtLabel, checkAmtText);
grid.addRow(2, tipPercentLabel, tipPercentSlider);
grid.addRow(3, splitLabel, splitChoiceBox);
grid.add(calcTipButton, 0, 4, 2, 1);
grid.addRow(5, tipAmtLabel, tipAmtText);
grid.addRow(6, totalLabel, totalText);
grid.addRow(7, amtPerPersonLabel, amtPerPersonText);
// instantiate the grid pane and put items in in grid
Scene scene = new Scene(grid);
scene.getRoot().setStyle("-fx-font: 15 'Comic Sans MS'");
primaryStage.setTitle("Tip Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void calcTipClick() {
//Gather choiceBox
String choiceInput = splitChoiceBox.getValue().toString();
int choiceSelection = Integer.parseInt(choiceInput.substring(0, 1));
//Gather Slider information
String sliderInput;
sliderInput = tipPercentLabel.getValue().toString();
int sliderSelection = Integer.parseInt(sliderInput.substring(0, 1));
//Gather textField amount
}
Not sure if this is what you are asking, but this is an idea of how you can calculate the tip and split it in your calcTipClick() method. You should look at formatters to ensure format, rounding, etc. But this should give you the general idea.
private void calcTipClick() {
//Gather choiceBox
String choiceInput = splitChoiceBox.getValue().toString();
int choiceSelection = Integer.parseInt(choiceInput.substring(0, 1));
//Gather Slider information
Number sliderInput = tipPercentSlider.getValue();
//Gather textField amount
String val = checkAmtText.getText();
NumberStringConverter nsc = new NumberStringConverter();
Number amount = 0;
try {
amount = nsc.fromString(val);
}catch (Exception pe) {
//Need to handle a parse error if the user isn't entering numbers
//Should look at text formatters to ensure amount is only entered valid
amount = 0;
}
Number tipAmount = amount.doubleValue() * sliderInput.doubleValue()/100;
tipAmtText.setText(tipAmount.toString());
Number totalAmount = tipAmount.doubleValue() + amount.doubleValue();
totalText.setText(totalAmount.toString());
Number perPerson = totalAmount.doubleValue() / choiceSelection;
amtPerPersonText.setText(perPerson.toString());
}

JavaFX GridPane - Configuring controls to grow and occupy all the available space

Trying to achieve:
Text Field 1 and Text Field 3 should occupy all the available free space
Button 1 and Button 2 should have same width
Issue:
Text Field 1 and Text Field 3 are NOT occupying all the available free space (though they are growing once Label is completely displayed)
Here is the screen shot:
// Removed imports for brevity
public class GridPaneTest extends Application
{
#Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("GridPane Test");
GridPane gridPane = new GridPane();
// gridPane.setGridLinesVisible(true);
gridPane.setHgap(5);
gridPane.setVgap(5);
gridPane.setPadding(new Insets(5));
TextField tf1 = new TextField("Text Field 1");
GridPane.setHgrow(tf1, Priority.ALWAYS);
gridPane.add(tf1, 0, 0);
TextField tf2 = new TextField("Text Field 2");
GridPane.setHgrow(tf2, Priority.NEVER);
gridPane.add(tf2, 1, 0);
Button button1 = new Button("Button 1");
button1.setMaxWidth(140);
GridPane.setHgrow(button1, Priority.NEVER);
GridPane.setHalignment(button1, HPos.RIGHT);
gridPane.add(button1, 2, 0);
TextField tf3 = new TextField("Text Field 3");
GridPane.setHgrow(tf3, Priority.ALWAYS);
gridPane.add(tf3, 0, 1, 2, 1);
Button button2 = new Button("Button 2 Button 2");
button2.setMaxWidth(140);
GridPane.setHgrow(button2, Priority.NEVER);
GridPane.setHalignment(button2, HPos.RIGHT);
gridPane.add(button2, 2, 1);
Label label1 = new Label(
"Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1");
GridPane.setHgrow(label1, Priority.ALWAYS);
gridPane.add(label1, 0, 2, 3, 1);
primaryStage.setScene(new Scene(gridPane));
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
According to GridPane documentation
if an application needs to explicitly control the size of rows or columns, it may do so by adding RowConstraints and ColumnConstraints objects to specify those metrics
gridPane.getColumnConstraints()
.addAll(new ColumnConstraints(), new ColumnConstraints(),
new ColumnConstraints(140) /* Control the third column size */);
Screen shot:

Changing the grid colour of a GraphView object in Android

I've added a GraphView object and populated it with some data as per the example in the documentation on the website. While I've found out how to change the background colour of the GraphView, I have no idea how to change the grid colour. Any ideas?
This is what I've tried:
public void createGraph(View view){
GraphView graph = (GraphView) view.findViewById(R.id.graph);
GridLabelRenderer gridLabelRenderer = graph.getGridLabelRenderer();
// This works
graph.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
// This does not work
gridLabelRenderer.setGridColor(getResources().getColor(android.R.color.holo_green_light));
// Nor does this
//gridLabelRenderer.setGridColor(15);
// This works
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {
new DataPoint(0, 1),
new DataPoint(1, 5),
new DataPoint(2, 3),
new DataPoint(3, 2),
new DataPoint(4, 6)
});
graph.addSeries(series);
}
try
graph.getGridLabelRenderer().reloadStyles();
styling example it here
https://github.com/appsthatmatter/GraphView-Demos/blob/master/app/src/main/java/com/jjoe64/graphview_demos/examples/StylingColors.java

Categories

Resources