I work on a LWUIT project that aims to computerize an Arabic book . That means each page of the
mentioned book accessed by a specific button
returns
To do that I created a form , array of buttons, and a textarea.
The setText( ) method of textarea widget is used to involve each page of the book
How?
When a button pressed
the setText( ) changes it's string according to the content of the
required page
returns
At the end of the project a problem of formatting faces me .
The book page's contents (Strings ) are unformatted.
returns
to solve the problem I tried a LWUIT HtmlComponent instead of textArea in order to format using
html tags , but it takes much of memory
(at least it cost more than 700 kb for an application).
So I wouldn't be able include all the pages of the book by this way.
returns
This my first trial
import javax.microedition.midlet.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.*;
public class Arabic_Lang extends MIDlet {
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form main_form = new com.sun.lwuit.Form();
final com.sun.lwuit.Form f = new com.sun.lwuit.Form();
final com.sun.lwuit.TextArea txt1 = new com.sun.lwuit.TextArea();
f.addComponent(txt1);
final com.sun.lwuit.Button l[]= new com.sun.lwuit.Button [3];
final com.sun.lwuit.Button inter = new com.sun.lwuit.Button("inter");
final com.sun.lwuit.Form jjj8 = new com.sun.lwuit.Form();
jjj8.setTitle( "اللغة العربية");
jjj8.getStyle().setBgColor(0x006699);
jjj8.setScrollableX(true);
int i;
for(i=0;i<3;i++)
{
l[i] =new com.sun.lwuit.Button();
l[i].getStyle().setBgColor(0xFFF66);
main_form.addComponent(l[i]);
main_form.setScrollable (true);
main_form.setScrollableX(false);
}
l[0].setText("");
l[0].getStyle().setBgColor(0xffff00);
l[0].setText("arabic");
l[1].setText("arabic");
l[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
}
});
l[1].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
f.show();
}
});
jjj8.addComponent(inter);
inter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
main_form.show();
}
}
);
jjj8.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
returns
And this is my trial to use htmlComponent
returns
import com.sun.lwuit.layouts.*;
import javax.microedition.midlet.*;
public class HelloLWUITMidlet3 extends MIDlet
{
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form form = new com.sun.lwuit.Form("");
final com.sun.lwuit.html.HTMLComponent htmlC = new com.sun.lwuit.html.HTMLComponent( );
htmlC.setRTL(true);
htmlC.setBodyText("هذه لغة عربية","UTF-8" );
form.addComponent(htmlC);
BorderLayout bl = new BorderLayout();
form.setScrollable(true);
form.show( );
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
Store the pages of the book as HTML files in your src dir (in the jar root) and load them directly into the HTMLComponent as is shown in the LWUITDemo.
Related
I'm using a TextField to display the path of a directory the user has opened in my application.
Currently, if the path can't fit inside the TextField, upon focusing away/clicking away from this control, it looks like as if the path has become truncated:
I want the behaviour of TextField set such that when I focus away from it, the path shown inside automatically scrolls to the right and the user is able to see the directory they've opened. I.e. something like this:
How can I achieve this? I've tried adapting the answer given from here
as follows in initialize() method in my FXML Controller class:
// Controller class fields
#FXML TextField txtMoisParentDirectory;
private String moisParentDirectory;
// ...
txtMoisParentDirectory.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldStr, String newStr) {
moisParentDirectory = newStr;
txtMoisParentDirectory.selectPositionCaret(moisParentDirectory.length());
txtMoisParentDirectory.deselect();
}
});
However it doesn't work.
Your problem is based on two events, the length of the text entered and the loss of focus, so to solve it I used the properties textProperty() and focusedProperty() and here is the result :
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Launcher extends Application{
private Pane root = new Pane();
private Scene scene;
private TextField tf = new TextField();
private TextField tft = new TextField();
private int location = 0;
#Override
public void start(Stage stage) throws Exception {
scrollChange();
tft.setLayoutX(300);
root.getChildren().addAll(tft,tf);
scene = new Scene(root,400,400);
stage.setScene(scene);
stage.show();
}
private void scrollChange(){
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
location = tf.getText().length();
}
});
tf.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(!newValue){
Platform.runLater( new Runnable() {
#Override
public void run() {
tf.positionCaret(location);
}
});
}
}
});
}
public static void main(String[] args) {
launch(args);
}
}
And concerning the Platform.runLater I added it following this answer Here I don't know why it does not work without it, good luck !
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
int location = tf.getText().length();
Platform.runLater(() -> {
tf.positionCaret(location);
});
}
});
this is also work
Since the other answers didn't work for me here is a solution that should do the trick:
private TextField txtField;
// Both ChangeListeners just call moveCaretToEnd(), we need them both because of differing data types we are listening to
private final ChangeListener<Number> caretChangeListener = (observable, oldValue, newValue) -> moveCaretToEnd();
private final ChangeListener<String> textChangeListener = (observable, oldValue, newValue) -> moveCaretToEnd();
// This method moves the caret to the end of the text
private void moveCaretToEnd() {
Platform.runLater(() -> {
txtField.deselect();
txtField.end();
});
}
public void initialize() {
// Immediatly add the listeners on initialization (or once you created the TextField if you are not using FXML)
txtField.caretPositionProperty().addListener(caretChangeListener);
txtField.textProperty().addListener(textChangeListener);
txtField.focusedProperty().addListener((observable, oldValue, isFocused) -> {
if (isFocused) {
// once the TextField has been focused remove the listeners to enable normal editing of the text
txtField.caretPositionProperty().removeListener(caretChangeListener);
txtField.textProperty().removeListener(textChangeListener);
} else {
// when the focus is lost apply the listeners again
moveCaretToEnd();
txtField.caretPositionProperty().addListener(caretChangeListener);
txtField.textProperty().addListener(textChangeListener);
}
});
}
i am creating notepad and i have given the option of word wrap as in notepad
but when i write
textArea.setLineWrap(true);
than it gives me the error as shown
cannot Find Symbol
Symbol: method setLineWrap(boolean)
Location: Variable textArea of type TextArea
even when i press '.' and dropdown came for textArea but it doesnt shows setLineWrap boolean method
here is my code so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test3;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Test3 extends JFrame{
private final JMenu Format;
private final JMenuItem Word;
private final TextArea textArea = new TextArea("", 0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
public Test3(){
setLayout(new FlowLayout()); //Default layout
JMenuBar menubar=new JMenuBar();
setJMenuBar(menubar);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textArea);
Format=new JMenu("Format");
Word=new JMenuItem("Word wrap");
Format.add(Word);
menubar.add(Format);
event1 e1 =new event1 ();
Word.addActionListener(e1);
}
public class event1 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
//textArea.setLineWrap(true);
//textArea.setWrapStyleWord(true);
}
}
public static void main(String []args){
Test3 t=new Test3();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setTitle("Notepad");
t.setVisible(true);
t.setSize(1280,786);
}
}
I Have changed your code little bit.
Instead of TextArea I have used JTextArea
and a JScrollPane to wrap the JTextArea
class Test3 extends JFrame {
private final JMenu Format;
private final JMenuItem Word;
private final JTextArea textArea = new JTextArea("", 0, 0);
public Test3() {
setLayout(new FlowLayout()); //Default layout
JScrollPane scroll = new JScrollPane (textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(scroll);
Format = new JMenu("Format");
Word = new JMenuItem("Word wrap");
Format.add(Word);
menubar.add(Format);
event1 e1 = new event1();
Word.addActionListener(e1);
}
public class event1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
}
}
public static void main(String[] args) {
Test3 t = new Test3();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setTitle("Notepad");
t.setVisible(true);
t.setSize(1280, 786);
}
}
Instead of using TextArea use JTextArea.
class test2{
private final JMenu Format;
private final JMenuItem Word;
private final JTextArea textArea = new JTextArea("", 0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
test2(){
setLayout (new FlowLayout()); //Default layout
JMenuBar menubar=new JMenuBar();
setJMenuBar(menubar);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textArea);
format=new JMenu("Format");
Word=new JMenuItem("Word wrap");
format.add(Word);
menubar.add(format);
event1 e1 =new event1 ();
Word.addActionListener(e18);
}
public class event18 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
}
}
public static void main(String []args){
Test2 t=new Test2();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setTitle("Notepad");
t.setVisible(true);
t.setSize(1280,786);
}
}
I'm creating a TableView to show information regarding a list of custom objects (EntityEvents).
The table view must have 2 columns.
First column to show the corresponding EntityEvent's name.
The second column would display a button. The button text deppends on a property of the EntityEvent. If the property is ZERO, it would be "Create", otherwise "Edit".
I managed to do it all just fine, except that I can't find a way to update the TableView line when the corresponding EntityEvent object is changed.
Very Important: I can't change the EntityEvent class to use JavaFX properties, since they are not under my control. This class uses PropertyChangeSupport to notify listeners when the monitored property is changed.
Note:
I realize that adding new elements to the List would PROBABLY cause the TableView to repaint itself, but that is not what I need. I say PROBABLY because I've read about some bugs that affect this behavior.
I tried using this approach to force the repaint, by I couldn't make it work.
Does anyone knows how to do it?
Thanks very much.
Here is a reduced code example that illustrates the scenario:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Main extends Application {
//=============================================================================================
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport m_NamePCS = new PropertyChangeSupport(this);
private int m_ActionCounter;
private PropertyChangeSupport m_ActionCounterPCS = new PropertyChangeSupport(this);
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
m_NamePCS.firePropertyChange("Name", lastName, m_Name);
}
public void addNameChangeListener(PropertyChangeListener listener) {
m_NamePCS.addPropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
m_ActionCounterPCS.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
public void addActionCounterChangeListener(PropertyChangeListener listener) {
m_ActionCounterPCS.addPropertyChangeListener(listener);
}
}
//=============================================================================================
private class AddPersonCell extends TableCell<EntityEvent, String> {
Button m_Button = new Button("Undefined");
StackPane m_Padded = new StackPane();
AddPersonCell(final TableView<EntityEvent> table) {
m_Padded.setPadding(new Insets(3));
m_Padded.getChildren().add(m_Button);
m_Button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
// Do something
}
});
}
#Override protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(m_Padded);
m_Button.setText(item);
}
}
}
//=============================================================================================
private ObservableList<EntityEvent> m_EventList;
//=============================================================================================
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Table View test.");
VBox container = new VBox();
m_EventList = FXCollections.observableArrayList(
new EntityEvent("Event 1", -1),
new EntityEvent("Event 2", 0),
new EntityEvent("Event 3", 1)
);
final TableView<EntityEvent> table = new TableView<EntityEvent>();
table.setItems(m_EventList);
TableColumn<EntityEvent, String> eventsColumn = new TableColumn<>("Events");
TableColumn<EntityEvent, String> actionCol = new TableColumn<>("Actions");
actionCol.setSortable(false);
eventsColumn.setCellValueFactory(new Callback<CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<EntityEvent, String> p) {
EntityEvent event = p.getValue();
event.addActionCounterChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
// TODO: I'd like to update the table cell information.
}
});
return new ReadOnlyStringWrapper(event.getName());
}
});
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<EntityEvent, String> ev) {
String text = "NONE";
if(ev.getValue() != null) {
text = (ev.getValue().getActionCounter() != 0) ? "Edit" : "Create";
}
return new ReadOnlyStringWrapper(text);
}
});
// create a cell value factory with an add button for each row in the table.
actionCol.setCellFactory(new Callback<TableColumn<EntityEvent, String>, TableCell<EntityEvent, String>>() {
#Override
public TableCell<EntityEvent, String> call(TableColumn<EntityEvent, String> personBooleanTableColumn) {
return new AddPersonCell(table);
}
});
table.getColumns().setAll(eventsColumn, actionCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// Add Resources Button
Button btnInc = new Button("+");
btnInc.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("+ clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() + 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
// Add Resources Button
Button btnDec = new Button("-");
btnDec.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("- clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() - 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
container.getChildren().add(table);
container.getChildren().add(btnInc);
container.getChildren().add(btnDec);
Scene scene = new Scene(container, 300, 600, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
//=============================================================================================
public Main() {
}
//=============================================================================================
public static void main(String[] args) {
launch(Main.class, args);
}
}
Try the javafx.beans.property.adapter classes, particularly JavaBeanStringProperty and JavaBeanIntegerProperty. I haven't used these, but I think you can do something like
TableColumn<EntityEvent, Integer> actionCol = new TableColumn<>("Actions");
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, Integer> ev) {
return new JavaBeanIntegerPropertyBuilder().bean(ev.getValue()).name("actionCounter").build();
});
// ...
public class AddPersonCell extends TableCell<EntityEvent, Integer>() {
final Button button = new Button();
public AddPersonCell() {
setPadding(new Insets(3));
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
button.setOnAction(...);
}
#Override
public void updateItem(Integer actionCounter, boolean empty) {
if (empty) {
setGraphic(null);
} else {
if (actionCounter.intValue()==0) {
button.setText("Create");
} else {
button.setText("Add");
}
setGraphic(button);
}
}
}
As I said, I haven't used the Java bean property adapter classes, but the idea is that they "translate" property change events to JavaFX change events. I just typed this in here without testing, but it should at least give you something to start with.
UPDATE: After a little experimenting, I don't think this approach will work if your EntityEvent is really set up the way you showed it in your code example. The standard Java beans bound properties pattern (which the JavaFX property adapters rely on) has a single property change listener and an addPropertyChangeListener(...) method. (The listeners can query the event to see which property changed.)
I think if you do
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private int m_ActionCounter;
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
pcs.firePropertyChange("name", lastName, m_Name);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
pcs.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
}
it will work with the adapter classes above. Obviously, if you have existing code calling the addActionChangeListener and addNameChangeListener methods you would want to keep those existing methods and the existing property change listeners, but I see no reason you can't have both.
I'm working in java me. I'm trying to switch between visual designs using ok Commands and back Commands. I have a form displayable which I named formA in my main class A.java and a formB in another class B.java . I used an ok Command in formA which on selection, is supposed to take the user to formB.
I created a reference to B.java in my main class A.java constructor
B b;
// A.java constructor
public A() {
b = new B(this);
}
now I could call the getFormB method from my commandAction in formA. Then I added a backCommand which is supposed to take me back to formA in A.java and I tried creating a reference in B.java same way I did in A.java but I get a SecurityException MIDletManager ERROR at runtime. I was adviced to add an A attribute to my B class and receive the instance as a constructor parameter so I can call the getFormA() method to switch to formA in A.java
A a;
B(A a) {
this.a = a;
}
in command action I did ds on the backCommand:
switchDisplayable ( null , a.getFormA());
This compiled, but at runtime on hitting the BACK key from formB I get java/lang/NullPointerException.
Can anyone tell me why this happended and how to fix it please. All I'm trying to acheive is the backCommand to take the user back to formA from formB
If your A class extends Form or your A class is Displayable, then in the Back command, you can just tell switchDisplayable(null, a).
If your A class is not a Form, then make sure your A class has the following methods:
public Form getFormA() {
return ...; // return the `Form` here so you will not get NullPointerException
}
UPDATE:
If you're using NetBeans, you can open Flow tab and drag backCommand from formB to formA. NetBeans will generate the required code for you.
If you code by hand, then it will looks like the following:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA;
private Form formB;
private Command formA_next;
private Command formB_back;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new Form("Form A");
formA_next = new Command("Next", Command.SCREEN, 0);
formA.addCommand(formA_next);
formA.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formA_next) {
display.setCurrent(formB);
}
}
});
formB = new Form("Form B");
formB_back = new Command("Back", Command.BACK, 0);
formB.addCommand(formB_back);
formB.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formB_back) {
display.setCurrent(formA);
}
}
});
}
display.setCurrent(formA);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
I don't know how you code your Form, but it seems that a is null. Maybe you can show me the full code. Passing this in constructor is generally not recommended. By the way, you still need a 'main' class that extends MIDlet right? Then there will be 3 classes, such as:
ExampleMiddlet.java (this is where you put your MIDlet lifecycle, such as startApp(), pauseApp(), etc):
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA, formB;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new FormA(this);
formB = new FormB(this);
}
display.setCurrent(formA);
}
public Form getFormA() {
return formA;
}
public Form getFormB() {
return formB;
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
FormA.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormA extends Form {
private Command cmdNext;
public FormA(final ExampleMidlet midlet) {
super("Form A");
append("This is form A.");
cmdNext = new Command("Next", Command.SCREEN, 0);
addCommand(cmdNext);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormB());
}
});
}
}
FormB.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormB extends Form {
private Command cmdBack;
public FormB(final ExampleMidlet midlet) {
super("Form B");
append("This is form B.");
cmdBack = new Command("Back", Command.SCREEN, 0);
addCommand(cmdBack);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormA());
}
});
}
}
I have to link an excel file with a application software which I am developing.The excel file will contain questionnaire for conducting surveys.I have this code which is only able to open a Jpanel to select the file.After I select the file nothing is happening.I wanted to be able to generate a template based on the questions that are in the excel file (like extracting the questions from the excel file and creating a template from it) and which I have to upload on the web later.could you please help me with this?
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class SelectFile extends JFrame{
public static void main(String[]args){
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Select File for Linking");
frame.setSize(400, 100);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
text.setBounds(20,20,120,20);
b.setBounds(150,20,80,20);
// b.setText("<html><font color='blue'><u>Select File</u></font></html>");
b.setHorizontalAlignment(SwingConstants.LEFT);
//b.setBorderPainted(false);
//b.setOpaque(false);
// b.setBackground(Color.lightGray);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new OnlyExt());
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
}
}
});
container.add(text);
container.add(b);
frame.setVisible(true);
}
}
class OnlyExt extends javax.swing.filechooser.FileFilter{
public boolean accept(File file) {
if (file.isDirectory()) return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".xls"));
}
public String getDescription() { return "Excel ( *.xls)"; }
}
Apache POI http://poi.apache.org/ provides an API for reading / writing Excel Files.
Look over this source for some tips.
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.EmptyBorder;
public class SelectFile {
public static void main(String[]args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("Select File for Linking");
// don't use null layouts.
//frame.setLayout(null);
// create a panel so we can add a border
JPanel container = new JPanel(new FlowLayout(3));
container.setBorder(new EmptyBorder(10,10,10,10));
frame.setContentPane(container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// instead call pack() after components are added
//frame.setSize(400, 100);
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
// irrelevant unless button stretched by layout
//b.setHorizontalAlignment(SwingConstants.LEFT);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
String desc = "Excel ( *.xls)";
String[] types = {".xls"};
fc.addChoosableFileFilter(
new FileNameExtensionFilter(desc, types));
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
try {
// 1.6+
Desktop.getDesktop().edit(file);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
container.add(text);
container.add(b);
frame.pack();
frame.setVisible(true);
}
});
}
}
BTW - The JFrame here would probably be better converted to a JDialog or JOptionPane.