Is this a bug in Swing in JDK1.6/JDK1.7 but not in JDK1.5? - swing

I have an application for which GUI was developed in Java Swing JDK1.5.I am planning to upgrade the JDK to JDK1.6 but doing so produces problem for me.
Problem Statement : If I open few dialogs(say 10) and dispose them and than call method 'getOwnedWindows()' , it returns 0 in JDK1.5 but returns 10 in JDK1.6. As in JDK1.6 it returns 10, my algorithm to set focus is not working correctly as it is able to find invlaid/disposed dialogs and try to set the focus on it but not on the correct and valid dialog or component because algorithm uses getOwnedWindows() to get the valid and currently open dialog.
Can anyone suggest me the workaround to avoid this problem in JDK1.6?
Following piece of code can demonstrate the problem.
Custom Dialog Class :
Java Code:
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
public class CustomDialog extends JDialog implements ActionListener {
private JPanel myPanel = null;
private JButton yesButton = null;
private JButton noButton = null;
private boolean answer = false;
public boolean getAnswer() { return answer; }
public CustomDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, modal);
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel(myMessage));
yesButton = new JButton("Yes");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setLocationRelativeTo(frame);
setVisible(true);
//System.out.println("Constrtuctor ends");
}
public void actionPerformed(ActionEvent e) {
if(yesButton == e.getSource()) {
System.err.println("User chose yes.");
answer = true;
//setVisible(false);
}
else if(noButton == e.getSource()) {
System.err.println("User chose no.");
answer = false;
//setVisible(false);
}
}
public void customFinalize() {
try {
finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Main Class:
Java Code:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
import java.awt.Window;
public class TestTheDialog implements ActionListener {
JFrame mainFrame = null;
JButton myButton = null;
JButton myButton_2 = null;
public TestTheDialog() {
mainFrame = new JFrame("TestTheDialog Tester");
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
myButton = new JButton("Test the dialog!");
myButton_2 = new JButton("Print no. of owned Windows");
myButton.addActionListener(this);
myButton_2.addActionListener(this);
mainFrame.setLocationRelativeTo(null);
FlowLayout flayout = new FlowLayout();
mainFrame.setLayout(flayout);
mainFrame.getContentPane().add(myButton);
mainFrame.getContentPane().add(myButton_2);
mainFrame.pack();
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(myButton == e.getSource()) {
System.out.println("getOwnedWindows 1 " + mainFrame.getOwnedWindows().length);
createMultipleDialogs();
int i = 0;
for (Window singleWindow : mainFrame.getOwnedWindows()) {
System.out.println("getOwnedWindows " + i++ + " "
+ singleWindow.isShowing() + " "
+ singleWindow.isVisible() + " " + singleWindow);
}
System.out.println("getOwnedWindows 2 " + mainFrame.getOwnedWindows().length);
//System.gc();
System.out.println("getOwnedWindows 3 " + mainFrame.getOwnedWindows().length);
//System.gc();
System.out.println("getOwnedWindows 4 " + mainFrame.getOwnedWindows().length);
} else if (myButton_2 == e.getSource()) {
System.out.println("getOwnedWindows now: " + mainFrame.getOwnedWindows().length);
}
}
public void createMultipleDialogs() {
for (int a = 0; a < 10; a++) {
CustomDialog myDialog = new CustomDialog(mainFrame, false,
"Do you like Java?");
myDialog.dispose();
myDialog.customFinalize();
}
}
public static void main(String argv[]) {
TestTheDialog tester = new TestTheDialog();
}
}
Running the above code gives different output for JDK1.5 and JDK1.6
I would appreciate your help in this regards.
Thanks

Related

how to ViewFlipper addView or removeView after autoStart set to true

For my app, I have lots of images(from url not from phone memory) required to be shown as slideshow. I am using ViewFlipper for this. I am getting this images from url and adding them in viewFlipper. Problem is when i add 5-6 images it works fine but for more than 5-6 it goes into OutOfMemory error.
I think, this can be done if we can somehow do something like this..
1. add some set of images to ViewFlipper
2. startFlipping, remove view after showing that image/view,
3. add more images.
Not sure if it can be done using viewFlipper or are there any other way ?
Sample Code of my AutoSlideShow:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class AutoSlideShow extends Activity {
ViewFlipper viewFlipper = null;
Button pauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
viewFlipper.setFlipInterval(2000);
viewFlipper.setAutoStart(true);
for (int i = 0; i < allUrls.length; i++) {
setFlipperImage(allUrls[i]);
}
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pauseButton.getText().equals("Resume")) {
viewFlipper.startFlipping();
pauseButton.setText("Pause");
} else {
viewFlipper.stopFlipping();
pauseButton.setText("Resume");
}
}
});
}
private void setFlipperImage(String url) {
ImageView image = new ImageView(getApplicationContext());
Bitmap bitmap = null;
try {
InputStream content = (InputStream) new URL(url).getContent();
bitmap = BitmapFactory.decodeStream(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
viewFlipper.addView(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_slide_show, menu);
return true;
}
}
private ViewFlipper mViewFlipper;
private GestureDetector mGestureDetector;
int i = 0;
int k = 0;
int l = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
if (i == 0) {
for (int i = 0; i < 2; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(allUrls[i]);
mViewFlipper.addView(imageView);
k++;
}
i = 1;
}
mViewFlipper.getDisplayedChild();
// Add all the images to the ViewFlipper
CustomGestureDetector customGestureDetector = new CustomGestureDetector();
mGestureDetector = new GestureDetector(this, customGestureDetector);
mViewFlipper.setInAnimation(this, android.R.anim.fade_in);
mViewFlipper.setOutAnimation(this, android.R.anim.fade_out);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class CustomGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Swipe left (next)
if (e1.getX() > e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.left_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.left_out);
mViewFlipper.showNext();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
Log.d("Count", "" + mViewFlipper.getChildCount());
}
// Swipe right (previous)
if (e1.getX() < e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.right_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.right_out);
mViewFlipper.showPrevious();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}

Google map API v2 J2ME

Hi everybody im a beginner in J2ME developpement and i created a little j2me application that supposed to allow me to locate places based on an address that i have to enter in a enter in a TextField so i made this piece of code based on a tutorial a from jappit.com but when i launch the application the screen is blocked on loading and i get this error in the console:
"Uncaught exception java/lang/NumberFormatException: Sorry... body { font-family: verdana."
and this is the code :
import com.jappit.midmaps.googlemaps.GoogleMaps;
import com.jappit.midmaps.googlemaps.GoogleMapsCoordinates;
import com.jappit.midmaps.googlemaps.GoogleMapsGeocoder;
import com.jappit.midmaps.googlemaps.GoogleMapsGeocoderHandler;
import com.jappit.midmaps.googlemaps.GoogleMapsMarker;
import com.jappit.midmaps.googlemaps.GoogleStaticMap;
import com.jappit.midmaps.googlemaps.GoogleStaticMapHandler;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MapMidlet extends MIDlet implements CommandListener{
TextField searchbox = new TextField("Address","Enter your address here",100,TextField.ANY);
Form menu = new Form("Search Menu");
List type = new List("Type",List.EXCLUSIVE);
Command search = new Command("Search",Command.OK,0);
Command Exit = new Command("exit",Command.EXIT,1);
Display display = Display.getDisplay(this);
Ticker ti = new Ticker("Find me If you can !");
Alert alert = new Alert("Please enter an address","address is missing", null, AlertType.ERROR);
String adress;
public MapMidlet() {
}
protected void destroyApp(boolean unconditional)
{
}
protected void pauseApp() {
}
protected void startApp() {
adress=searchbox.getString();
menu.setCommandListener(this);
menu.append(searchbox);
menu.addCommand(search);
menu.addCommand(Exit);
display.setCurrent(menu);
//display.setCurrent(new MapCanvas(this));
}
public void commandAction(Command c, Displayable d) {
if(c==search)
{
display.setCurrent(new MapCanvas(this));}
else
{notifyDestroyed();}
}
public class MapCanvas extends Canvas implements GoogleStaticMapHandler, GoogleMapsGeocoderHandler
{
GoogleMaps gMaps = null;
GoogleStaticMap map = null;
String API_KEY = "AIzaSyBe1yXRcCXWQB_6ReSGbf0lH8XVwTvNpSQ";
MapMidlet mid;
public MapCanvas(MapMidlet mid)
{
this.mid=mid;
gMaps = new GoogleMaps(API_KEY);
map = gMaps.createMap(getWidth(), getHeight(), GoogleStaticMap.FORMAT_PNG);
//map.setHandler(this);
//map.setCenter(new GoogleMapsCoordinates(36.8189700,10.1657900));
//map.setZoom(15);
//map.update();
GoogleMapsGeocoder geocoder = gMaps.createGeocoder();
geocoder.setHandler(this);
geocoder.geocodeAddress(adress);
}
protected void paint(Graphics g)
{
map.draw(g, 0, 0, Graphics.TOP | Graphics.LEFT);
}
public void GoogleMapsGeocodeError(String address, int errorCode, String errorDescription)
{
System.out.println("Geocode error: " + errorCode + ", " + errorDescription);
}
public void GoogleMapsGeocodeSuccess(String address, GoogleMapsCoordinates coordinates, int accuracy)
{
map.setCenter(coordinates);
map.addMarker(new GoogleMapsMarker(coordinates));
map.setZoom(accuracy);
map.update();
}
public void GoogleStaticMapUpdateError(GoogleStaticMap map, int errorCode, String errorMessage)
{
System.out.println("map error: " + errorCode + ", " + errorMessage);
}
public void GoogleStaticMapUpdated(GoogleStaticMap map)
{
System.out.println("map loaded");
repaint();
}
}
}
Thanks.

Swing GUI Client Listeners not responding to update of Remote RMI Property

I am having some trouble with getting a JTree to redraw when an explicit call is made to its model (a call which I make once I have added some new nodes to it).
The code, which initially worked fine, fails now that the application is exported to RMI.
I store the DefaultTreeModel object in the Controller class, which is a Remote Object.
I add the DefaultTreeModel object to the JTree in my Client, using tree.addModel(controller.getModel());
I use an ActionListener subscribed to a button on the Client GUI to call a method in the Controller which performs the "Add new node" action.
I use a TreeModelListener to print a message to screen to prove that the Model Listener has fired.
Do Client side Swing listeners not work over RMI?
I have managed to reproduce the problem. I include the code for completeness but anticipate that someone will be able to reel off the answer based on experience.
Server Driver Class:
package server;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import client.controller.TestTreeControllerService;
import server.controller.TestTreeControllerImpl;
public class TestTreeServerStart {
/**
* #param args
*/
public static void main(String[] args) {
new TestTreeServerStart();
}
public TestTreeServerStart() {
try {
LocateRegistry.createRegistry(1099);
TestTreeControllerService c = new TestTreeControllerImpl();
Registry registry = LocateRegistry.getRegistry();
registry.rebind("TestTreeControllerService", c);
System.out.println("Started the RMI Server");
}
catch (RemoteException e) {
System.out.println(e.getMessage());
}
}
}
Server Controller Implementation Class:
package server.controller;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.controller.TestTreeControllerService;
#SuppressWarnings("serial")
public class TestTreeControllerImpl extends UnicastRemoteObject implements TestTreeControllerService {
/**
*
*/
//private static final long serialVersionUID = -8137864611400855504L;
private DefaultTreeModel m ;
public DefaultTreeModel getModel() {
return m;
}
public TestTreeControllerImpl() throws RemoteException {
super();
m = new DefaultTreeModel(new DefaultMutableTreeNode("Root"));
}
public void addNodeAction() throws RemoteException {
DefaultTreeModel m = (DefaultTreeModel) getModel();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
DefaultMutableTreeNode root = (DefaultMutableTreeNode) m.getRoot();
root.add(newNode);
//m.insertNodeInto(newNode, (DefaultMutableTreeNode) m.getRoot(), m.getChildCount(m.getRoot()));
m.nodeStructureChanged(root);
}
}
Client Driver Class:
package client;
import java.rmi.Naming;
import java.rmi.RemoteException;
import client.controller.TestTreeControllerService;
import client.view.TreeTestClient;
public class TreeTestClientStart {
/**
* #param args
*/
public static void main(String[] args) {
try {
TestTreeControllerService c = (TestTreeControllerService) Naming.lookup("rmi://localhost:1099/TestTreeControllerService");
new TreeTestClient(c);
}
catch(RemoteException e) {
System.out.println("Remote service not found: " + e.getLocalizedMessage());
}
catch (Exception e) {
System.out.println("Splat");
}
}
}
Client Controller Interface:
package client.controller;
import javax.swing.tree.DefaultTreeModel;
public interface TestTreeControllerService extends java.rmi.Remote {
public DefaultTreeModel getModel() throws java.rmi.RemoteException;
public void addNodeAction() throws java.rmi.RemoteException;
}
Client UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
*Client "Add Node" Action Listener (invokes Add Action in Controller) *
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.view.TreeTestClient;
public class AddNodeAction implements ActionListener {
private TreeTestClient treeTest;
public AddNodeAction(TreeTestClient treeTestIn) {
treeTest=treeTestIn;
}
#Override
public void actionPerformed(ActionEvent arg0) {
try {
treeTest.getController().addNodeAction();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client "Refresh Action" Tree Listener (Prints to Screen to prove that Listener fired)
package client.view.action;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import client.view.TreeTestClient;
public class RefreshTreeAction implements PropertyChangeListener, TreeModelListener {
private TreeTestClient treeTest;
public RefreshTreeAction(TreeTestClient treeTestIn) {
treeTest = treeTestIn;
}
private void refreshTree() {
System.out.println("Refresh tree fired");
}
#Override
public void treeNodesChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesInserted(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesRemoved(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeStructureChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void propertyChange(PropertyChangeEvent arg0) {
refreshTree();
}
}
The TreeModel exported by the server is serialized to the client as the client's own copy. The server doesn't know anything about what happens to the client's copy, and the client doesn't know anything about what happens to the server's copy. They are not the same object.
By adding the following code to an ActionListener subscribed to a new button on the GUI, I have been able to examine the contents of the Model at the click of a button:
//Loop contents of model attached to Client Tree
for (int i=0; i<t.getModel().getChildCount(t.getModel().getRoot()); i++) {
System.out.println("From Tree: Row #" + i + ": " + t.getModel().getChild(t.getModel().getRoot(), i));
}
//Loop contents of model object stored in Controller
try {
for (int i=0; i<c.getModel().getChildCount(c.getModel().getRoot()); i++) {
System.out.println("From Controller: Row #" + i + ": " + c.getModel().getChild(c.getModel().getRoot(), i));
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I found that the reference to the Client's Model was a different version to the state being maintained in the Controller's model object. There was no output in the Client loop, but the Controller's loop gave the correct state.
I have subsequently added a Swing Timer to the GUI to refresh the tree's model to match that of the Constructor. An updated GUI Class and GUI Refresh Action follow, which work:
Updated UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.Timer;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.GUIRefreshAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a listener that doesn't use the Remote object
t.addTreeSelectionListener(new RefreshTreeAction(this));
//Try a property change listener on the TreeModel
t.addPropertyChangeListener("treeModel", new RefreshTreeAction(this));
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
//Add a GUI redraw timer
Timer timer = new Timer(1000, new GUIRefreshAction(this));
timer.setInitialDelay(1);
timer.start();
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
GUI Refresh Listener Class
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import client.view.TreeTestClient;
public class GUIRefreshAction implements ActionListener {
private TreeTestClient client;
public GUIRefreshAction(TreeTestClient clientIn) {
client = clientIn;
}
#Override
public void actionPerformed(ActionEvent e) {
//Update the Tree's Model to match latest on Server
try {
client.getTree().setModel(client.getController().getModel());
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
}
I hope this helps someone who has the same requirements for a RMI Client Swing GUI to update in reaction to changes on the Server.

Jni Font Error in Swing application

I get this Random Jni error, sometimes the codes works, sometimes it doesn't
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Fonts {
public static void main(String[] args) {
Fonts fs = new Fonts();
try {
fs.initialize();
} catch (Exception e) {
e.printStackTrace();
}
fs.frm.setVisible(true);
}
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
private Font[] fnts;
private StyledDocument doc;
private MutableAttributeSet mas;
// private String[] fams;
private int cp = 0;
public Fonts() {
}
public void dis(String s) {
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception e) {
e.printStackTrace();
}
}
public void initialize() throws BadLocationException {
frm = new JFrame("awesome");
frm.setMinimumSize(new Dimension(width, height));
frm.setBounds(100, 100, width, height);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.getContentPane().setLayout(new BorderLayout());
fnts = ge.getAllFonts();
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
frm.getContentPane().add(jsp, BorderLayout.CENTER);
frm.pack();
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
}
}
}
And here is the error I get.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0xb3fdad10, pid=20482, tid=3066784624
#
# JRE version: 6.0_26-b03
# Java VM: Java HotSpot(TM) Client VM (20.1-b02 mixed mode, sharing linux-x86 )
# Problematic frame:
# C [libfontmanager.so+0x2ed10] float+0x40
#
# An error report file with more information is saved as:
# /home/alex/repos/java-alex.fonts/bin/hs_err_pid20482.log
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Aborted
added importans / standard Swing rulles
changed main method
moved all methods for JFrame from the toop to the end of methods,
set PrefferedSize to the JScrollPane
then for example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private Font[] fnts;
private StyledDocument doc;
private MutableAttributeSet mas;
// private String[] fams;
private int cp = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
}
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
}
private void dis(String s) {
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
you have to change logics for adding Font to the JTextPane, there are wrong order from Z - > A (just my helicopter view)
EDIT: and changed access/visibily (# by attn trashgod)
from
public void dis(String s) {...
to
private void dis(String s) {...

trouble executing actionlistener in swing applet embedded in html

Following is the applet code below:
import javax.swing.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ui extends JApplet implements ActionListener{
public static JPanel panel2;
private JTextField subnetField =null;
public static JPanel panel3;
public static Font fc;
public static String[] subn;
public static String searchnet;
boolean flag=false;
public void init()
{
String hostname = null;
String hostaddress=null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
hostaddress=addr.getHostAddress();
// Get hostname
hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
subn= hostaddress.split("\\.");
System.out.println(subn[2]);
searchnet=subn[2];
//WindowDestroyer listener=new WindowDestroyer();
//addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new GridLayout(3,0));
JPanel panel1 =new JPanel();
panel2 =new JPanel();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
JLabel lb2 = new JLabel("You are at: "+hostname+" "+hostaddress+" ");
lb2.setFont(new Font("sans-serif",Font.BOLD,15));
lb2.setForeground(Color.RED);
JPanel panel1_1 =new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
panel1_1.setBackground(Color.WHITE);
panel1_1.add(lb2, c);
//lb2.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel1_1.add(lb2, BorderLayout.EAST);
panel1_1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(panel1_1);
panel3=new JPanel();
panel3.setLayout(new GridLayout(2,0));
panel3.setBackground(Color.WHITE);
panel1.add(panel3);
UIManager.put("Button.background", Color.white);
UIManager.put("Button.foreground", Color.red);
fc = new Font("sans-serif",Font.BOLD,15);
UIManager.put("Button.font", fc);
JButton searchButton= new JButton("Search");
//Border b = new SoftBevelBorder(BevelBorder.LOWERED) ;
//searchButton.setBorder(b);
searchButton.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(searchButton);
searchButton.addActionListener(this);
contentPane.add(panel1);
panel2.setBackground(Color.WHITE);
contentPane.add(panel2);
//contentPane.add(searchButton);
//JButton closeButton=new JButton("Close");
//contentPane.add(closeButton);
//closeButton.addActionListener(this);
contentPane.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand ().equals ("Close"))
{
System.exit(0);
}
if (e.getActionCommand ().equals ("Search"))
{
panel2.setVisible(false);
panel2.removeAll();
panel2.revalidate();
panel3.setVisible(false);
panel3.removeAll();
panel3.revalidate();
if(flag){
searchnet=subnetField.getText();
}
result(panel2);//puts panel 2&panel 3 in the ui
panel2.setVisible(true);
panel3.setVisible(true);
}
}
public boolean complete;
public JPanel call(){
return null;
}
public void result(JPanel pn){
.
.
.
}
}
}
private void addColumnName(JPanel pn) {
// TODO Auto-generated method stub
}
public void addDataToTable(JPanel p, String element, int type){
......
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (Exception e) {
// TODO: error handling
}
} else {
// TODO: error handling
}
}
public static void main(String[] args){
ui start=new ui();
start.setVisible(true);
JFrame f = new JFrame("Find Device");
ui applet=new ui();
applet.init();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,450);
f.setVisible(true);
}
}
then the html file looks like this:
<html>
<applet code=ui.class
archive="webapplet.jar"
width=800 height=450>
</applet>
</body>
</html>
when i run the program via eclipse as an applet it runs fine, but when i put it in the html file, the init() seems to show up but the actionlistener on the button never seems to work
Any help would be really appreciated. Thanks!!
ps: will be happy to share any additional details if required
Emm... you mean the code never works as
System.exit(0);
?
If you mean "Close" button inactivity so it shouldn't close Internet Browser ... so that's OK :)
And this one as
InetAddress addr = InetAddress.getLocalHost();
Hmm... As for applet, I guess you should use getCodeBase() instead
Good luck :)