Updating a java jframe - java

I am trying to update the text in a jtextarea stored in a class I created with the netbeans GUI tool.
In my server class I have the following code....
window is the name of the object instance
Message message = (Message) in.readObject();
window.addText(message.getMessage());
The getMessage meathod works and I can output text to the console using this method.
This is the code I have in the GUI class (window) to update the textarea:
public void addText(String txt)
{
jTextArea1.append(txt);
jTextArea2.append(txt);
jTextArea1.updateUI();
jTextArea1.revalidate();
jTextArea1.validate();
jTextArea2.updateUI();
jTextArea2.revalidate();
jTextArea2.validate();
}
However this isn't updating... the method is defiantly receiving the string as I have tried outputting to the console from there (with no problem).
Do I need to refresh the window somehow?
The full GUI class
package hunterinstant;
public class Conversation extends javax.swing.JFrame implements Runnable {
public Conversation() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea2.setColumns(20);
jTextArea2.setEditable(false);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
jButton1.setText("Send");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public void run() {
/*
* 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(Conversation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Conversation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Conversation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Conversation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Conversation().setVisible(true);
}
});
}
public void addText(String txt)
{
jTextArea1.append(txt);
jTextArea2.append(txt);
jTextArea1.updateUI();
jTextArea1.revalidate();
jTextArea1.validate();
jTextArea2.updateUI();
jTextArea2.revalidate();
jTextArea2.validate();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

Related

erreur : Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container

i want to add a JFrame from another class named : Home to the another Jframe in class Dashboard , when i click on on button Home must the content of the Home class be in the mainPnale but when i run it it shows this errer : Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
so please help me thanks alote
this is the Dashboard interface when i click on button Home must import the Panel from class Home like the second pic
this is the interface of class Home
this is the function when click on button home from class Dashboard :
private void panelHomeMouseClicked(java.awt.event.MouseEvent evt) {
panelcontent.removeAll();
Home he = new Home();
panelcontent.add(he);
}
and this is the class Home :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project;
/**
*
* #author MR-INT
*/
public class Home extends javax.swing.JFrame {
/**
* Creates new form Home
*/
public Home() {
initComponents();
}
/**
* 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() {
panelMainContent3 = new javax.swing.JPanel();
lblcontent3 = new javax.swing.JLabel();
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
home_form1 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
panelMainContent3.setPreferredSize(new java.awt.Dimension(300, 350));
lblcontent3.setText("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
javax.swing.GroupLayout panelMainContent3Layout = new javax.swing.GroupLayout(panelMainContent3);
panelMainContent3.setLayout(panelMainContent3Layout);
panelMainContent3Layout.setHorizontalGroup(
panelMainContent3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelMainContent3Layout.createSequentialGroup()
.addGap(375, 375, 375)
.addComponent(lblcontent3)
.addContainerGap(436, Short.MAX_VALUE))
);
panelMainContent3Layout.setVerticalGroup(
panelMainContent3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelMainContent3Layout.createSequentialGroup()
.addGap(153, 153, 153)
.addComponent(lblcontent3)
.addContainerGap(181, Short.MAX_VALUE))
);
jRadioButtonMenuItem1.setSelected(true);
jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton2.setText("jButton2");
jLabel1.setText("Welcome to the main home");
jButton1.setText("jButton1");
jButton3.setText("jButton3");
javax.swing.GroupLayout home_form1Layout = new javax.swing.GroupLayout(home_form1);
home_form1.setLayout(home_form1Layout);
home_form1Layout.setHorizontalGroup(
home_form1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(home_form1Layout.createSequentialGroup()
.addContainerGap(279, Short.MAX_VALUE)
.addGroup(home_form1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, home_form1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(54, 54, 54)
.addComponent(jButton2)
.addGap(318, 318, 318))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, home_form1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(336, 336, 336))))
.addGroup(home_form1Layout.createSequentialGroup()
.addGap(347, 347, 347)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE))
);
home_form1Layout.setVerticalGroup(
home_form1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, home_form1Layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 167, Short.MAX_VALUE)
.addComponent(jButton3)
.addGap(79, 79, 79)
.addGroup(home_form1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addGap(157, 157, 157))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(home_form1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(home_form1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JPanel home_form1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JLabel lblcontent;
private javax.swing.JLabel lblcontent1;
private javax.swing.JLabel lblcontent2;
public javax.swing.JLabel lblcontent3;
private javax.swing.JPanel panelMainContent;
private javax.swing.JPanel panelMainContent1;
private javax.swing.JPanel panelMainContent2;
private javax.swing.JPanel panelMainContent3;
// End of variables declaration
}

Why are my overridden paintComponent methods not being called

I am using Netbeans. I set up a graphics program to do graphing. I overrode 3 JPanel paintComponent methods just to get started but these methods are not being called.
I have programs that work. My new override code looks the same. I've tried a plethora of things and have run out of ideas. I am using Borderlayout for the first time but that shouldn't cause a problem.
import java.awt.Graphics;
import java.awt.Graphics2D;
/*
* To change this license header, choose License Headers in Project
*Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class MainForm extends javax.swing.JFrame
{
/**
* Creates new form NewJFrame
*/
public MainForm()
{
initComponents();
initProgram();
}
private void initProgram()
{
System.out.println("InitProgram");
}
/**
* 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()
{
pnlPrintPanel = new javax.swing.JPanel();
pnlGraphForm = new javax.swing.JPanel();
pnlGraph = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
pnlInputPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pnlGraphForm.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
pnlGraph.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jLabel2.setText("jLabel2");
javax.swing.GroupLayout pnlGraphLayout =
new javax.swing.GroupLayout(pnlGraph);
pnlGraph.setLayout(pnlGraphLayout);
pnlGraphLayout.setHorizontalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
pnlGraphLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(277, 277, 277))
);
pnlGraphLayout.setVerticalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphLayout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(204, Short.MAX_VALUE))
);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout pnlGraphFormLayout =
new javax.swing.GroupLayout(pnlGraphForm);
pnlGraphForm.setLayout(pnlGraphFormLayout);
pnlGraphFormLayout.setHorizontalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pnlGraphFormLayout.setVerticalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())
);
pnlGraph = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraph.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
pnlInputPanel.setBorder(
javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlInputPanelLayout =
new javax.swing.GroupLayout(pnlInputPanel);
pnlInputPanel.setLayout(pnlInputPanelLayout);
pnlInputPanelLayout.setHorizontalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(271, 271, 271)
.addComponent(jButton1)
.addContainerGap(297, Short.MAX_VALUE))
);
pnlInputPanelLayout.setVerticalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
javax.swing.GroupLayout pnlPrintPanelLayout =
new javax.swing.GroupLayout(pnlPrintPanel);
pnlPrintPanel.setLayout(pnlPrintPanelLayout);
pnlPrintPanelLayout.setHorizontalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pnlPrintPanelLayout.setVerticalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
pnlGraphForm = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraphForm.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
getContentPane().add(pnlPrintPanel, java.awt.BorderLayout.CENTER);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("BUTTON");
pnlGraphForm.paintComponents((Graphics2D)
pnlGraphForm.getGraphics());
}
/**
* #param args the command line arguments
*/
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(MainForm.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel pnlGraph;
private javax.swing.JPanel pnlGraphForm;
private javax.swing.JPanel pnlInputPanel;
private javax.swing.JPanel pnlPrintPanel;
// End of variables declaration
}
At this stage, I expected to see the panel/method names printed but it isn't happening

Unable to append text from a separate class to a JTextArea - Java

I'm currently having trouble (as the title states) appending text to a JTextArea from a separate class (or thread).
Here is my code, since I don't know what's causing the problem. (note that I'm using the Netbeans generated code for my GUI):
Chat Box GUI:
public class ChatBoxGUI extends javax.swing.JFrame
{
/**
* Creates new form ChatBoxGUI
* #return
*/
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
public void setLabels(java.net.SocketAddress address, int port) {
this.addressLabel.setText("IP Address: " +address);
this.portLabel.setText("Port: " +Integer.toString(port));
}
public ChatBoxGUI() {
initComponents();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
startServerButton = new javax.swing.JButton();
connectServerButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
addressLabel = new javax.swing.JLabel();
portLabel = new javax.swing.JLabel();
outputTextField = new javax.swing.JTextField();
stopButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
inputOutputTextArea = new javax.swing.JTextArea();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
startServerButton.setText("Start Server");
startServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startServerButtonActionPerformed(evt);
}
});
connectServerButton.setText("Connect to Server");
connectServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectServerButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
jLabel1.setText("Isaac's Chat Box");
addressLabel.setText("IP Address:");
portLabel.setText("Port: ");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
inputOutputTextArea.setEditable(false);
inputOutputTextArea.setColumns(20);
inputOutputTextArea.setRows(5);
jScrollPane2.setViewportView(inputOutputTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2)
.addComponent(outputTextField, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(startServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(connectServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(addressLabel))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(stopButton)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(portLabel)))
.addGap(0, 18, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startServerButton)
.addComponent(jLabel1)
.addComponent(stopButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(connectServerButton)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addressLabel)
.addComponent(portLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(outputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void startServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
CreateServerDialog createServerDialog = new CreateServerDialog(this, true);
createServerDialog.setVisible(true);
try {
Runnable serverClassRunnable = new ServerClass(createServerDialog.getPort());
Thread serverClassThread = new Thread(serverClassRunnable);
serverClassThread.start();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
private void connectServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
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(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatBoxGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel addressLabel;
private javax.swing.JButton connectServerButton;
private javax.swing.JTextArea inputOutputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField outputTextField;
private javax.swing.JLabel portLabel;
private javax.swing.JButton startServerButton;
private javax.swing.JButton stopButton;
// End of variables declaration
}
Create Server Dialog:
public class CreateServerDialog extends javax.swing.JDialog {
private int port; private boolean isValid = false; private java.awt.Frame parent;
public int getPort() {
return port;
}
/**
* Creates new form CreateServerDialog
*/
public CreateServerDialog(java.awt.Frame par, boolean modal) {
super(par, modal);
parent = par;
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
portInput = new javax.swing.JTextField();
okButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Enter Port:");
okButton.setText("Ok");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(okButton)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(portInput)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(portInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton))
);
pack();
}// </editor-fold>
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
ErrorDialog errorDialog = new ErrorDialog(parent, true);
try {
port = Integer.parseInt(this.portInput.getText());
isValid = true;
} catch (NumberFormatException n) {
errorDialog.errorOccured(0);
isValid = false;
}
if (port <= 1024 || port > 65535) {
errorDialog.errorOccured(0);
isValid = false;
}
if (isValid == true) {
this.dispose();
}
}
/**
* #param args the command line arguments
*/
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(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CreateServerDialog dialog = new CreateServerDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JButton okButton;
private javax.swing.JTextField portInput;
// End of variables declaration
}
Server Class:
import java.io.*;
import java.net.*;
public class ServerClass implements Runnable
{
private final ServerSocket serverSocket;
public ServerClass(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
ChatBoxGUI chatBoxGUI = new ChatBoxGUI();
try {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort()); //this is the code that isn't working
Socket server = serverSocket.accept();
System.out.println();
chatBoxGUI.setLabels(server.getLocalSocketAddress(), serverSocket.getLocalPort()); //this also isn't working - but that's not the focus of this question
DataOutputStream out = new DataOutputStream(server.getOutputStream());
DataInputStream in = new DataInputStream(server.getInputStream());
chatBoxGUI.getTextArea().append("\nClient found! Connected with: " +server.getRemoteSocketAddress());
//note: this part isn't finished - but it doesn't need to be for that code to work
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've tried to do research on the problem, and what I've found tells me that I have to use either invokeLater or invokeAndWait when running the code so that it runs in the EDT. And I have tried to implement this but it still doesn't seem to work:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort());
}
});
Similar output to the terminal works completely fine, so it's definitely an issue with appending the text.
Any help would be appreciated, and thanks in advance.
You have multiple instances of the ChatBoxGUI class, so you are not updating the text area that is visible on the desktop.
So first you create the ChatBoxGUI class. Then when you click on a button you create the ServerClass. In the ServerClass you create a second instance of the ChatBoxGUI.
Don't create the second instance of the ChatBoxGUI class!!!
Instead, if you want to access variables in the ChatBoxGUI class then you need to:
pass a reference of the ChatBoxGUI class to the ServerClass
save this reference as an instance variable in the ServerClass
access this variable when you want to add text to the text area.
Without a more complete example, all I can do is link you to this question that has an answer for a similar issue.
Or you could try changing your approach from:
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
To:
public void setTextArea(String textToAppend)
{
inputOutputTextArea.append(textToAppend);
}

why calling a chat application from Jframe doesn't work?

I hope someone here can help me, I have 3 Jframes: Server, Client and Call_Client, when I run the Server then the Client, every thing is Ok and connection is estabished successefuly, but if I try to call "Call_Client" which contain a Jbutton will call a new Client, the Client Jframe appears but without connecting to the Server
Here is the Server code:
package javaapplication7;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* #author Win
*/
public class ser extends javax.swing.JFrame {
static ServerSocket ss;
static Socket s;
static DataInputStream dun;
static DataOutputStream dout;
/**
* Creates new form ser
*/
public ser() {
initComponents();
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
msg_area = new javax.swing.JTextArea();
msg_text = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
msg_area.setColumns(20);
msg_area.setRows(5);
jScrollPane1.setViewportView(msg_area);
msg_text.setText("jTextField1");
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(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(27, 27, 27))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(27, 27, 27))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)))
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String msgout = "";
msgout = msg_text.getText().trim();
dout.writeUTF(msgout);
} catch (Exception e) {
}
}
/**
* #param args the command line arguments
*/
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(ser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ser().setVisible(true);
}
});
String msgin = "";
try{
ss = new ServerSocket(80);
s = ss.accept();
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
while(!msgin.equals("Exit")){
msgin = dun.readUTF();
msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
}
}catch(Exception e){}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea msg_area;
public javax.swing.JTextField msg_text;
// End of variables declaration
}
Client code:
package javaapplication7;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
*
* #author Win
*/
public class kel extends javax.swing.JFrame {
static Socket s;
static DataInputStream dun;
static DataOutputStream dout;
/**
* Creates new form kel
*/
public kel() {
initComponents();
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
msg_area = new javax.swing.JTextArea();
msg_text = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
msg_area.setColumns(20);
msg_area.setRows(5);
jScrollPane1.setViewportView(msg_area);
msg_text.setText("jTextField1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(26, 26, 26)
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(71, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String msgout = "";
msgout = msg_text.getText().trim();
dout.writeUTF(msgout);
} catch (Exception e) {
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws IOException {
/* 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(kel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(kel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(kel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(kel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new kel().setVisible(true);
}
});
try{
s = new Socket("localhost", 80);
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while(!msgin.equals("Exit")){
msgin = dun.readUTF();
msg_area.setText(msg_area.getText().trim()+"\n serveur :\t"+msgin);
}
}catch(Exception e){}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea msg_area;
public javax.swing.JTextField msg_text;
// End of variables declaration
}
Here is my Call_Client Interface code:
package javaapplication7;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import static javaapplication7.Serveur.s;
/**
*
* #author Win
*/
public class Tes extends javax.swing.JFrame {
/**
* Creates new form Tes
*/
public Tes() {
initComponents();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("Appeler");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 60, -1, -1));
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
kel k = new kel();
k.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws IOException {
/* 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(Tes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Tes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Tes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Tes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Tes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Please I need Help, I'm new in Java and thunk you.

JScrollPane scrollbar disappears on window resizing

This is an attempt to get two JEditorPane components sharing a common scrollbar and displaying the same content fetched over a URL. But, I am facing these challenges:
JEditorPane translation (right one) is not getting the HTML content helpURL (common expected).
Edit: Any of the two and one at a time is showing the content right, plus there is no exception thrown.
The scroller (to outermost JScrollPane panelScrollPane) disappears on window resizing.
Fot tl;dr: Find scrollbar policy in myInitComponents method and content setting in fetchURL method.
package test;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
public class URLReader extends javax.swing.JFrame {
/**
* Creates new form URLReader
*/
public URLReader() {
initComponents();
myInitComponents();
}
/**
* 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() {
panelScrollPane = new javax.swing.JScrollPane();
contentPanel = new javax.swing.JPanel();
leftScrollPane = new javax.swing.JScrollPane();
content = new javax.swing.JEditorPane();
rightScrollPane = new javax.swing.JScrollPane();
translation = new javax.swing.JEditorPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
contentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Content Panel", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
leftScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Content"));
content.setContentType("text/html"); // NOI18N
content.setAutoscrolls(false);
leftScrollPane.setViewportView(content);
rightScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Translation"));
rightScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
translation.setContentType("text/html"); // NOI18N
rightScrollPane.setViewportView(translation);
javax.swing.GroupLayout contentPanelLayout = new javax.swing.GroupLayout(contentPanel);
contentPanel.setLayout(contentPanelLayout);
contentPanelLayout.setHorizontalGroup(
contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(contentPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(leftScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(rightScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
.addContainerGap())
);
contentPanelLayout.setVerticalGroup(
contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(contentPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(leftScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addComponent(rightScrollPane))
.addContainerGap())
);
panelScrollPane.setViewportView(contentPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.addGap(12, 12, 12))
);
pack();
}// </editor-fold>
private void myInitComponents(){
leftScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
leftScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
rightScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
rightScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panelScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
/*
content.setLineWrap(true);
content.setWrapStyleWord(true);
translation.setLineWrap(true);
translation.setWrapStyleWord(true);
*/
}
private void fetchURL(String url){
try{
// URL(URL baseURL[, String relativeURL])
URL helpURL = new URL(url);
this.content.setPage(helpURL);
this.translation.setPage(helpURL);
}
catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + url);
}
// return this.content;
}
/**
* #param args the command line arguments
*/
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(URLReader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(URLReader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(URLReader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(URLReader.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() {
String url = "http://hi.wikipedia.org/wiki/%E0%A4%AE%E0%A5%81%E0%A4%96%E0%A4%AA%E0%A5%83%E0%A4%B7%E0%A5%8D%E0%A4%A0";
URLReader reader = new URLReader();
reader.fetchURL(url);
reader.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JEditorPane content;
private javax.swing.JPanel contentPanel;
private javax.swing.JScrollPane leftScrollPane;
private javax.swing.JScrollPane panelScrollPane;
private javax.swing.JScrollPane rightScrollPane;
private javax.swing.JEditorPane translation;
// End of variables declaration
}
P.S.: I am passing full code (NetBeans IDE) for better perspective, if not suitable, please direct so, I will try to shorten this. Thanks.

Categories

Resources