Jni Font Error in Swing application - swing

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) {...

Related

java jlabel working in windows but not in linux showing old, formats on screen, openjdk?

So I have written a Java application, that provides a transparent Heads up display at the top of the screen, it works perfectly on windows, but on my kubuntu 16.04 machine it does not clear the old label when you change the labels text, you end up with a ton of overlapping mess.
because a picture is worth a thousand words, the top is how it looks in windows, the bottom is how it looks under kubuntu:
https://s23.postimg.org/yra0vvlvf/rawr.png
here is the code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.URL;
import javax.swing.*;
import java.io.*;
public class spob extends JFrame implements WindowFocusListener
{
public spob()
{
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon((new ImageIcon("icon.png", "trayicon")).getImage());
final SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("spO2 pr monitor");
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
setType(javax.swing.JFrame.Type.UTILITY);
setUndecorated(true);
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setSize(400, 35);
JLabel label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
add(label);
setLocation(800, 0);
addWindowFocusListener(this);
setAlwaysOnTop( true );
this.setFocusable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
URL url = null;
BufferedReader in = null;
String[] anArray = new String[10];
anArray[0] = "<html><font color=green>- spO2:91 pr:65</font></html>";
anArray[1] = "<html><font color=red>+ spO2:85 pr:77</font></html>";
anArray[2] = "<html><font color=green>- spO2:90 pr:68</font></html>";
anArray[3] = "<html><font color=orange>+ spO2:89 pr:76</font></html>";
anArray[4] = "<html><font color=orange>- spO2:89 pr:72</font></html>";
anArray[5] = "<html><font color=orange>+ spO2:88 pr:73</font></html>";
anArray[6] = "<html><font color=red>- spO2:87 pr:78</font></html>";
anArray[7] = "<html><font color=red>+ spO2:86 pr:73</font></html>";
anArray[8] = "<html><font color=green>- spO2:92 pr:74</font></html>";
anArray[9] = "<html><font color=green>+ spO2:90 pr:71</font></html>";
while (true){
try {
Thread.sleep(200);
//url = new URL("http://192.168.1.153/stat.php");
//in = new BufferedReader(new InputStreamReader(url.openStream()));
//label.setText(in.readLine().toString());
Random randomno = new Random();
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
} catch (Exception ex) {
} finally {
//try {
// in.close();
//} catch (IOException e) {
//}
}
}
}
public void windowGainedFocus(WindowEvent e){}
public void windowLostFocus(WindowEvent e)
{
if(e.getNewState()!=e.WINDOW_CLOSED){
setAlwaysOnTop(false);
setAlwaysOnTop(true);
}
}
public static void main(String[] args)
{
new spob();
}
}
So, a number of issues
You're violating the single threaded rules of Swing, essentially, updating the UI from outside the context of the EDT, this can cause issues if the system is trying to paint something while you're trying to update it
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f)); - Swing doesn't know how to deal with opaque components which have an alpha based color, it tends to not to update the any of the components beneath it.
Transparent windows are ... fun ... they tend to introduce their own issues beyond what we would normally expect.
On my Mac system I was able to reproduce the issue, but inconsistently. This was especially apparent, because the Mac OS keeps rendering a shadow around the text.
The first thing I got rid of was setType(javax.swing.JFrame.Type.UTILITY);, I also added a repaint request of the label's parent container which seems to have solved the symptoms of the problem, but again, I was able to execute the code without at times.
If you want to update the UI periodically, you should use a Swing Timer, see How to use Swing Timers for more details. If you need to do something in the background and then update the UI, you should use a SwingWorker, have a look Worker Threads and SwingWorker for more details
(wow is me, it doesn't like my animated gif :()
The example deliberately uses a translucent background, it's intended to show the frame. Change pane.setAlpha(0.5f); to pane.setAlpha(0.0f); to make it fully transparent (I've tested that as well).
If you have issues, uncomment the line label.getParent().repaint(); in the Timer and see if that helps
public class Test {
public static void main(String[] args) {
new Test();
}
private JLabel label;
private String[] anArray = {
"<html><font color=green>- spO2:91 pr:65</font></html>",
"<html><font color=red>+ spO2:85 pr:77</font></html>",
"<html><font color=green>- spO2:90 pr:68</font></html>",
"<html><font color=orange>+ spO2:89 pr:76</font></html>",
"<html><font color=orange>- spO2:89 pr:72</font></html>",
"<html><font color=orange>+ spO2:88 pr:73</font></html>",
"<html><font color=red>- spO2:87 pr:78</font></html>",
"<html><font color=red>+ spO2:86 pr:73</font></html>",
"<html><font color=green>- spO2:92 pr:74</font></html>",
"<html><font color=green>+ spO2:90 pr:71</font></html>"
};
private Random randomno = new Random();
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
// Transparent window...
frame.setBackground(new Color(255, 255, 255, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BackgroundPane pane = new BackgroundPane();
// Set this to 0.0f to make it fully transparent
pane.setAlpha(0.5f);
pane.setLayout(new BorderLayout());
pane.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.setContentPane(pane);
label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
frame.add(label);
frame.pack();
Dimension size = frame.getSize();
size.width = 400;
frame.setSize(size);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
// label.getParent().repaint();
}
});
timer.start();
}
});
}
public class BackgroundPane extends JPanel {
private float alpha;
public BackgroundPane() {
setOpaque(false);
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
public float getAlpha() {
return alpha;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
}
nb I'm not using openJDK, I'm using Java 8, that might make a difference
Testing for capabilities
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
public class Test {
public static void main(String[] args) {
GraphicsEnvironment ge
= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
boolean isUniformTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
boolean isPerPixelTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT);
boolean isShapedWindowSupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT);
System.out.println("isUniformTranslucencySupported = " + isUniformTranslucencySupported);
System.out.println("isPerPixelTranslucencySupported = " + isPerPixelTranslucencySupported);
System.out.println("isShapedWindowSupported = " + isShapedWindowSupported);
}
}

Add custom wms layer to codename one Mapcontainer

I am building an android GPS app with Codename one. I use com.codename1.googlemaps.MapContainer to create a Google map;
In my app is use tabs to create different "pages".
Code:
cnt = new MapContainer();
t.addTab("Tab3", cnt);
And for my current location I use:
try {
Coord position = new Coord(lat,lng);
cnt.clearMapLayers();
cnt.setCameraPosition(position);
cnt.addMarker(EncodedImage.create("/maps-pin.png"), position, "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// stuff todo...
}
});
} catch(IOException err) {
// since the image is iin the jar this is unlikely
err.printStackTrace();
}
I like to add a wms layer to the Google Maps. Is this possible? I can't find in codenameone a command addLayer. If yes, do you have a code snippet how to do this?
If it is not possiple, can I use openlayers in my codename one app? Can you give me a code snippet to do this?
Edit
I started to create an native file to "catch"the addtileoverlay from google maps api. The layer I want to use is a xyz layer, so I think I can use a urltileprovider from the googlemap api
I made the native code for the tileoverlay but the tileoverlay doesn't appear. Is it because i didn't get a link with the mapcontainer.
I am little bit stuck. I tried to build from scratch with the googmaps example but the mapcompnent is not anymore used.
package com.Bellproductions.TalkingGps;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.TileOverlay;
import com.codename1.impl.android.AndroidNativeUtil;
import java.util.Locale;
import java.net.MalformedURLException;
public class SeamarksImpl {
private GoogleMap mapInstance;
private TileOverlay m;
TileProvider provider;
public boolean isSupported() {
return true;
}
public long addTilelayer (){
final String URL_FORMAT = "http://t1.openseamap.org/seamark/{z}/{x}/{y}.png";
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
provider = new UrlTileProvider(256, 256) {
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
try {
y = (1 << zoom) - y - 1;
return new URL(String.format(Locale.US, URL_FORMAT, zoom, x, y ));
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}
TileOverlayOptions tileopt = new TileOverlayOptions().tileProvider(provider);
public void addlayer() {
m = mapInstance.addTileOverlay(tileopt);
}
};
}
});
long p = 1;
return p;}
}
My seamarks.java file has this code to bind with the native interface
import com.codename1.system.NativeInterface;
/**
*
* #author Hongerige Wolf
*/
public interface Seamarks extends NativeInterface {
public void addTilelayer ();
}
In the mainactivity java file i have the statements
public Seamarks seamark;
public void init(Object context) {
seamark = (Seamarks)NativeLookup.create(Seamarks.class);
}
public void start() {
seamark.addTilelayer();
}
Update
I created a new googlemaps.CN1lib. But the xyz layer is not showing on the googlemaps. I used native code tot use the Tileoverlay feature and tried to add tileoverlay in the same way as Markers.
In the InternalNativeMapsImpl file i changed
private void installListeners() {
/*
if (mapInstance == null) {
view = null;
System.out.println("Failed to get map instance, it seems google play services are not installed");
return;
}*/
view.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mapInstance = googleMap;
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
String tileLayer= "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
//String s = String.format(Locale.US, tileLayer , zoom, x, y);
String s = tileLayer + "/" + zoom + "/" + x + "/" + reversedY + ".png";
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
mapInstance.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
Long val = listeners.get(marker);
if (val != null) {
MapContainer.fireMarkerEvent(InternalNativeMapsImpl.this.mapId, val.longValue());
return true;
}
return false;
}
});
mapInstance.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
MapContainer.fireMapChangeEvent(InternalNativeMapsImpl.this.mapId, (int) position.zoom, position.target.latitude, position.target.longitude);
}
});
mapInstance.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireTapEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireLongPressEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setMyLocationEnabled(showMyLocation);
mapInstance.getUiSettings().setRotateGesturesEnabled(rotateGestureEnabled);
}
});
}
Secondly i added a addTilexyz method also in the same way as addMarkers
public long addTilexyz(final String Turl) {
uniqueIdCounter++;
final long key = uniqueIdCounter;
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
// Tileurl = "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, Turl , zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
});
return key;
}
In the InternalNativeMaps file i added te method
public long addTilexyz(String Turl);
And in the Mapcontainer file i added
public MapObject addTilexyz(String Turl) {
if(internalNative != null) {
MapObject o = new MapObject();
Long key = internalNative.addTilexyz(Turl);
o.mapKey = key;
markers.add(o);
return o;
} else {
}
MapObject o = new MapObject();
return o;
}
I am puzzeled what is wrong with the code. I wonder if the commands
Long key = internalNative.addTilexyz(Turl);
and
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
put the tileoverlay on the googlemap. Or is the tileurl wrong. http://t1.openseamap.org/seamark/z/x/y.png is correct.
We don't expose layers in the native maps at this time, you can fork the project and just add an API to support that to the native implementations.

Simple chat client using JMS

I'm using Swing, Java Messaging Service and GlassFish4.1 server to build a chat box from a Jpanel so I can add it to my Jframe application; but I seem to have a problem establishing a connection.
During runtime the program stops at the line:
TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");
I previously got this client-code to work on an Enterprise application, but now I'm attempting to add it to a regular Java project I'm rather stuck.
Really appreciate any help on this, I'm very new to JMS so please keep answers as Lamen as possible. Thanks!
import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class ChatPanel extends javax.swing.JPanel implements Runnable{
private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;
/**
* Creates new form chatFrame
* #param nickName
*/
public ChatPanel(String nickName)
{
initComponents();
DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
name = nickName;
connect();
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
// </editor-fold>
public JTextArea getTextArea()
{
return gameInfoTextArea;
}
public void setText(String textString)
{
String s = gameInfoTextArea.getText() + "\n" + textString;
gameInfoTextArea.setText(s);
}
private void connect()
{
try
{
Context ctx = new InitialContext();
TopicConnectionFactory tcf = (TopicConnectionFactory)
ctx.lookup("BJconn");
tpConnection = tcf.createTopicConnection();
tpConnection.setClientID(name);
tpSession = tpConnection.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup("BJDest");
tpPublisher = tpSession.createPublisher(topic);
tpSubscriber = tpSession.createDurableSubscriber(topic, name);
tpConnection.start();
t = new Thread(this);
t.start();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Chat cannot connect");
System.out.println(e.getMessage());
}
}
/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
tpConnection.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage() );
}
} */
private void sendMessage()
{
try
{
TextMessage tx = tpSession.createTextMessage();
tx.setText(name + ": " + this.chatField.getText());
tpPublisher.send(tx);
this.chatField.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot send message");
}
}
#Override
public void run()
{
try
{
while (true)
{
TextMessage tx = (TextMessage) tpSubscriber.receive();
if (tx != null)
{
String content = "";
content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
this.gameInfoTextArea.setText(content);
Thread.sleep(100);
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
chatField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
gameInfoTextArea = new javax.swing.JTextArea();
setBackground(new java.awt.Color(0, 102, 0));
chatField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chatFieldActionPerformed(evt);
}
});
chatField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
chatFieldKeyReleased(evt);
}
});
gameInfoTextArea.setEditable(false);
gameInfoTextArea.setColumns(20);
gameInfoTextArea.setRows(5);
jScrollPane1.setViewportView(gameInfoTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chatField)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>
private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
{
sendMessage();
}
}
// Variables declaration - do not modify
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}

Getting null / empty JtextArea

I crated a Frame which have a panel inside it and the panel have a textarea inside it. Now i created a constructor which makes the frame visible for some time and after that it is set as invisible. Time for which it is visible it shows some massage.
When i run the constructor code inside the main method of outputDisplay class it shows the text massage
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class OutputDisplay {
static JFrame frame;
JPanel panel;
JTextArea area;
Font font;
public void timer(int time){
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
}
});
timer.start();
timer.setRepeats(false);
}
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue,String path,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.MAGENTA);
area.setSize(200, 200);
int j=0;
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(500, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue) throws InterruptedException{
frame = new JFrame("Report");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.BLUE);
area.setSize(200, 200);
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
frame.setResizable(false);
}//constructor
public OutputDisplay() {
}//no arg
public void dialogue (String massage) throws InterruptedException{
frame = new JFrame("Massage");
frame.setLocation(400, 220);
JPanel panel = new JPanel();
JTextArea area = new JTextArea();
Font font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.GREEN);
area.setSize(200, 200);
int j=0;
String[] t = {massage};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(400, 100);
frame.setVisible(true);
Thread.sleep(8*1000);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//dialogue
static void warningPopUp (String massage){
JOptionPane.showMessageDialog(null, massage);
}//dialogue
public static void main(String[] args){
new OutputDisplay("We are checking for account validation"+"\n"
+ "If user id and password matches then we will goto websites for updation. " +"\n"
+ "You will get a complete report once we are done", 4*1000);
}//main
}//OutputDisplay
Don't call Thread.sleep(...) on the Swing EDT as that just puts your whole GUI to sleep.
Do use a Swing Timer instead.
Do Google and search this site for similar questions.
Please check out Lesson: Concurrency in Swing
Also check out the Swing Tutorials
Edit
You're still using Thread.sleep, again you shouldn't use it, but instead should use a Timer. Also, never set a JTextArea's size or preferred size ever. Do this and the scrollbars of your JScrollPane won't work. Instead, set its rows and columns.
import java.awt.Color;
import java.awt.Font;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TimeLimitedDialogTester {
private static final int EB_GAP = 25;
private JPanel mainPanel = new JPanel();
public TimeLimitedDialogTester() {
mainPanel.add(new JButton(new ShowDialogAction("Show Dialog")));
mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, 2 * EB_GAP, 2 * EB_GAP, 2 * EB_GAP));
}
public JPanel getMainPanel() {
return mainPanel;
}
#SuppressWarnings("serial")
private class ShowDialogAction extends AbstractAction {
public ShowDialogAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Window mainWin = SwingUtilities.getWindowAncestor(mainPanel);
int seconds = 5;
String dialogTitle = "WARNING";
String text = "We are checking for account validation. If user id and password matches then we"
+ " will go to websites for updating. You will get a complete report once we are done.";
TimeLimitedDialog timeLimitedDialog = new TimeLimitedDialog(mainWin, seconds, dialogTitle, text);
timeLimitedDialog.dialogShow();
}
}
private static void createAndShowGui() {
TimeLimitedDialogTester timeLimitedDialog = new TimeLimitedDialogTester();
JFrame frame = new JFrame("TimeLimitedDialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(timeLimitedDialog.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TimeLimitedDialog {
private static final int ROWS = 6;
private static final int COLS = 30;
private static final Color FG = Color.green.darker().darker();
private JDialog dialog;
private JTextArea displayArea = new JTextArea(ROWS, COLS);
private int seconds;
public TimeLimitedDialog(Window mainWin, int seconds, String dialogTitle, String text) {
displayArea.setWrapStyleWord(true);
displayArea.setLineWrap(true);
displayArea.setFocusable(false);
displayArea.setText(text);
displayArea.setForeground(FG);
displayArea.setFont(displayArea.getFont().deriveFont(Font.BOLD));
this.seconds = seconds;
dialog = new JDialog(mainWin, dialogTitle, ModalityType.APPLICATION_MODAL);
dialog.add(new JScrollPane(displayArea));
dialog.pack();
dialog.setLocationRelativeTo(mainWin);
}
public void dialogShow() {
new Timer(seconds * 1000, new TimerListener()).start();
dialog.setVisible(true);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (dialog != null && dialog.isVisible()) {
dialog.dispose();
}
((Timer) e.getSource()).stop();
}
}
}

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

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