Header not showing in PDF document - openpdf

I am trying to add a header to each page in my document.
I am using OpenPDF 1.3.29 installed through Maven.
Here is a test program:
package test;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderTest {
public static void main(String[] args)
throws Exception {
Document doc = null;
PdfWriter writer = null;
try {
doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
writer = PdfWriter.getInstance(doc, new FileOutputStream("C:\\Tmp\\test.pdf"));
doc.open();
Font headerFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD,18);
HeaderFooter header = new HeaderFooter(new Phrase("Test Header",headerFont), false);
doc.setHeader(header);
doc.add(new Paragraph("Test Content"));
} finally {
try { doc.close(); } catch( Exception e ) { }
try { writer.close(); } catch( Exception e ) { }
}
}
}
The resulting PDF contains the content paragraph, but not the header.
Looking at the sample code, this seems like it should work.
Any idea what I did wrong?

I figured it out.
I needed to set the header and footer before calling open() on the document.
Also, I changed the header and footer to use Paragraph instead of Phrase. This is strange because the JavaDocs use Phrase.
Anyway, this code works as expected:
package test;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderTest {
public static void main(String[] args)
throws Exception {
Document doc = null;
PdfWriter writer = null;
try {
doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
writer = PdfWriter.getInstance(doc, new FileOutputStream("C:\\Tmp\\test.pdf"));
HeaderFooter header = new HeaderFooter(new Paragraph("Test Header"), false);
header.setAlignment(HeaderFooter.ALIGN_CENTER);
header.setBorder(Rectangle.NO_BORDER);
doc.setHeader(header);
HeaderFooter footer = new HeaderFooter(new Paragraph("This is page: "), true);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_RIGHT);
doc.setFooter(footer);
doc.open();
doc.add(new Paragraph("Test Content"));
} finally {
try { doc.close(); } catch( Exception e ) { }
try { writer.close(); } catch( Exception e ) { }
}
}
}

Related

Why is batik can't save .svg file using OutputStream?

I want to manipulate with existing .svg file from file system using library Batik by Apache. My goal is load .svg file, draw some shapes on it and than save final result on file system.
Now I have two classes. First class is able to load file .svg and draw shape on it, but don't able to save result. Second class is able to draw shape on new canvas and save result on file system.
This first class. I try to save final result using OutputStream, but it didn't work.
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.svg.GVTTreeBuilderAdapter;
import org.apache.batik.swing.svg.GVTTreeBuilderEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.concurrent.atomic.AtomicBoolean;
public class RedrawingSVG extends JFrame {
protected AtomicBoolean shown = new AtomicBoolean(false);
public static void main(String[] args) throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
RedrawingSVG redrawingSVG = new RedrawingSVG();
redrawingSVG.drawSvg();
}
public void drawSvg() throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
final JSVGCanvas canvas = new JSVGCanvas();
canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // to update it
canvas.setURI(new File("/home/ekuntsevich/Downloads/img.svg").toURI().toURL().toString());
canvas.addGVTTreeBuilderListener(new GVTTreeBuilderAdapter() {
public void gvtBuildCompleted(GVTTreeBuilderEvent e) {
synchronized (shown) {
shown.set(true); // No modifications be fore!!
shown.notifyAll();
}
}
});
getContentPane().add(canvas);
setSize(800, 400);
setVisible(true);
synchronized (shown) { // Strictly required to wait
while (shown.get() == false) {
try {
shown.wait(0);
} catch (Exception e) {
}
}
}
Document doc = canvas.getSVGDocument();
SVGGraphics2D svgGenerator = new SVGGraphics2D(doc);
svgGenerator.setPaint(Color.red);
svgGenerator.fill(new Rectangle(100, 100, 1000, 1000));
Element root = doc.getDocumentElement();
svgGenerator.getRoot(root);
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img2.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, true);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This second class.
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
public class TestSVGGen {
public void paint(Graphics2D g2d) {
g2d.setPaint(Color.red);
g2d.fill(new Rectangle(10, 10, 100, 100));
}
public static void main(String[] args) throws IOException {
// Get a DOMImplementation.
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// Ask the test to render into the SVG Graphics2D implementation.
TestSVGGen test = new TestSVGGen();
test.paint(svgGenerator);
// Finally, stream out SVG to the standard output using
// UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img3.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, useCSS);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Finally I want to combine capabilities this two classes. I want to have code for: loading .svg image -> drawing something over this image -> save result as .svg image on file system.
I resolved my issue. I looked through different signatures for method stream from class SVGGraphics2D and found out that there is has method with parameters suitable for my case. I used next method stream(Element svgRoot, Writer writer) for saving .svg image. Finally, instead svgGenerator.stream(out, true); I used svgGenerator.stream(root, out);. It works for me.
Fastest way to save SVGDOcument to File [for future generations :) ]
public static void saveSvgDocumentToFile(SVGDocument document, File file)
throws FileNotFoundException, IOException {
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8")) {
svgGenerator.stream(document.getDocumentElement(), out);
}
}

how to validate an xml string in java?

I have seen some examples here, which show how to validate an xml File (It´s workking), but my question is: How can I modify this code to validate an String
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.List;
import java.io.*;
import java.util.LinkedList;
import java.net.URL;
import java.sql.Clob;
import java.sql.SQLException;
public class Validate {
public String validaXML(){
try {
Source xmlFile = new StreamSource(new File("C:\\Users\\Desktop\\info.xml"));
URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
final List exceptions = new LinkedList();
validator.setErrorHandler(new ErrorHandler()
{
#Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
validator.validate(xmlFile);
} catch (SAXException ex) {
System.out.println( ex.getMessage());
return ex.getMessage().toString();
} catch (IOException e) {
System.out.println( e.getMessage());
return e.getMessage().toString();
}
return "Valid";
}
public static void main(String[] args) {
String res;
Validate val = new Validate();
res=val.validaXML();
System.out.println(res);
}
}
I have tried with this:
Source xmlFile = new StreamSource("<Project><Name>sample</Name></Project>");
It compiles, but I got this:
"no protocol: sample"
Thanks for reading I´ll apreciate you opinion
The reason why that doesnt work is the constructor your using is StreamSource(String systemId). The String constructor on StreamSource doesnt take xml.
Use the constructor StreamSource(Reader reader) and make an reader, such as
new StreamSource(new StringReader("xml here"))
or you can use the constructor StreamSource(InputStream inputStream) as
new StreamSource(new ByteArrayInputStream("xml here".getBytes()))

java.lang.RuntimeException: Failed : HTTP error code : 404

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("https://demo.docusign.net/restapi/v2/login_information");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.ops.tiaa-cref.org", 8080));
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("Username", "puviars#gmail.com");
conn.setRequestProperty("Password", "*******");
conn.setRequestProperty("IntegratorKey", "TIAC-e30cd896-cd8b-4cca-8551-86b8c51ea85a");
//conn.setRequestProperty("X-DocuSign-Authentication","{\"Username\":\"puviars#gmail.com\",\"Password\":\"********\",\"IntegratorKey\":\"TIAC-e30cd896-cd8b-4cca-8551-86b8c51ea85a\"}");
//String input = "{\"api_password\":\"false\",\"include_account_id_guid\":\"false\",\"login_settings\":\"none\"}";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("api_password", "true"));
params.add(new BasicNameValuePair("include_account_id_guid", "false"));
params.add(new BasicNameValuePair("login_settings", "all"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
//conn.setDoOutput(true);
//OutputStream os = conn.getOutputStream();
//os.write(input.getBytes());
//os.flush();
//conn.setRequestProperty("api_password","false");
//conn.setRequestProperty("include_account_id_guid","false");
//conn.setRequestProperty("login_settings","none");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
//
while invoking rest url via httpsurlconnection, the below code in eclispe IDE using run as java program.i am getting the below error:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 404
at NetClientGet.main(NetClientGet.java:71)
Please help me to resolve it. This code is just to hit demo url to login & fetch the details & then i will proceed to send the pdf documents to esign it.But if am using their interactive website i could get the response in JSON.
//

Read text file and display it in Jtable?

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.
My Text File: File Name(people.txt)
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
Names VARCHAR(500) NO
Address VARCHAR(500) NO
My Code So Far:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
static public void main(String[] arg){
JScrollPane scroll;
JTable table;
DefaultTableModel model;
String fname="people";
try
{
FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine,str = null;
//Read File Line By Line
String text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
String fline=myVector.elementAt(0).toString();
String[] sp=fline.split("\\s+");
for(String spt:sp){
System.out.println(spt);
//model = new DefaultTableModel(spt, ); // I dont know how to put the strings
into Jtable here
table = new JTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
int a=0;// for text box name
for(i=1;i<myVector.size();i++){
str=myVector.elementAt(i).toString();
String[] res =str.split("\\s+");
int k=0;
for(String st:res)
System.out.println(st);
k++;a++; }
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thank You.
File Content: (Each attribute is separated by a semicolon and each line is a record.)
Hello1;123
World1;234
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class FileToJTable {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new FileToJTable().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File(""/*Give your File Path here*/);
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Student> studentList = new ArrayList<Student>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Student student = new Student();
student.setName(splitData[0]);
student.setNumber(splitData[1]);
studentList.add(student);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("File to JTable");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Student {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Student> list = new ArrayList<Student>();
private String[] columnNames = {"Name", "Number"};
public void setList(List<Student> list) {
this.list = list;
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
case 1:
return list.get(rowIndex).getNumber();
default:
return null;
}
}
}
}
Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps
Define a DefaultTableModel:
String columns[] = { //Column Names// };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// specify number of columns
tableModel = new DefaultTableModel(0,2);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
Reading from text file:
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)
{
tableModel.addRow(line.split(", "));
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

In LWUIT, Component of another Form are not display

I am new on J2me developer using LWUIT library. I am making two forms: one is MainMidlet.java and another is UpgradeApp.java. Problem is that whatever the component add on UpgradeApp.java the component are not displayed. Please help me.
My Code as Follows.
MainMidlet.java
package com.sun.lwuit.jewelvicinity;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.table.TableLayout.Constraint;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
import javax.microedition.midlet.*;
public class MainMidlet extends MIDlet implements ActionListener
{
Form frm_Main;
public Button btn_main_Search, btn_main_WishList, btn_main_UpgradeApp, btn_main_Login, btn_main_NewUser,btn_main_Help, btn_main_AboutUs, btn_main_ContactUs, btn_main_Feedback, btn_main_Terms,btn_main_Privacy, btn_main_Exit;
public Image img_main_Search, img_main_Wishlist, img_main_UpgradeApp, img_main_Login, img_main_NewUser,img_main_Help, img_main_AboutUs, img_main_ContactUs, img_main_FeedBack, img_main_Terms,img_main_Privacy, img_main_Exit;
public Command cmd_Exit, cmd_Select;
public void startApp()
{
//--- Use for third soft Button
//Display.getInstance().setThirdSoftButton(true);
Display.init(this);
try
{
Resources theme = Resources.open("/LWUITtheme.res");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
}
catch (IOException io)
{
io.printStackTrace();
Dialog.show("Theme Exception", io.getMessage(), "Ok", null);
}
frm_Main = new Form("Jewel Vicinity");
try
{
img_main_Search = Image.createImage("/res/btn_main_search.png");
img_main_Wishlist = Image.createImage("/res/btn_main_wishlist.png");
img_main_UpgradeApp = Image.createImage("/res/btn_main_upgradeapp.png");
img_main_Login = Image.createImage("/res/btn_main_login.png");
img_main_NewUser = Image.createImage("/res/btn_main_newuser.png");
img_main_Help = Image.createImage("/res/btn_main_help.png");
img_main_AboutUs = Image.createImage("/res/btn_main_aboutus.png");
img_main_ContactUs = Image.createImage("/res/btn_main_contactus.png");
img_main_FeedBack = Image.createImage("/res/btn_main_feedback.png");
img_main_Terms = Image.createImage("/res/btn_main_terms.png");
img_main_Privacy = Image.createImage("/res/btn_main_privacy.png");
img_main_Exit = Image.createImage("/res/btn_main_exit.png");
}
catch (IOException io)
{
io.printStackTrace();
Dialog.show("Image not Found!", io.getMessage(), "Ok", null);
}
btn_main_Search = new Button("Search", img_main_Search);
btn_main_WishList = new Button("Wish List", img_main_Wishlist);
btn_main_UpgradeApp = new Button("Upgrade", img_main_UpgradeApp);
btn_main_Login = new Button("Login", img_main_Login);
btn_main_NewUser = new Button("NewUser", img_main_NewUser);
btn_main_Help = new Button("help", img_main_Help);
btn_main_AboutUs = new Button("About Us", img_main_AboutUs);
btn_main_ContactUs = new Button("Contact Us", img_main_ContactUs);
btn_main_Feedback = new Button("FeedBack", img_main_FeedBack);
btn_main_Privacy = new Button("Privacy", img_main_Privacy);
btn_main_Terms = new Button("Terms", img_main_Terms);
btn_main_Exit = new Button("Exit", img_main_Exit);
lbl_main_WishList.setTextPosition(Component.BOTTOM);
lbl_main_WishList.setAlignment(Component.CENTER);
lbl_main_WishList.getStyle().setMargin(0, 30, 0, 30);
lbl_main_UpgradeApp = new Label("Upgrade");
cmd_Exit = new Command("Exit", 1);
cmd_Select = new Command("Select");
GridLayout grd_MenuLayout = new GridLayout(4, 3);
frm_Main.setTitle("Menu");
frm_Main.setLayout(grd_MenuLayout);
frm_Main.setScrollableY(true);
//---- Add Button On Main Form
frm_Main.addComponent(btn_main_Search);
frm_Main.addComponent(btn_main_WishList);
frm_Main.addComponent(btn_main_UpgradeApp);
frm_Main.addComponent(btn_main_Login);
frm_Main.addComponent(btn_main_NewUser);
frm_Main.addComponent(btn_main_Help);
frm_Main.addComponent(btn_main_AboutUs);
frm_Main.addComponent(btn_main_ContactUs);
frm_Main.addComponent(btn_main_Feedback);
frm_Main.addComponent(btn_main_Terms);
frm_Main.addComponent(btn_main_Privacy);
frm_Main.addComponent(btn_main_Exit);
frm_Main.addCommand(cmd_Select);
frm_Main.addCommand(cmd_Exit);
//frm_Main.setCommandListener(this);
frm_Main.addCommandListener(this);
frm_Main.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae)
{
Command cmd = ae.getCommand();
String strcmdName = cmd.getCommandName();
if(strcmdName.equals("Exit"))
{
notifyDestroyed();
}
if (strcmdName.equals("Select"))
{
if(btn_main_Search.hasFocus())
{
//Dialog.show("Search", "Search", "Ok", null);
Form frm_Search = new Form("Search");
frm_Search.show();
}
if(btn_main_UpgradeApp.hasFocus())
{
Form UpgradeApp = new Form("Upgrade App");
UpgradeApp.show();
}
}
}
}
UpgradeApp.java
package com.sun.lwuit.jewelvicinity;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.FlowLayout;
public class UpgradeApp extends Form implements ActionListener
{
Label lbl_UpgradeApp;
Command cmd_Yes, cmd_No;
Form frm_UpgradeApp;
public UpgradeApp()
{
Display.init(this);
frm_UpgradeApp = new Form("Upgrade Application");
lbl_UpgradeApp = new Label("The New Version of Jewel.");
cmd_Yes = new Command("Yes", 1);
cmd_No = new Command("No", 2);
FlowLayout flw_UpgradeLayout = new FlowLayout(CENTER);
frm_UpgradeApp.setLayout(flw_UpgradeLayout);
frm_UpgradeApp.addComponent(lbl_UpgradeApp);
frm_UpgradeApp.addCommand(cmd_No);
frm_UpgradeApp.addCommand(cmd_Yes);
frm_UpgradeApp.addCommandListener(this);
frm_UpgradeApp.setVisible(true);
frm_UpgradeApp.show();
}
public void actionPerformed(ActionEvent evt)
{
}
}
From a brief review you seem to be calling Display.init(this); in a form subclass. I suggest you use a debugger and walk through the code.

Resources