Simple chat client using JMS - swing

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
}

Related

Make a line of Swing components of variable length inside another line

I'm trying to make a web inspector interface in Swing.
I managed to make the tags render correctly, but I have a problem with attributes.
I have a JPanel with FlowLayout, there are some JLabels inside it, and a JPanel in the middle, which has FlowLayout set on it too. That JPanel can contain any number of inner JPanels for attributes, each of them has 2 TextFields and 3 JLabels, inputs have zero width by default and are not visible, JLabels can have arbitrary length.
The problem is I cannot make my lines have the correct length. I add my attributes JPanels after the main container is laid out and made visible, maybe that is the problem. I also tried setting all the widths manually in the code (and increase the width of my top-level line too), but the output is still far from correct. My elements are either not visible except the first child JPanel (but I have a lot of empty space on the right).
I tried calling validate() and doLayout(), and I don't see any difference.
What is the right way to do this layout? First add everything, and then call setVisible() on my JFrame? Or it's not necessary?
Also, how can I make sure that the elements will always stay in one line?
I tried BoxLayout too, but that's not suitable, as it gives all the available parent width to my attributes panel (and I need it have zero pixel width when it is empty). If I add glue to the end, then free space is distributed equally between the glue and my JPanel.
public class WebInspectorTest {
private static Node prepareTree() {
Node root = new Node(1);
root.tagName = "body";
root.attributes.put("onload", "init()");
Node p = new Node(root, 1);
p.tagName = "p";
Node text1 = new Node(p, 3);
text1.nodeValue = "This is a ";
Node i = new Node(p, 1);
i.tagName = "i";
i.attributes.put("style", "background-color: rgb(223, 216, 45); color: #8848a7; cursor: pointer");
Node text2 = new Node(i, 3);
text2.nodeValue = "paragraph";
Node text3 = new Node(p, 3);
text3.nodeValue = ".";
Node img = new Node(p, 1);
img.tagName = "img";
img.attributes.put("src", "smiley.gif");
return root;
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
final Node root = prepareTree();
if (root == null) return;
final JFrame frame = new JFrame("Document Inspector");
JPanel cp = new JPanel();
cp.setBorder(BorderFactory.createEmptyBorder(9, 10, 9, 10));
frame.setContentPane(cp);
cp.setLayout(new BorderLayout());
final JPanel contentpane = new JPanel();
contentpane.setBackground(Color.WHITE);
contentpane.setOpaque(true);
//contentpane.setBounds(0, 0, 490, 380);
final int width = 490, height = 418;
final JScrollPane scrollpane = new JScrollPane(contentpane);
scrollpane.setOpaque(false);
scrollpane.getInsets();
cp.add(scrollpane);
scrollpane.setBackground(Color.WHITE);
scrollpane.setOpaque(true);
scrollpane.setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TagLibrary.init();
final Entry rootEntry = new Entry(root);
contentpane.add(rootEntry);
final JScrollPane sp = scrollpane;
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() + sp.getVerticalScrollBar().getPreferredSize().width;
rootEntry.inflate(width);
contentpane.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentMoved(java.awt.event.ComponentEvent evt) {}
#Override
public void componentResized(java.awt.event.ComponentEvent evt) {
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() - 12;
rootEntry.setWidth(width);
}
});
}
});
}
}
public class Entry extends javax.swing.JPanel {
public Entry() {
initComponents();
}
public Entry(Node node) {
this.node = node;
initComponents();
initEvents();
}
private void addAttributes() {
final Entry entry = this;
Set<String> keys = node.attributes.keySet();
attributes.setPreferredSize(new Dimension(0, line_height));
int index = 0;
for (String key: keys) {
Attribute attr = new Attribute(this, key, node.attributes.get(key));
attributes.add(attr);
Dimension dim = attributes.getPreferredSize();
attributes.setPreferredSize(new Dimension(dim.width + attr.getWidth(), dim.height));
}
int max_width = Math.max(attributes.getPreferredSize().width + headerTag.getWidth() + headerTag2.getWidth() + 38, getPreferredSize().width);
header.setMinimumSize(new Dimension(max_width, line_height));
footer.setMinimumSize(new Dimension(max_width, line_height));
setMinimumSize(new Dimension(max_width, line_height));
}
private void initEvents() {
marker.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
if (!opened) open();
else close();
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});
addMouseListener(listener);
}
public void addChild(Entry child, int pos) {
content.add(child, pos);
//content.validate();
}
public void inflate(int width) {
if (node == null) return;
if (node.nodeType == 1) {
boolean isPaired = !TagLibrary.tags.containsKey(node.tagName.toLowerCase()) ||
TagLibrary.tags.get(node.tagName.toLowerCase());
if (!isPaired) {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(" />");
threeDots.setText("");
headerTag3.setText("");
content.setVisible(false);
footer.setVisible(false);
marker.setVisible(false);
} else {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(">");
headerTag3.setText("</" + node.tagName.toLowerCase() + ">");
footerTag.setText("</" + node.tagName.toLowerCase() + ">");
}
addAttributes();
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
content.removeAll();
//System.out.println(getWidth());
for (int i = 0; i < node.children.size(); i++) {
Entry e = new Entry(node.children.get(i));
content.add(e);
e.inflate(w);
//content.setSize(e.getSize());
}
content.doLayout();
if (node.children.size() > 0) {
open();
} else {
close();
}
} else if (node.nodeType == 3 && !node.nodeValue.matches("\\s*")) {
content.removeAll();
header.setVisible(false);
footer.setVisible(false);
JTextArea textarea = new JTextArea();
textarea.setText(node.nodeValue);
textarea.setEditable(false);
textarea.setOpaque(false);
textarea.setBackground(new Color(255, 255, 255, 0));
textarea.setColumns(180);
textarea.setFont(new Font("Tahoma", Font.PLAIN, 16));
int rows = node.nodeValue.split("\n").length;
textarea.setRows(rows);
textarea.addMouseListener(listener);
int height = getFontMetrics(textarea.getFont()).getHeight() * rows;
content.add(textarea);
content.setOpaque(false);
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
((JPanel)getParent()).setMinimumSize(new Dimension(w, line_height * 2 + content.getPreferredSize().height));
opened = true;
content.validate();
} else {
setVisible(false);
content.removeAll();
opened = false;
return;
}
int w = Math.max(Math.max(Math.max(content.getMinimumSize().width, header.getMinimumSize().width), min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
int height = line_height * 2 + content.getPreferredSize().height;
if (opened) {
setSize(w, height);
}
updateWidth(w);
}
public void setWidth(int width) {
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
setPreferredSize(new Dimension(w, getPreferredSize().height));
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).setWidth(w);
} else {
c[i].setSize(w, c[i].getMaximumSize().height);
c[i].setMaximumSize(new Dimension(w, c[i].getMaximumSize().height));
}
}
}
private void updateWidth(int width) {
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width);
if (content.getPreferredSize().width > w) {
w = content.getPreferredSize().width;
}
if (getSize().width > w) return;
setPreferredSize(new Dimension(w, getPreferredSize().height));
Entry last = this;
Component c = getParent();
while (c != null && c.getParent() != null && c.getParent() instanceof Entry) {
//c.setPreferredSize(new Dimension(w, c.getPreferredSize().height));
Component[] children = ((JPanel)c).getComponents();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof Entry && children[i] != last && children[i].getSize().width < w) {
((Entry)children[i]).setWidth(w);
} else if (!(children[i] instanceof Entry) && children[i].getParent() != last && children[i].getSize().width < w) {
children[i].setSize(w, children[i].getMaximumSize().height);
children[i].setMaximumSize(new Dimension(w, children[i].getMaximumSize().height));
}
}
w += margin;
w = Math.max(c.getParent().getSize().width, w);
if (((Entry)c.getParent()).node.tagName.equals("body")) System.err.println("Root entry width: " + w);
int h = line_height * 2 + ((Entry)c.getParent()).content.getPreferredSize().height;
c.getParent().setSize(w, h);
((Entry)c.getParent()).header.setMinimumSize(new Dimension(w, line_height));
((Entry)c.getParent()).footer.setMinimumSize(new Dimension(w, line_height));
//((Entry)c.getParent()).content.setPreferredSize(new Dimension(w, ((Entry)c.getParent()).getSize().height - line_height * 2));
last = (Entry)c.getParent();
c = c.getParent().getParent();
}
if (c != null) c.validate();
content.validate();
}
ActionListener callback;
public static final int min_width = 280;
public static final int line_height = 26;
public static final int margin = 30;
MouseListener listener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
//System.out.println("Entered");
updateChildren(true);
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
//System.out.println("Exited");
updateChildren(false);
repaint();
}
};
private void updateChildren(boolean value) {
hovered = value;
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).updateChildren(value);
}
}
}
#Override
public void paintComponent(Graphics g) {
if (hovered) {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(190, 230, 255, 93));
g.fillRect(0, 0, getWidth(), getHeight());
} else {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, getWidth(), getHeight());
}
//super.paintComponent(g);
}
private boolean hovered = false;
public void open() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png")));
threeDots.setVisible(false);
headerTag3.setVisible(false);
content.setVisible(true);
footer.setVisible(true);
opened = true;
}
public void close() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle2.png")));
content.setVisible(false);
footer.setVisible(false);
boolean has_children = node.children.size() > 0;
threeDots.setVisible(has_children);
marker.setVisible(has_children);
headerTag3.setVisible(true);
opened = false;
}
public void openAll() {
open();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).openAll();
}
}
}
public void closeAll() {
close();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).closeAll();
}
}
}
public boolean opened = false;
public Node node;
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
header = new javax.swing.JPanel();
headerMargin = new javax.swing.JPanel();
marker = new javax.swing.JLabel();
headerTag = new javax.swing.JLabel();
attributes = new javax.swing.JPanel();
headerTag2 = new javax.swing.JLabel();
threeDots = new javax.swing.JLabel();
headerTag3 = new javax.swing.JLabel();
content = new javax.swing.JPanel();
footer = new javax.swing.JPanel();
footerMargin = new javax.swing.JPanel();
footerTag = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
header.setBackground(new java.awt.Color(255, 255, 255));
header.setAlignmentX(0.0F);
header.setMaximumSize(new java.awt.Dimension(32767, 26));
header.setMinimumSize(new java.awt.Dimension(280, 26));
header.setOpaque(false);
header.setPreferredSize(new java.awt.Dimension(280, 26));
header.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
headerMargin.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 0, 5));
headerMargin.setMaximumSize(new java.awt.Dimension(30, 26));
headerMargin.setOpaque(false);
headerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
marker.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png"))); // NOI18N
marker.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
marker.setPreferredSize(new java.awt.Dimension(22, 22));
javax.swing.GroupLayout headerMarginLayout = new javax.swing.GroupLayout(headerMargin);
headerMargin.setLayout(headerMarginLayout);
headerMarginLayout.setHorizontalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
headerMarginLayout.setVerticalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
header.add(headerMargin);
headerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag.setForeground(new java.awt.Color(102, 0, 153));
headerTag.setText("<body");
header.add(headerTag);
attributes.setMaximumSize(new java.awt.Dimension(32767, 26));
attributes.setOpaque(false);
attributes.setPreferredSize(new java.awt.Dimension(0, 26));
attributes.setLayout(new javax.swing.BoxLayout(attributes, javax.swing.BoxLayout.LINE_AXIS));
header.add(attributes);
headerTag2.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag2.setForeground(new java.awt.Color(102, 0, 153));
headerTag2.setText(">");
header.add(headerTag2);
threeDots.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
threeDots.setText("...");
threeDots.setPreferredSize(new java.awt.Dimension(19, 20));
header.add(threeDots);
headerTag3.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag3.setForeground(new java.awt.Color(102, 0, 153));
headerTag3.setText("</body>");
header.add(headerTag3);
add(header);
content.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 30, 0, 0));
content.setAlignmentX(0.0F);
content.setOpaque(false);
content.setLayout(new javax.swing.BoxLayout(content, javax.swing.BoxLayout.PAGE_AXIS));
add(content);
footer.setBackground(new java.awt.Color(255, 255, 255));
footer.setAlignmentX(0.0F);
footer.setMaximumSize(new java.awt.Dimension(32767, 26));
footer.setOpaque(false);
footer.setPreferredSize(new java.awt.Dimension(91, 26));
footer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
footerMargin.setOpaque(false);
footerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
javax.swing.GroupLayout footerMarginLayout = new javax.swing.GroupLayout(footerMargin);
footerMargin.setLayout(footerMarginLayout);
footerMarginLayout.setHorizontalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 30, Short.MAX_VALUE)
);
footerMarginLayout.setVerticalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 26, Short.MAX_VALUE)
);
footer.add(footerMargin);
footerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
footerTag.setForeground(new java.awt.Color(102, 0, 153));
footerTag.setText("</body>");
footer.add(footerTag);
add(footer);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel attributes;
private javax.swing.JPanel content;
private javax.swing.JPanel footer;
private javax.swing.JPanel footerMargin;
private javax.swing.JLabel footerTag;
private javax.swing.JPanel header;
private javax.swing.JPanel headerMargin;
private javax.swing.JLabel headerTag;
private javax.swing.JLabel headerTag2;
private javax.swing.JLabel headerTag3;
private javax.swing.JLabel marker;
private javax.swing.JLabel threeDots;
// End of variables declaration
}
public class Attribute extends javax.swing.JPanel {
public Attribute(Entry entry, String name, String value) {
initComponents();
this.entry = entry;
name_field.setText(name);
if (value == null || value.isEmpty()) {
value_field.setText("");
eq.setVisible(false);
quote1.setVisible(false);
quote2.setVisible(false);
value_field.setVisible(false);
} else {
value_field.setText(value);
}
//setOpaque(true);
//setBackground(Color.RED);
setSize(name_field.getPreferredSize().width + value_field.getPreferredSize().width + 36, Entry.line_height);
originalName = name;
}
public String getEditorText() {
return full_editor.getText();
}
public String getNameField() {
return name_field.getText();
}
public String getValueField() {
return value_field.getText();
}
public String getOriginalName() {
return originalName;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
full_editor = new javax.swing.JTextField();
name_field = new javax.swing.JLabel();
eq = new javax.swing.JLabel();
quote1 = new javax.swing.JLabel();
value_editor = new javax.swing.JTextField();
value_field = new javax.swing.JLabel();
quote2 = new javax.swing.JLabel();
setMaximumSize(new java.awt.Dimension(32767, 24));
setOpaque(false);
setPreferredSize(new java.awt.Dimension(400, 22));
setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
full_editor.setBorder(null);
full_editor.setMinimumSize(new java.awt.Dimension(0, 22));
full_editor.setOpaque(false);
full_editor.setPreferredSize(new java.awt.Dimension(6, 22));
add(full_editor);
name_field.setForeground(new java.awt.Color(102, 0, 102));
name_field.setText("class");
name_field.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 2, 0, 0));
add(name_field);
eq.setForeground(new java.awt.Color(102, 0, 102));
eq.setText("=");
add(eq);
quote1.setForeground(new java.awt.Color(153, 153, 153));
quote1.setText("\"");
add(quote1);
value_editor.setBorder(null);
value_editor.setMinimumSize(new java.awt.Dimension(0, 22));
value_editor.setOpaque(false);
value_editor.setPreferredSize(new java.awt.Dimension(0, 22));
add(value_editor);
value_field.setForeground(new java.awt.Color(0, 51, 204));
value_field.setText("link");
add(value_field);
quote2.setForeground(new java.awt.Color(153, 153, 153));
quote2.setText("\"");
add(quote2);
}// </editor-fold>
private final int full_editor_width = 8;
private boolean is_new = false;
private String originalName;
private Entry entry;
private ActionListener listener;
// Variables declaration - do not modify
private javax.swing.JLabel eq;
private javax.swing.JTextField full_editor;
private javax.swing.JLabel name_field;
private javax.swing.JLabel quote1;
private javax.swing.JLabel quote2;
private javax.swing.JTextField value_editor;
private javax.swing.JLabel value_field;
// End of variables declaration
}
public class Node {
public Node() {}
public Node(Node parent_node) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
}
public Node(int node_type) {
nodeType = node_type;
}
public Node(Node parent_node, int node_type) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
nodeType = node_type;
}
public boolean addChild(Node node) {
if (nodeType == 1) {
children.add(node);
return true;
}
return false;
}
public Node parent;
public Vector<Node> children = new Vector<Node>();
public LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();
public Node previousSibling;
public Node nextSibling;
public String tagName = "";
public int nodeType = 3;
public String nodeValue = "";
}
public class TagLibrary {
public static void init() {
if (init) return;
tags.put("br", false);
tags.put("hr", false);
tags.put("link", false);
tags.put("img", false);
tags.put("a", true);
tags.put("span", true);
tags.put("div", true);
tags.put("p", true);
tags.put("sub", true);
tags.put("sup", true);
tags.put("b", true);
tags.put("i", true);
tags.put("u", true);
tags.put("s", true);
tags.put("strong", true);
tags.put("em", true);
tags.put("quote", true);
tags.put("cite", true);
tags.put("table", true);
tags.put("thead", true);
tags.put("tbody", true);
tags.put("cite", true);
tags.put("head", true);
tags.put("body", true);
leaves.add("style");
leaves.add("script");
init = true;
}
private static boolean init = false;
public static Hashtable<String, Boolean> tags = new Hashtable<String, Boolean>();
public static Vector<String> leaves = new Vector<String>();
}
Here is the screeshot of the GUI:
Output
And here is the same when I make a viewport wider by dragging:
Output
This is close to what I need, despite the fact that the whole attributes are hidden when the parent line container is way too narrow.

MVC+ SWING and a ListSelectionListener

What I am trying to do is get the selected value from my SWING View JList to my controller class, so I can use that data in my controller.
For simplicity I manually added 2 elements to my JList("Item 1", "Item 2", (so I have something to pass)I seem to have a problem accessing it. My View has a JList with a ListSelectionListener which I pass to my controller via my main:
public class AppMain {
private AppView appView = null;
public static void main(String[] args) {
AppView appView = new AppView();
Controller controller = new Controller(appView);
}
public AppView getView() {
return appView;
}
}
My view is:
import javax.swing.event.ListSelectionListener;
public class AppView extends javax.swing.JFrame {
public AppView() {
initComponents();
this.setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
ValueList = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ValueList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", " " };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(ValueList);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JList ValueList;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
public void ListSelectionListener(ListSelectionListener selectionListener) {
ValueList.addListSelectionListener(selectionListener);
}
}
And a Controller:
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Controller implements ListSelectionListener{
AppView gui;
public Controller(AppView v)
{
gui = v;
gui.ListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
this.gui.ListSelectionListener(this);
System.out.println("FOO");
}
}
No I want TO get the selectedValue in the Controller. I can't seem to grasp it. Also This prints Foo 3 times and I also cannot find out why.
Thanks in advance
As shown in How to Write a List Selection Listener more than one ListSelectionEvent may be generated as the user selects fist one entry and then another. Try checking when the selection is stable.
if (!e.getValueIsAdjusting()) {
// examine result
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
…
}

Topshelf TimeoutException

I'm trying to use Topshelf Framework to create a windows service. But when i try to start the service, there is this exception :
" The service failed to start... System.Service.Process.TimeoutException : the waiting period has expired and the operation has not been completed"
This is my code :
public class MyService : ServiceControl
{
private System.Timers.Timer _timer;
public void MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = false;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
Thanks for any help :)
There are several issues I notice:
The current code would make the timer fire only once (you have AutoReset = false)
with TopShelf, the MyService class should look like this:
using System.Timers;
using Topshelf;
namespace TopShelfTestService
{
public class MyService
{
private System.Timers.Timer _timer;
public MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = true;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
}
and the console app/ Program.cs will look like so:
using Topshelf;
namespace TopShelfTestService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host"); //7
x.SetDisplayName("Test Service with TopShelf"); //8
x.SetServiceName("TopShelfTestService");
});
}
}
}

Trying to get an applause sound to play when jframe opens

First i will say i have my Jframe opening and staying open for 10 seconds.
I wrote some games for kids to display to them what a future in programming could be or computer science... anyway
Whomever wins I have another Jframe designed to pop up when it does i would like a sound clip to play. Currently the sound clip is in the source folder and i have a little method to play it but it is not working. Here is the code
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class HoorayWithTimer extends javax.swing.JFrame {
int counter;
public HoorayWithTimer() {
initComponents();
Clip click = clipOpen("applause3.wav");// should open the clip
clipStart(click);
}//end of public HorrayWithTimer()
/*
* This method is called from within the constructor to initialize 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() {
timerLabel = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(571, 410));
getContentPane().setLayout(null);
getContentPane().add(timerLabel);
timerLabel.setBounds(632, 411, 66, 29);
timerLabel.getAccessibleContext().setAccessibleName("timerLabel");
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/party_balloons_scaled.png"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 560, 540);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
HoorayWithTimer.this.setVisible(false);
HoorayWithTimer.this.dispose();
}
});
timer.start();
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
private Clip clipOpen(String name)// method to play clip
{
URL url = getClass().getResource(name);
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(stream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
}
return null;
}
private void clipStart(Clip clip) {
clip.start();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HoorayWithTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new HoorayWithTimer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel timerLabel;
// End of variables declaration
}
I think problem is here clipOpen("applause3.wav"). Try to use /applause3.wav. Also where is your wav file? For example it works for my path "/res/1.mp3", 1.mp3 file exists in res folder in folder src.
EDIT: Replace your code and watch exception, it's here not in clipStart method:
private Clip clipOpen(String name){
URL url = getClass().getResource(name);
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(stream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
ex.printStackTrace()
}
return null;
}

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