I have ObservableList<LineChart> backCharts. Also I have class StackChartSeries to compare data's scale. Depending on that I add new backchart with new scale or add series to existed backchart.
Applying style to chart must work with every chart of the specified scale. But it works only with the first chart of the specified scale.
Code next:
public class StackChart extends StackPane {
private LineChart baseChart;
private final ObservableList<LineChart> backCharts = FXCollections.observableArrayList();
private final double yAxisWidth = 60;
private final AnchorPane details;
private final double yAxisSeparation = 20;
private double strokeWidth = 0.5;
private int size = 0;
public StackChart(LineChart baseChart) {
this(baseChart, null);
}
public StackChart(LineChart baseChart, Double strokeWidth) {
if (strokeWidth != null) {
this.strokeWidth = strokeWidth;
}
this.baseChart = baseChart;
baseChart.setCreateSymbols(false);
baseChart.setLegendVisible(false);
baseChart.getXAxis().setAutoRanging(false);
baseChart.getXAxis().setAnimated(false);
baseChart.getXAxis().setStyle("-fx-font-size:" + 18);
baseChart.getYAxis().setAnimated(false);
baseChart.getYAxis().setStyle("-fx-font-size:" + 18);
setFixedAxisWidth(baseChart);
setAlignment(Pos.CENTER_LEFT);
backCharts.addListener((Observable observable) -> rebuildChart());
details = new AnchorPane();
bindMouseEvents(baseChart, this.strokeWidth);
rebuildChart();
}
private void bindMouseEvents(LineChart baseChart, Double strokeWidth) {
getChildren().add(details);
details.prefHeightProperty().bind(heightProperty());
details.prefWidthProperty().bind(widthProperty());
details.setMouseTransparent(true);
setOnMouseMoved(null);
setMouseTransparent(false);
final Axis xAxis = baseChart.getXAxis();
final Axis yAxis = baseChart.getYAxis();
final Line xLine = new Line();
final Line yLine = new Line();
yLine.setFill(Color.GRAY);
xLine.setFill(Color.GRAY);
yLine.setStrokeWidth(strokeWidth/2);
xLine.setStrokeWidth(strokeWidth/2);
xLine.setVisible(false);
yLine.setVisible(false);
final Node chartBackground = baseChart.lookup(".chart-plot-background");
for (Node n: chartBackground.getParent().getChildrenUnmodifiable()) {
if (n != chartBackground && n != xAxis && n != yAxis) {
n.setMouseTransparent(true);
}
}
chartBackground.setCursor(Cursor.CROSSHAIR);
chartBackground.setOnMouseEntered((event) -> {
chartBackground.getOnMouseMoved().handle(event);
xLine.setVisible(true);
yLine.setVisible(true);
details.getChildren().addAll(xLine, yLine);
});
chartBackground.setOnMouseExited((event) -> {
xLine.setVisible(false);
yLine.setVisible(false);
details.getChildren().removeAll(xLine, yLine);
});
chartBackground.setOnMouseMoved(event -> {
double x = event.getX() + chartBackground.getLayoutX();
double y = event.getY() + chartBackground.getLayoutY();
xLine.setStartX(65);
xLine.setEndX(details.getWidth()-10);
xLine.setStartY(y+5);
xLine.setEndY(y+5);
yLine.setStartX(x+5);
yLine.setEndX(x+5);
yLine.setStartY(12);
yLine.setEndY(details.getHeight()-28);
});
}
private void setFixedAxisWidth(LineChart chart) {
chart.getYAxis().setPrefWidth(yAxisWidth);
chart.getYAxis().setMaxWidth(yAxisWidth);
}
private void rebuildChart() {
getChildren().clear();
getChildren().add(resizeBaseChart(baseChart));
for (LineChart lineChart : backCharts) {
getChildren().add(resizeBackgroundChart(lineChart));
}
getChildren().add(details);
}
private Node resizeBaseChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
return lineChart;
}
private Node resizeBackgroundChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
hBox.setMouseTransparent(true);
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.translateXProperty().bind(baseChart.getYAxis().widthProperty());
lineChart.getYAxis().setTranslateX((yAxisWidth + yAxisSeparation) * backCharts.indexOf(lineChart));
return hBox;
}
private LineChart prepareLineChart(String seriesName){
NumberAxis yAxis = new NumberAxis();
NumberAxis xAxis = new NumberAxis();
// xAxis
xAxis.setAutoRanging(false);
xAxis.setVisible(false);
xAxis.setOpacity(0.0);
xAxis.lowerBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).lowerBoundProperty());
xAxis.upperBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).upperBoundProperty());
xAxis.tickUnitProperty().bind(((NumberAxis) baseChart.getXAxis()).tickUnitProperty());
// yAxis
yAxis.setSide(Side.RIGHT);
yAxis.setLabel(seriesName);
// create chart
LineChart lineChart = new LineChart(xAxis, yAxis);
lineChart.setAnimated(false);
lineChart.setLegendVisible(false);
setFixedAxisWidth(lineChart);
return lineChart;
}
public void addSeries(List<StackChartSeries> series){
Collections.sort(series, (x, y) -> (int) (x.getMaxY() - y.getMaxY()));
LineChart lineChart = null;
size = series.size();
for (int i = 0; i < size; i++) {
if (i == 0 || series.get(i).getMaxY() / series.get(i-1).getMaxY() >= 10
|| series.get(i).getMaxY() / series.get(i-1).getMaxY() <= 0.1
|| Math.abs(series.get(i).getMaxY() - series.get(i-1).getMaxY()) >= 900
) {
lineChart = prepareLineChart("Scale" + i);
//new chart with new scale
backCharts.add(lineChart);
}
lineChart.getData().add(series.get(i).getSeries());
}
int j = 0;
for (LineChart chart : backCharts) {
styleBackChart(chart);
//HERE
setLineStyle(chart, j+3);
}
}
private void styleBackChart(LineChart lineChart) {
setStyle(lineChart);
Node contentBackground = lineChart.lookup(".chart-content").lookup(".chart-plot-background");
contentBackground.setStyle("-fx-background-color: transparent;");//
lineChart.setVerticalZeroLineVisible(false);
lineChart.setHorizontalZeroLineVisible(false);
lineChart.setVerticalGridLinesVisible(false);
lineChart.setHorizontalGridLinesVisible(false);
lineChart.setCreateSymbols(false);
lineChart.getXAxis().setStyle("-fx-font-size:" + 18);
lineChart.getYAxis().setStyle("-fx-font-size:" + 18);
}
private void setStyle(LineChart chart) {
chart.getYAxis().lookup(".axis-label").setStyle("-fx-font-size: 24;");
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle("-fx-stroke-width: " + strokeWidth + ";");
}
public Node getLegend() {
HBox hbox = new HBox();
final CheckBox baseChartCheckBox = new CheckBox(baseChart.getYAxis().getLabel());
baseChartCheckBox.setSelected(true);
baseChartCheckBox.setDisable(true);
baseChartCheckBox.getStyleClass().add("readonly-checkbox");
baseChartCheckBox.setOnAction(event -> baseChartCheckBox.setSelected(true));
hbox.getChildren().add(baseChartCheckBox);
for (final LineChart lineChart : backCharts) {
CheckBox checkBox = new CheckBox(lineChart.getYAxis().getLabel());
checkBox.setSelected(true);
checkBox.setOnAction(event -> {
if (backCharts.contains(lineChart)) {
backCharts.remove(lineChart);
} else {
backCharts.add(lineChart);
}
});
hbox.getChildren().add(checkBox);
}
hbox.setAlignment(Pos.CENTER);
hbox.setSpacing(20);
hbox.setStyle("-fx-padding: 0 10 20 10");
return hbox;
}
private void setLineStyle (LineChart chart, Integer k) {
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle(" -fx-stroke-dash-array: " + k + " 5 15 5;");
}
}
StackChartSeries.java:
import javafx.scene.chart.XYChart;
import org.apache.commons.lang.ArrayUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
public class StackChartSeries {
private XYChart.Series series;
private final double[] xValues;
private final double[] yValues;
private Optional<Double> maxY;
public StackChartSeries(double[] xValues, double[] yValues) {
this.xValues = xValues;
this.yValues = yValues;
}
public XYChart.Series getSeries() {
return series != null ? series : (series = prepareSeries(xValues, yValues));
}
private static XYChart.Series<Number, Number> prepareSeries( double[] xValues, double[] yValues) {
XYChart.Series<Number, Number> series = new XYChart.Series<>();
for (int i = 0; i < yValues.length; i++){
series.getData().add(new XYChart.Data(xValues[i], yValues[i]));
}
return series;
}
public double getMaxY(){
if (maxY != null){
return maxY.get();
}
else {
Double d = C?ollections.max(Arrays.asList(ArrayUtils.toObject(yValues)));
maxY = Optional.of(d);
return maxY.get();
}
}
public double[] getXValues() {
return xValues;
}
public double[] getYValues() {
return yValues;
}
}
I submit data and a chart has been displayed But again when I submit it by inserting new values in form,chart doesn't update itself.Another thing I saw is when I refresh the page then it update the chart and chart with new values get display.
For instance If I give values Wheat=40 and Sugar=60and submit , It will display the chart.Now when I submit Wheat=90 and Sugar=10 , it displays nothing but the old chart remain present on the page.Now If I refresh the page , The chart with updated values will be availabe.How can I get rid of that problem :( Please suggest a solution if any one have.
Here is my code
Chart Code
<p:barChart id="horizontal"
value="#{reportingCharts.categoryModel}" legendPosition="se"
style="width:635px;height:500px" title="Horizontal Bar Chart"
orientation="horizontal" min="0" max="150" animate="true"
zoom="true" barMargin="90"
rendered="#{chartsRendering.barCharts}" showDatatip="true" shadow="true" />
Button Code
<h:commandButton id="btnLanguage" action="#{reportingCharts.getGraphValuesOnLanguageBasis}"
value="Plot Chart Language">
</h:commandButton>
getGraphValuesOnLanbguageBasis method
public void getGraphValuesOnLanguageBasis() {
categoryModel = null;
resList = (ArrayList<ChartResult>) serviceObj
.getChartByLanguage(ranks, language);
if (chartType.equalsIgnoreCase("bar")
|| chartType.equalsIgnoreCase("line")
|| chartType.equalsIgnoreCase("column")) {
categoryModel = new CartesianChartModel();
ChartSeries langChart = null;
for (int a = 0; a < ranks.length; a++) {
langChart = new ChartSeries();
if(a == 0){
for(int z=0;z<language.length;z++){
langChart.set(languageMap.get(Integer.parseInt(language[z])),0);
}
}
String rank = "";
boolean rankAvailable = false;
for (int x = 0; x < resList.size(); x++) {
if(Integer.parseInt(resList.get(x).getRankId()) == Integer.parseInt(ranks[a])){
rank = resList.get(x).getRankName();
x = resList.size();
rankAvailable = true;
}
}
if(rankAvailable == false){
langChart.setLabel(rankMap.get(Integer.parseInt(ranks[a])));
}
else{
langChart.setLabel(rank);
}
for (int x = 0; x < resList.size(); x++) {
if (Integer.parseInt(resList.get(x).getRankId()) == Integer
.parseInt(ranks[a]) && rankAvailable == true) {
langChart.set(languageMap.get(Integer.parseInt(resList.get(x).getCriteria())), Integer
.parseInt(resList.get(x).getNoOfPersons()));
}
}
categoryModel.addSeries(langChart);
}
} else if (chartType.equalsIgnoreCase("pie")) {
pieModel = new PieChartModel();
for (int x = 0; x < resList.size(); x++) {
pieModel.set(languageMap.get(Integer.parseInt(resList.get(x).getCriteria())), Integer
.parseInt(resList.get(x).getNoOfPersons()));
}
}
ChartsRendering chartRenderer1 = (ChartsRendering) FacesContext
.getCurrentInstance().getExternalContext().getSessionMap()
.get("chartsRendering");
if (chartType.equalsIgnoreCase("bar")) {
chartRenderer1.showBarChart();
} else if (chartType.equalsIgnoreCase("line"))
chartRenderer1.showLineChart();
else if (chartType.equalsIgnoreCase("column"))
chartRenderer1.showColumnChart();
else if (chartType.equalsIgnoreCase("pie"))
chartRenderer1.showPieChart();
}
The chart won't update itself after you change the model values but you can update it through ajax. For example if you have a chart:
<p:barChart id="myBarChart" value=#{yourChartBean.chartModel} ..../>
and a selecteOneMenu which sends new values to your backing bean, define a method which will update the model in your backing bean:
<p:selectOneMenu id="aMenu" value="#{yourChartBean.menuValue}">
<p:ajax event="change" update="myBarChart" listener="#{yourChartBean.refreshChart()}"/>
<f:selectItem itemLabel="This value" itemValue="tv"/>
<f:selectItem itemLabel="Another value" itemValue="av"/>
</p:selectOneMenu>
in this case the refreshChart() method is intended to update your chart model:
public void refreshChart() {
buildChart();
}
private void buildChart() {
chartModel = new CartesianChartModel();
ChartSeries series1 = new ChartSeries();
...
ChartSeries series2 = new ChartSeries();
...
categoryModel.addSeries(series1);
categoryModel.addSeries(series2);
}
Chart should be visible when page loads...after that all ajax request properly renders your chart.
To do that just provide a dummy series data like (0,0) for series 1 and (0,0) for series 2 when page loads, after that everything works fine
I've built a list and inserted labels in each cell. For now the text that is too long simply disappear. I'd like to wrap the text so it is entirely visible inside each cell.
Can you please help?
update: issue solved
For those who need an answer, I used LWUIT's HTMLComponent inside a container. The HTMLComponent allows you to use HTML code. That would allow you to format your list the way you want it to be.
Here is more details on the solution.
In Java ME with LWUIT, I used a HTMLComponent to get the precise layout I wanted. The best way for me was to use an HTML Table inside the HTMLComponent. It just behaves like HTML.
String html_code = "";
html_code = "<table width='100%'>";
html_code += "<tr><td><strong>"+fullname+"</strong></td></tr>";
if (title.length()>0) { html_code += "<tr><td><i>"+title+"</i></td></tr>"; }
if (message.length()>0) { html_code += "<tr><td>"+message+"</td></tr>"; }
if (date.length()>0) { html_code += "<tr><td><i>"+date+"</i></td></tr>"; }
html_code += "</table>";
HTMLComponent html = new HTMLComponent(null);
html.setBodyText(html_code);
Just incase if you are looking for a more "elegant" solution, i found a handy resource online. I am posting here for reference purposes, but HtmlComponent does the job.
import com.sun.lwuit.Font;
/** A class supporting word wrap for MIDP. */
public class WordWrap {
Font font;
int width;
String txt;
int pos;
/**
* Initializes the WordWrap object with the given Font, the text string
* to be wrapped, and the target width.
*
* #param font: The Font to be used to calculate the character widths.
* #param txt: The text string to be wrapped.
* #param width: The line width.
*/
public WordWrap (Font font, String txt, int width) {
this.font = font;
this.txt = txt;
this.width = width;
}
/**
* returns the next line break position. If no text is left, -1 is returned.
*/
public int next () {
int i = pos;
int len = txt.length ();
if (pos >= len) return -1;
int start = pos;
while (true) {
while (i < len && txt.charAt (i) > ' ')
i++;
int w = font.stringWidth (txt.substring (start, i));
if (pos == start) {
if (w > width) {
while (font.stringWidth (txt.substring (start, --i)) > width)
{ }
pos = i;
break;
}
}
if (w <= width) pos = i;
if (w > width || i >= len || txt.charAt(i) == '\n') break;
i++;
}
return pos >= len ? pos : ++pos;
}
}
import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.FocusListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.Border;
import com.sun.lwuit.plaf.Style;
/**
*
* #author rubycube
*/
public class WrapList extends Container {
private Button hiddenButton;
private int id;
public WrapList(String text, int containerID) {
id = containerID;
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
this.setFocusable(false);
final Style thisContainerStyle = this.getStyle();
Border thisContainerBorder = Border.createRoundBorder(20, 20, 0xcccccc);
thisContainerStyle.setBorder(thisContainerBorder);
hiddenButton = new Button(" ");
hiddenButton.setPreferredSize(new Dimension(1, 1));
Style style = hiddenButton.getStyle();
style.setBgTransparency(0, false);
style.setBorder(Border.createEmpty());
FocusListener hiddenButtonFL = new FocusListener() {
public void focusGained(Component cmp) {
WrapList parentContainer = ((WrapList) (cmp.getParent()));
Border parentContainerBorder = Border.createRoundBorder(20, 20, 0xff6600);
Style parentContainerStyle = parentContainer.getStyle();
parentContainerStyle.setBorder(parentContainerBorder);
parentContainerStyle.setBgColor(0xff9900);
parentContainerStyle.setBgTransparency(50);
parentContainer.repaint();
}
public void focusLost(Component cmp) {
WrapList parentContainer = ((WrapList) (cmp.getParent()));
Border parentContainerBorder = Border.createRoundBorder(20, 20, 0xcccccc);
Style parentContainerStyle = parentContainer.getStyle();
parentContainerStyle.setBorder(parentContainerBorder);
parentContainerStyle.setBgTransparency(0);
parentContainer.repaint();
}
};
hiddenButton.addFocusListener(hiddenButtonFL);
Label l = new Label(text);
l.setSelectedStyle(thisContainerStyle);
//l.setUnselectedStyle(thisContainerStyle);
WordWrap ww = new WordWrap(l.getStyle().getFont(), text, (Display.getInstance().getDisplayWidth() - 10));
int si = 0;
int ei = 0;
while (true) {
int np = ww.next();
if (np == -1) {
break;
} else {
si = ei;
ei = np;
}
String lineText = text.substring(si, ei);
Label line = new Label(lineText);
line.setEndsWith3Points(false);
this.addComponent(line);
}
this.addComponent(hiddenButton);
}
public void addActionListener(ActionListener actionlistener) {
hiddenButton.addActionListener(actionlistener);
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
Is there any way to create a Tab Menu in j2me?
I found a code but I am unable to understand it
In this code there is Tab Menu created which is in Canvas class and then Tab menu is created which is totally done in Canvas or painted. The only part I found difficult to grasp was the void go() method and then
When I try to draw anything above and below this code using paint method, it doesn't work - what's the problem?
Below is the code
// Tab Menu CANVAS class
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class TabMenuCanvas extends Canvas
{
TabMenu menu = null;
public TabMenuCanvas()
{
menu = new TabMenu(
new String[]{"Home", "News", "Community", "Your files", "Credits", "Events", "Blog", "Upload", "Forum Nokia"},
getWidth() - 20
);
}
protected void keyPressed(int key)
{
int gameAction = getGameAction(key);
if(gameAction == Canvas.RIGHT)
{
menu.goRight();
repaint();
}
else if(gameAction == Canvas.LEFT)
{
menu.goLeft();
repaint();
}
}
protected void paint(Graphics g)
{
g.translate(10, 30);
menu.paint(g);
g.translate(- 10, - 30);
}
}
// Tab Menu Class
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TabMenu
{
int background = 0xffffff;
int bgColor = 0xcccccc;
int bgFocusedColor = 0x0000ff;
int foreColor = 0x000000;
int foreFocusedColor = 0xffffff;
int cornerRadius = 6;
int padding = 2;
int margin = 2;
Font font = Font.getDefaultFont();
int scrollStep = 20;
int selectedTab = 0; //selected tab index
int[] tabsWidth = null; //width of single tabs
int[] tabsLeft = null; //left X coordinate of single tabs
int tabHeight = 0; //height of tabs (equal for all tabs)
String[] tabs = null; //tab labels
int menuWidth = 0; //total menu width
int viewportWidth = 0; //visible viewport width
int viewportX = 0; //current viewport X coordinate
public TabMenu(String[] tabs, int width)
{
this.tabs = tabs;
this.viewportWidth = width;
initialize();
}
void initialize()
{
tabHeight = font.getHeight() + cornerRadius + 2 * padding; //[ same for all tabs]
menuWidth = 0;
tabsWidth = new int[tabs.length];
tabsLeft = new int[tabs.length];
for(int i = 0; i < tabsWidth.length; i++)
{
tabsWidth[i] = font.stringWidth(tabs[i]) + 2 * padding + 2 * cornerRadius;
tabsLeft[i] = menuWidth;
menuWidth += tabsWidth[i];
if(i > 0)
{
menuWidth += margin;
}
}
}
public void goRight()
{
go(+1);
}
public void goLeft()
{
go(-1);
}
private void go(int delta)
{
int newTab = Math.max(0, Math.min(tabs.length - 1, selectedTab + delta));
boolean scroll = true;
if(newTab != selectedTab && isTabVisible(newTab))
{
selectedTab = newTab;
if( (delta > 0 && tabsLeft[selectedTab] + tabsWidth[selectedTab] > viewportX + viewportWidth) ||
(delta < 0 && tabsLeft[selectedTab] < viewportX))
{
scroll = true;
}
else
{
scroll = false;
}
}
if(scroll)
{
viewportX = Math.max(0, Math.min(menuWidth - viewportWidth, viewportX + delta * scrollStep));
}
}
private boolean isTabVisible(int tabIndex)
{
return tabsLeft[tabIndex] < viewportX + viewportWidth &&
tabsLeft[tabIndex] + tabsWidth[tabIndex] >= viewportX;
}
public void paint(Graphics g)
{
int currentX = - viewportX;
g.setClip(0, 0, viewportWidth, tabHeight);
g.setColor(background);
g.fillRect(0, 0, viewportWidth, tabHeight);
for(int i = 0; i < tabs.length; i++)
{
g.setColor(i == selectedTab ? bgFocusedColor : bgColor);
g.fillRoundRect(currentX, 0, tabsWidth[i], tabHeight + cornerRadius, 2 * cornerRadius, 2 * cornerRadius);
g.setColor(i == selectedTab ? foreFocusedColor : foreColor);
g.drawString(tabs[i], currentX + cornerRadius + padding, cornerRadius + padding, Graphics.LEFT | Graphics.TOP);
currentX += tabsWidth[i] + margin;
}
}
}
When I try to draw anything above and below this code using paint method, it doesn't work
what of the paint methods you use to draw above and below? Pay attention that there are two methods named that way - first is in TabMenuCanvas, second is in TabMenu (second method is invoked from TabMenuCanvas#repaint).
whatever you would try to draw in TabMenuCanvas#paint will most likely be overwritten by setClip and fillRect when TabMenu#paint is invoked following repaint request
The only place where one can expect to be able to draw something visible seems to be in TabMenu#paint method, inside the clip area that is set there.
You can use GUI Libraries for J2ME,for example Lightweight User Interface Toolkit (LWUIT),Flemil have "tab menu".You can see list of GUI Libraries here.
I have some JSF code that currently works (as shown below), and I need to modify it to conditionally suppress the display of certain rows of the table. I know how to conditionally suppress the display of a particular cell, but that seems to create an empty cell, while what I'm trying to do is to not display the row at all.
Any suggestions?
<h:dataTable styleClass="resultsTable" id="t1" value="#{r.common}" var="com" headerClass="headerBackgrnd" rowClasses="rowOdd, rowEven" columnClasses="leftAlign, rightAlign, leftAlign">
<h:column>
<h:outputText rendered="#{com.rendered}" styleClass="inputText" value="#{com.description}: " />
</h:column>
<h:column>
<h:outputText styleClass="outputText" value="#{com.v1}" />
</h:column>
<h:column>
<h:inputText styleClass="inputText" value="#{com.v2}" />
</h:column>
</h:dataTable>
Basically, the line that says #{com.rendered} will conditionally display the contents of a single cell, producing an empty cell when com.rendered is false. But I want to skip an entire row of the display under certain conditions - how would I go about doing that?
Rows correspond to data objects in the collection of your table. If you don't want the row, don't put the object in the collection.
Alternatively, you can use the rowClasses parameter for dataTable.
Bean code:
public String getRowClasses() {
StringBuilder sb = new StringBuilder();
for (Data data : myData) {
sb.append(data.hide ? 'hide,' : 'show,');
}
return sb.toString();
}
CSS:
tr.hide {display:none;}
For people using richFaces, you can use rich:column's filterExpression attribute.
<rich:column filterExpression="#{put your expression here}">
...
</rich>
If the condition is not met, the complete row is filtered out.
Example is using seam EL!
extension to Brian's solution.
To display the column names I did the following in primefaces
<p:dataTable value="#{eiBean.dce.ilDbConns}" var="c">
<p:columnGroup type="header">
<p:row>
<p:column colspan="1" />
<p:column colspan="1" />
</p:row>
<p:row>
<p:column headerText="DataBase Type" width="auto" />
<p:column headerText="URL" width="400" />
</p:row>
</p:columnGroup>
<p:column rendered='#{c.conType == "TARGET"}'>
<p:outputLabel value="#{c.dbType}" />
</p:column>
<p:column rendered='#{c.conType == "TARGET"}'>
<p:outputLabel value="#{c.dbUrl}" />
</p:column>
</p:dataTable>
I extend HtmlTableRenderer default renderer and overwrite renderRowStart method to achieve this by giving style attribute into table->tr element with value display:none.
The item inside binding list needs to implement TableRow interface which only has one method of isHide. In the concrete class you can put any logic you like to give a boolean value.
BTW, in this custom renderer also has PrimeFaces implementation like function which gives the message when table is empty and the table->tr will automatically calculate how many columns in the table and give proper value to colspan attribute.
public class MyDataTableRenderer extends HtmlTableRenderer {
private static final Integer[] ZERO_INT_ARRAY = new Integer[] { 0 };
private static final String NO_RESULT_MESSAGE_ATTR_NAME = "noResultMessage";
private static final String defaultEmptyMessage = "No records found";
private static final Logger log = Logger.getLogger(DHSDataTableRenderer.class.getName());
#Override
public void encodeInnerHtml(FacesContext facesContext, UIComponent component) throws IOException {
UIData uiData = (UIData) component;
String message = (String) uiData.getAttributes().get(NO_RESULT_MESSAGE_ATTR_NAME);
if (message == null || "".equals(message.trim())) {
message = defaultEmptyMessage;
}
ResponseWriter writer = facesContext.getResponseWriter();
int rowCount = uiData.getRowCount();
int newspaperColumns = getNewspaperColumns(component);
int columnNumber = getChildCount(component);
if (rowCount == -1 && newspaperColumns == 1) {
encodeInnerHtmlUnknownRowCount(facesContext, component);
return;
}
if (rowCount == 0) {
// nothing to render, to get valid xhtml we render an empty dummy
// row
writer.startElement(HTML.TBODY_ELEM, uiData);
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element", null);
writer.startElement(HTML.TR_ELEM, uiData);
writer.startElement(HTML.TD_ELEM, uiData);
writer.writeAttribute(HTML.COLSPAN_ATTR, columnNumber, null);
writer.writeAttribute(HTML.CLASS_ATTR, "dhs-empty-table", null);
writer.write(message);
writer.endElement(HTML.TD_ELEM);
writer.endElement(HTML.TR_ELEM);
writer.endElement(HTML.TBODY_ELEM);
return;
}
// begin the table
// get the CSS styles
Styles styles = getStyles(uiData);
int first = uiData.getFirst();
int rows = uiData.getRows();
int last;
if (rows <= 0) {
last = rowCount;
} else {
last = first + rows;
if (last > rowCount) {
last = rowCount;
}
}
int newspaperRows;
if ((last - first) % newspaperColumns == 0) {
newspaperRows = (last - first) / newspaperColumns;
} else {
newspaperRows = ((last - first) / newspaperColumns) + 1;
}
boolean newspaperHorizontalOrientation = isNewspaperHorizontalOrientation(component);
// get the row indizes for which a new TBODY element should be created
Integer[] bodyrows = getBodyRows(facesContext, component);
int bodyrowsCount = 0;
// walk through the newspaper rows
for (int nr = 0; nr < newspaperRows; nr++) {
boolean rowStartRendered = false;
// walk through the newspaper columns
for (int nc = 0; nc < newspaperColumns; nc++) {
// the current row in the 'real' table
int currentRow;
if (newspaperHorizontalOrientation) {
currentRow = nr * newspaperColumns + nc + first;
} else {
currentRow = nc * newspaperRows + nr + first;
}
// if this row is not to be rendered
if (currentRow >= last) {
continue;
}
// bail if any row does not exist
uiData.setRowIndex(currentRow);
if (!uiData.isRowAvailable()) {
log.severe("Row is not available. Rowindex = " + currentRow);
break;
}
if (nc == 0) {
// first column in table, start new row
beforeRow(facesContext, uiData);
// is the current row listed in the bodyrows attribute
if (ArrayUtils.contains(bodyrows, currentRow)) {
// close any preopened TBODY element first
if (bodyrowsCount != 0) {
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.startElement(HTML.TBODY_ELEM, uiData);
// Do not attach bodyrowsCount to the first TBODY
// element, because of backward compatibility
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element" + (bodyrowsCount == 0 ? "" : bodyrowsCount),
null);
bodyrowsCount++;
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
renderRowStart(facesContext, writer, uiData, styles, nr);
rowStartRendered = true;
}
List<UIComponent> children = null;
for (int j = 0, size = getChildCount(component); j < size; j++) {
if (children == null) {
children = getChildren(component);
}
UIComponent child = children.get(j);
if (child.isRendered()) {
boolean columnRendering = child instanceof UIColumn;
if (columnRendering) {
beforeColumn(facesContext, uiData, j);
}
encodeColumnChild(facesContext, writer, uiData, child, styles, nc * uiData.getChildCount() + j);
if (columnRendering) {
afterColumn(facesContext, uiData, j);
}
}
}
if (hasNewspaperTableSpacer(uiData)) {
// draw the spacer facet
if (nc < newspaperColumns - 1) {
renderSpacerCell(facesContext, writer, uiData);
}
}
}
if (rowStartRendered) {
renderRowEnd(facesContext, writer, uiData);
afterRow(facesContext, uiData);
}
}
if (bodyrowsCount != 0) {
// close the last TBODY element
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
}
#Override
protected void renderRowStart(FacesContext facesContext, ResponseWriter writer, UIData uiData, Styles styles, int rowStyleIndex) throws IOException {
writer.startElement(HTML.TR_ELEM, null); // uiData);
renderRowStyle(facesContext, writer, uiData, styles, rowStyleIndex);
Object obj = uiData.getRowData();
boolean isHide = false;
if (obj instanceof TableRow) {
isHide = ((TableRow) obj).isHide();
}
if (isHide) {
writer.writeAttribute("style", "display: none;", null);
}
Object rowId = uiData.getAttributes().get(org.apache.myfaces.shared.renderkit.JSFAttr.ROW_ID);
if (rowId != null) {
writer.writeAttribute(HTML.ID_ATTR, rowId.toString(), null);
}
}
private void encodeInnerHtmlUnknownRowCount(FacesContext facesContext, UIComponent component) throws IOException {
UIData uiData = (UIData) component;
ResponseWriter writer = facesContext.getResponseWriter();
Styles styles = getStyles(uiData);
Integer[] bodyrows = getBodyRows(facesContext, component);
int bodyrowsCount = 0;
int first = uiData.getFirst();
int rows = uiData.getRows();
int currentRow = first;
boolean isRowRendered = false;
while (true) {
uiData.setRowIndex(currentRow);
if (!uiData.isRowAvailable()) {
break;
}
isRowRendered = true;
// first column in table, start new row
beforeRow(facesContext, uiData);
// is the current row listed in the bodyrows attribute
if (ArrayUtils.contains(bodyrows, currentRow)) {
// close any preopened TBODY element first
if (bodyrowsCount != 0) {
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.startElement(HTML.TBODY_ELEM, uiData);
// Do not attach bodyrowsCount to the first TBODY element,
// because of backward compatibility
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element" + (bodyrowsCount == 0 ? "" : bodyrowsCount), null);
bodyrowsCount++;
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
renderRowStart(facesContext, writer, uiData, styles, currentRow);
List<UIComponent> children = null;
for (int j = 0, size = getChildCount(component); j < size; j++) {
if (children == null) {
children = getChildren(component);
}
UIComponent child = children.get(j);
if (child.isRendered()) {
boolean columnRendering = child instanceof UIColumn;
if (columnRendering) {
beforeColumn(facesContext, uiData, j);
}
encodeColumnChild(facesContext, writer, uiData, child, styles, j);
if (columnRendering) {
afterColumn(facesContext, uiData, j);
}
}
}
renderRowEnd(facesContext, writer, uiData);
afterRow(facesContext, uiData);
currentRow++;
if (rows > 0 && currentRow - first > rows) {
break;
}
}
if (!isRowRendered) {
// nothing to render, to get valid xhtml we render an empty dummy
// row
writer.startElement(HTML.TBODY_ELEM, uiData);
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element", null);
writer.startElement(HTML.TR_ELEM, uiData);
writer.startElement(HTML.TD_ELEM, uiData);
writer.endElement(HTML.TD_ELEM);
writer.endElement(HTML.TR_ELEM);
writer.endElement(HTML.TBODY_ELEM);
return;
}
if (bodyrowsCount != 0) {
// close the last TBODY element
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
}
private Integer[] getBodyRows(FacesContext facesContext, UIComponent component) {
Integer[] bodyrows = null;
String bodyrowsAttr = (String) component.getAttributes().get(JSFAttr.BODYROWS_ATTR);
if (bodyrowsAttr != null && !"".equals(bodyrowsAttr)) {
String[] bodyrowsString = StringUtils.trim(StringUtils.splitShortString(bodyrowsAttr, ','));
// parsing with no exception handling, because of JSF-spec:
// "If present, this must be a comma separated list of integers."
bodyrows = new Integer[bodyrowsString.length];
for (int i = 0; i < bodyrowsString.length; i++) {
bodyrows[i] = new Integer(bodyrowsString[i]);
}
} else {
bodyrows = ZERO_INT_ARRAY;
}
return bodyrows;
}
}
Use the empty css selector as suggested here, but with tr instead of td. This worked for me.
https://stackoverflow.com/a/19177424
As described here: https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
This selector works on all current browsers.
<style>
tr:empty {
display: none;
}
</style>
I've successfully hidden rows by putting a rendered attribute in all the <h:column> tags. The problem is that it suppresses the table headers. If your table has no table headers (they are <f:facet name="header"> tags embedded in the <h:column>), this approach might work for you.
I ended up using multiple lists in the backing bean, as I needed the table headers.