Lwuit touch screen strange behaviour - java-me

I am making an application using LWUIT.
There is a form
There is a list embedded on the form.
The list has 5 elements.
Initially, when I first load the app, if I choose the 1st element, 2nd gets chosen; when I choose the second the 3rd gets chose and and so on (Weird!)
I am not able to click any button on the screen either
next what I do is, shift to a different from using arrow keys (of the keyboard... I am running the app on a simulator btw)
Then I come back to the first form and now everything works as expected(no weird behaviour).
What could be the issue?
I am using Sun Java Micro Edition SDK 3.0 (default touch screen for testing)
My code is:
List dummy = new List();
dummy.addItem("wewerwer");
dummy.addItem("wewerdswer");
dummy.addItem("wewqweerwer");
dummy.addItem("dscxwewerwer");
dummy.addItem("jhgwewerwer");
mainListForm.setLayout(new BorderLayout());
mainListForm.addComponent(BorderLayout.CENTER,dummy);
mainListForm.show();
What could possible be going wrong here?
UPDATE 1
I think there is a bug here. I have attached the complete code below along with the screen shot
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class Demo extends MIDlet implements ActionListener {
private Form mForm;
List abc;
public void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/Test.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0])
);
} catch (Exception e){
System.out.println(e.toString());
}
if (mForm == null) {
Button click = new Button("Press me!");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("I have been pressed");
}
});
abc = new List();
abc.addItem("Str1");
abc.addItem("Str2");
abc.addItem("Str3");
abc.addItem("Str4");
abc.addItem("Str5");
abc.addItem("Str6");
Form f = new Form("Hello, LWUIT!");
abc.addActionListener(this);
f.addComponent(abc);
Command exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.addCommandListener(this);
f.addComponent(click);
f.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
System.out.println(abc.getSelectedIndex());
}
}
So now when I click on 'Str1' of the list Str2 gets selected and so on.
IDE: Netbeans
Emulator: Default Touch screen phone

On the action event set the list to active again after the event by invoking setHandlesInput(true)

OK....so this is how you resolve it.
After the form is displayed remove the list from the form and again add it to the form and then repaint the form.
Earlier Code
1) form.addComponenet(BorderLayout.center,list);
2) form.show();
Word Around for the problem
1)form.addComponenet(BorderLayout.center,list);
2)form.show();
3)form.setScrollable(false);
I know its kind of strange, but this way the list index selection works smooth for touch screen phones.

Related

KeyListener doesn't work, my Jframe can not recognise my keyboard

I dont know why my application can not detect my keyboard.
Application its a JFrame who implements SerialPortEventListener and KeyListener.
In the Jframe of my application I have 1 Tabbed Pane with 2 Panels.
When I press some buttons it doesn't work( NOTHING IN THE OUTPUT).
I will show you my code(Not all, just the most importants parts) :
MY CLASS:
public class java_arduino_frame extends javax.swing.JFrame implements SerialPortEventListener, KeyListener {
MY KEYS FUNCTIONS:
public void keyTyped(KeyEvent e){
throw new UnsupportedOperationException("not yet");
}
public void keyPressed(KeyEvent e){
int keyCode;
keyCode = e.getKeyCode();
System.out.println(keyCode);
}
public void keyReleased(KeyEvent e){
throw new UnsupportedOperationException("not yet");
}
MY CONSTRUCTOR OF MY CLASS:
public java_arduino_frame() {
getContentPane().setBackground( Color.LIGHT_GRAY );
initComponents();
addKeyListener(this);
}
THE MAIN
public static void main(String args[]) {
strong text
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new java_arduino_frame().setVisible(true);
}
});
A KeyListener will only respond when the component it is registered IS focusable AND has focus, since clicking a button will cause the focus to be transferred to the button, the frame will no longer have input focus.
It's also unlikely that the frame would be able to receive keyboard focus directly either.
As a general rule of thumb, you should be using the Key Bindings API instead, which will provide you with the ability to over come the focus realated issues.
Depending on what you're doing, you might also consider using a JTextArea or a JTextField with a DocumentListener, assuming you want to send characters to through the serial connection. Have a look at Listening for Changes on a Document for more details

Incompatibility with Java 7

For the life of me, I cannot figure out why this program does not work in Java 7. I've run it with no problems in using Java 6, but as soon as I run it with Java 7, it doesn't work.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HelloWorld implements ActionListener {
JButton button;
boolean state;
public HelloWorld(){
init();
state = false;
System.out.println("state - "+state);
while (true){
if (state == true){
System.out.println("Success");
}
}
}
private void init(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Button");
button.addActionListener(this);
frame.add(button);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if (source == button){
state = !state;
System.out.println("state - "+state);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new HelloWorld();
}
}
Using Java 6, if I press the button, it will print out the phrase "Success" until I hit the button again. Using Java 7 registers that the button was pressed and the value of state was changed to true, but the phrase "Success" is never printed. What's going on?
Add volatile to the field declaration.
Without volatile, changes in the field are not guaranteed to be visible on other threads.
In particular, the JITter is free to believe that the field never changes on the main thread, allowing it to remove the if entirely.
When you show the JFrame
frame.setVisible(true);
The Java Show the window and stop the execution on this line.
You configured the window to exit on close:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This program will terminate after you close the window.
So the code after the init() call will never be executed.

repainting multiple JPanel from a single "control" panel

so i'm trying to set up an application where i have multiple panels inside a jframe. lets say 3 of them are purely for display purposes, and one of them is for control purposes. i'm using a borderLayout but i don't think the layout should really affect things here.
my problem is this: i want the repainting of the three display panels to be under the control of buttons in the control panel, and i want them to all execute in sync whenever a button on the control panel is pressed. to do this, i set up this little method :
public void update(){
while(ButtonIsOn){
a.repaint();
b.repaint()
c.repaint();
System.out.println("a,b, and c should have repainted");
}
}
where a,b, and c are all display panels and i want a,b,and c to all repaint continously until i press the button again. the problem is, when i execute the loop, the message prints in an infinite loop, but none of the panels do anything, ie, none of them repaint.
i've been reading up on the event dispatch thread and swing multithreading, but nothing i've found so far has really solved my problem. could someone give me the gist of what i'm doing wrong here, or even better, some sample code that handles the situation i'm describing? thanks...
The java.util.concurrent package provides very powerful tools for concurrent programing.
In the code below, I make use of a ReentrantLock (which works much like the Java synchronized keyword, ensuring mutually exclusive access by multiple threads to a single block of code). The other great thing which ReentrantLock provides are Conditions, which allow Threads to wait for a particular event before continuing.
Here, RepaintManager simply loops, calling repaint() on the JPanel. However, when toggleRepaintMode() is called, it blocks, waiting on the modeChanged Condition until toggleRepaintMode() is called again.
You should be able to run the following code right out of the box. Pressing the JButton toggle repainting of the JPanel (which you can see working by the System.out.println statements).
In general, I'd highly recommend getting familiar with the capabilities that java.util.concurrent offers. There's lots of very powerful stuff there. There's a good tutorial at http://docs.oracle.com/javase/tutorial/essential/concurrency/
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RepaintTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel()
{
#Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
// print something when the JPanel repaints
// so that we know things are working
System.out.println( "repainting" );
}
};
frame.add( panel );
final JButton button = new JButton("Button");
panel.add(button);
// create and start an instance of our custom
// RepaintThread, defined below
final RepaintThread thread = new RepaintThread( Collections.singletonList( panel ) );
thread.start();
// add an ActionListener to the JButton
// which turns on and off the RepaintThread
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
thread.toggleRepaintMode();
}
});
frame.setSize( 300, 300 );
frame.setVisible( true );
}
public static class RepaintThread extends Thread
{
ReentrantLock lock;
Condition modeChanged;
boolean repaintMode;
Collection<? extends Component> list;
public RepaintThread( Collection<? extends Component> list )
{
this.lock = new ReentrantLock( );
this.modeChanged = this.lock.newCondition();
this.repaintMode = false;
this.list = list;
}
#Override
public void run( )
{
while( true )
{
lock.lock();
try
{
// if repaintMode is false, wait until
// Condition.signal( ) is called
while ( !repaintMode )
try { modeChanged.await(); } catch (InterruptedException e) { }
}
finally
{
lock.unlock();
}
// call repaint on all the Components
// we're not on the event dispatch thread, but
// repaint() is safe to call from any thread
for ( Component c : list ) c.repaint();
// wait a bit
try { Thread.sleep( 50 ); } catch (InterruptedException e) { }
}
}
public void toggleRepaintMode( )
{
lock.lock();
try
{
// update the repaint mode and notify anyone
// awaiting on the Condition that repaintMode has changed
this.repaintMode = !this.repaintMode;
this.modeChanged.signalAll();
}
finally
{
lock.unlock();
}
}
}
}
jComponent.getTopLevelAncestor().repaint();
You could use SwingWorker for this. SwingWorker was designed to perform long running tasks in the background without blocking the event dispatcher thread. So, you need to extend SwingWorker and implement certain methods that will make sense to you. Note that all long running action should happen in the doInBackground() method, and the Swing UI elements should be updated only on the done() method.
So here is an example :
class JPanelTask extends SwingWorker<String, Object>{
JPanel panel = null;
Color bg = null;
public JPanelTask(JPanel panel){
this.panel = panel;
}
#Override
protected String doInBackground() throws Exception {
//loooong running computation.
return "COMPLETE";
}
#Override
protected void done() {
panel.repaint();
}
}
Now, in your "control" button's action performed event, you could do the following :
controlButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanelTask task1 = new JPanelTask(panel1);
task1.execute();
JPanelTask task2 = new JPanelTask(panel2);
task2.execute();
//so on..
}
});
Another way is using javax.swing.Timer. Timer helps you to fire a change to your ui elements in a timely fasthion.This may not be the most appropriate solution. But it gets the work done too.
Again you should be careful about updating UI elements in right places.

using lwuit UI library I am not destroy j2me application

I am working with j2me using lwuit I have one problem is that
when I am startApp() inside midlet I first set Display.init(this)
and run application lwuit work good but when I am using Form inside startApp() event in midlet it good work but in this form actionevent I am call new form and in this new form
I put one back command when I pressed it it does not move on main midlet
please help how know lwuit use
import javax.microedition.MIDlet;
import some lwuit UILibrary
public class mainMiddlet extends MIDlet implement ActionListner
{
public mainMiddlet(){
try{
Display.init(this);
//somthing is here
form=new Form();
form.addActionListener(this);
}catch(Exception e){}
}
public void actionperformed(ActionEven ae){
//here i call new form
//in action event of this form
new form().show();
}
//here some middlet default method
}
public class newForm extends Form {
//in this form I am put one command back and when i am pressed it
// I call mainMiddlet but it throw error internal application java.lang.nullpointer
// can I back on mainmiddlet from on form to another form
// my main problem is I am not move on mainmiddlet for exit middlet because destoryall()
// is method of middlet
}
Its just simple. You can call the show() method inside next form back command. For example,
MainMidlet.java
// create the midlet and write inside of the midlet
final Form form = new Form();
form.addCommand(new Command("Next") {
public void actionPerformed(ActionEvent evt) {
new NewForm(form).show();
}
});
NewForm.java
// create the NewForm class and write inside of the class
public NewForm(final Form form) {
// Constructor
addCommand(new Command("Back") {
public void actionPerformed(ActionEvent evt) {
form.show();
}
});
}

How to use QLPreviewController in a non-modal way? Why does my code not work?

I have QLPreviewController up and running but I'm using PresentModalViewController() to show the QLPreviewController directly. For reasons beyond explanation, I would like to have my own UIViewController which will create its own view and within that view I would like to use the QLPreviewController. Should be easy I thought, but the code below just does nothing. The QLPreviewControllers ViewDidAppear never gets called. (In my example below, PreviewController inherits from QLPreviewController and encapsulates delegate, preview item and source).
Can somebody explain what is wrong with the code below (besides the fact that it is pointless :-))?
Oh, yeah: in my test scenario, I present the controller below modally. It shows up but witout the preview.
public class OuterPreviewController : UIViewController
{
public OuterPreviewController (QLPreviewControllerDataSource oDataSource) : base()
{
this.oDataSource = oDataSource;
}
private PreviewController oPreviewController;
private QLPreviewControllerDataSource oDataSource;
public override void LoadView ()
{
this.View = new UIView();
this.View.Frame = new RectangleF(0, 0, 500, 500);
this.View.BackgroundColor = UIColor.Red;
}
public override void ViewDidAppear (bool animated)
{
// Code execution comes her. No errors, no issues.
base.ViewDidAppear (animated);
this.oPreviewController = new PreviewController();
this.oPreviewController.DataSource = this.oDataSource;
// Preview controller's view is added but it never shows up.
this.View.AddSubview(this.oPreviewController.View);
this.oPreviewController.View.Frame = this.View.Frame;
this.oPreviewController.View.Center = this.View.Center;
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
}
Found a solution by coincidence today: all ReloadData() on the preview controller and magically it will show its contents.
This allows to add a QLPreviewController to an existing view as a subview and embed a preview. It also gets you rid of the toolbar which contains the open in menu.

Resources