How to have custom drag and drop support in Java Swing - java

I have enabled the default custom drag and support for a JTree, it works like a charm :)
I have one tree, one text and one editor pane, if I drag any node from the tree to the text area, it pastes the text, but when I do the same thing to the editor pane, it doesn't copy the plain text, it copies the text with bullet and changes the entire layout.
All I need is to copy the plain text to the editor pane, this only happens when I set the content type to "plain/text" when the change the content type it will copy with bullet symbol...
Is there any possibility that when I drop to the text area/editor pane, instead of name of node, it should place 'name of the node +"?"', I have googled it but only can find how to enable the drag and support for JLabel.
package testing_dragging;
import java.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
public class test_dragging_form extends javax.swing.JFrame {
/**
* Creates new form test_dragging_form
*/
public test_dragging_form() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
jEditorPane1 = new javax.swing.JEditorPane();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTree1.setDragEnabled(true);
jTree1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jTree1MouseMoved(evt);
}
});
jScrollPane1.setViewportView(jTree1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setDragEnabled(true);
jScrollPane2.setViewportView(jTextArea1);
try
{
jEditorPane1.setPage("file:///home/rocky/Desktop/test_plan_template.html");
}
catch(Exception ex)
{
System.out.println("Some exception occured"+ ex.getMessage());
}
jEditorPane1.setDragEnabled(true);
jScrollPane3.setViewportView(jEditorPane1);
jLabel1.setText("draglabel");
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jLabel1MousePressed(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()
.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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(jLabel1))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 12, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jLabel1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
pack();
}// </editor-fold>
private void jTree1MouseMoved(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
JComponent comp = (JComponent)evt.getSource();
TransferHandler handler = comp.getTransferHandler();
comp.setTransferHandler(handler);
handler.exportAsDrag(comp, evt, TransferHandler.COPY);
}
private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
JComponent comp = (JComponent)evt.getSource();
TransferHandler handler = new TransferHandler("text");
comp.setTransferHandler(handler);
handler.exportAsDrag(comp, evt, TransferHandler.COPY);
}
/**
* #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(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(test_dragging_form.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 test_dragging_form().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTree jTree1;
// End of variables declaration
}

I have a little experience with custom drag'n'drop and may be your problem has better solution, but this works:
Make your custom dropTarget for JEditorPane. It will pick the text/plain DataFlavor instead of default text/html one;
class JEditorPaneDropTarget extends DropTargetAdapter{
JEditorPaneDropTarget(JEditorPane pane) {
new DropTarget(pane, this);
}
#Override
public void drop(DropTargetDropEvent dtde) {
Transferable tr = dtde.getTransferable();
Object data;
try {
DataFlavor df = new DataFlavor("text/plain; class=java.lang.String");
data = tr.getTransferData(df);
JEditorPane pane = (JEditorPane) ((DropTarget)dtde.getSource()).getComponent();
pane.setText((String)data);
} catch (Exception e) {
//
}
}
}
Initialize it with your jEditorPane1 somewhere in initComponents():
new JEditorPaneDropTarget(jEditorPane1);
Here are no checks for possible null or cast exceptions, so you will need those too.
Read something about DataFlavors and how to use them. May be there is a way to mention right DataFlavor to use without writing whole custom DropTarget class, but i didn't find any.

Related

passing information from one jframe to another

To begin with, I know that using multiple jframes is frowned upon, unfortunately i have gotten myself to deep into this project to start over. my issue is i cannot find a way to transfer data (user input) from one frame to another, i will provide the code i need to be transferred from frame 1 to another frame
this is my code for the name and email they have to input
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
here is the button code to go to the new frame
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
i am new to swing and i dont need someone to complete my program. i just need to know how to carry it over to a new text box on a new frame.
Doing this is fairly easy. All you need to do is to set a constructor in which you are passing your frame with the values you need over to your new frame.
For example, I have a LoginScreen.java and DoctorScreen.java. If my user successfully entered his details and logs in, I transfer an ArrayList of Doctors from one JFrame to another JFrame, or more precisely, from one java class to another by creating a new instance of that class
Example here
Passing an arraylist from LoginScreen.java to DoctorScreen.java
DoctorScreen dScreen = new DoctorScreen(frame, docList,d);
Now Taking those values passed from LoginScreen.java and setting them in DoctorScreen.java
public DoctorScreen(JFrame frame, ArrayList<Doctor> docList, Doctor d) {
// TODO Auto-generated constructor stub
dialog = new JFileChooser(System.getProperty("user.dir"));
this.frame = frame;
this.docList = docList;
this.d = d;
initialize();
}
Now, you can change the DoctorScreen Constructor to fit into whatever project you are trying to do.
The steps I would advise you to take is to create a Java file for handling your input, and the second Java file to display what you entered in the first file
EG:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String field1 = txtrEnterYourFull.getText();
String name = nameL.getText();
String field2 = txtroptionalEnterYour.getText();
Display display = new Display(name, field1, field2);//using this as example
}
}
Then in your display.java, call your constructor taking in these fields and display them either in a textfield/textarea or in a JLabel in your frame
String name, field1, field2;
public Display(String name, String field1, String field2){
this.name = name;
this.field1 = field1;
this.field2 - field2;
}
Please take note that these variables have already been declared and I am merely using this for demonstration purposes.
Frames are like any other class, so just use the same kind of strategies you use to pass data between any other classes. For example you can simply create setter methods in your second frame class and call them from the first frame.
Note: This is just something I threw together really fast in Netbeans so there is a lot of generated code. Also, this is strictly an example I'm not saying it's necessarily the best way to do this.
Here is a quick and dirty example of how you might pass data between two JFrame objects:
This is the code to pay attention to from Frame1:
private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {
Frame2 otherFrame = new Frame2();
otherFrame.setTextFieldText(jTextField1.getText());
otherFrame.setTextAreaText(jTextArea1.getText());
otherFrame.setVisible(true);
}
Here is the full code for Frame1:
public class Frame1 extends javax.swing.JFrame {
/**
* Creates new form Frame1
*/
public Frame1() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
sendToOtherFrameBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setText("text area data");
jScrollPane1.setViewportView(jTextArea1);
jTextField1.setText("text field data");
sendToOtherFrameBtn.setText("Send To Other Frame");
sendToOtherFrameBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendToOtherFrameBtnActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(99, 99, 99)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(sendToOtherFrameBtn)))
.addContainerGap(135, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(sendToOtherFrameBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
pack();
}// </editor-fold>
private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {
Frame2 otherFrame = new Frame2();
otherFrame.setTextFieldText(jTextField1.getText());
otherFrame.setTextAreaText(jTextArea1.getText());
otherFrame.setVisible(true);
}
/**
* #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(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame1.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 Frame1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton sendToOtherFrameBtn;
// End of variables declaration
}
Here is the important code from Frame2:
public void setTextFieldText(String txt){
jTextField1.setText(txt);
}
public void setTextAreaText(String txt){
jTextArea1.setText(txt);
}
Here is the full code for Frame2:
public class Frame2 extends javax.swing.JFrame {
/**
* Creates new form Frame2
*/
public Frame2() {
initComponents();
}
public void setTextFieldText(String txt){
jTextField1.setText(txt);
}
public void setTextAreaText(String txt){
jTextArea1.setText(txt);
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
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(111, 111, 111)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(jTextField1))
.addContainerGap(123, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(52, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99))
);
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(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame2.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 Frame2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

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.

Adding element in Java Netbeans generated combo box

I'm having some problem in adding new elements to the combo box. The code is created by Netbeans Form Editor, because of this I only have access to modify the event listeners. The elements cant be predefined because the elements are in a database and constantly expanding. Currently the combo box has only one element and i would like it to update according to the values from the database. Thank you for your time folks.
package Interface;
/**
*
* #author Raam
*/
public class Welcome extends javax.swing.JFrame {
/**
* Creates new form Welcome
*/
public Welcome() {
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() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("addNewRecord");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Add New Record", "Class", "Section", "Student" }));
jComboBox1.setToolTipText("Add New Record");
jComboBox1.setName("AddNewRecord"); // NOI18N
jComboBox1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboBox1FocusGained(evt);
}
});
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Choose Class" }));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jButton1.setText("Open Database");
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(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jComboBox1FocusGained(java.awt.event.FocusEvent evt) {
jComboBox1.addElement(); //Tried this, not working
}
/**
* #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(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Welcome.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 Welcome().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
// End of variables declaration
}
You have to add the ítem in the model:
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBox1.getModel();
model.addElement("new ítem");
Can be done by going to properties of the combo box then to >> model. As the answer provided here https://stackoverflow.com/a/39689417/5737654

How to take values from 10 textFields and using one button to output the choices into a textField or Area? (With code)

We're trying to design a set of Textfields where users can enter a value depending on how much quantity of the product they want. We have one button called checkout.
Basically, 2 classes, One called FoodDept (where all the textfields are and the checkout Button), and one called Checkout where there is a textfield or Area where i can output the choices or numbers the user indicated. That is basicallly all I need.
package shopping;
import java.util.*;
public class foodDept extends javax.swing.JFrame {
/**
* Creates new form foodDept
*/
int apple;
int banana;
double a = 0;
double b = 0;
public foodDept() {
initComponents();
apple=0;
banana=0;
}
/**
* 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() {
appleLabel = new javax.swing.JLabel();
appleField = new javax.swing.JTextField();
backBtn = new javax.swing.JButton();
bananaLabel = new javax.swing.JLabel();
bananaField = new javax.swing.JTextField();
checkoutBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
appleLabel.setText("Apple ($1.99):");
appleField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
appleFieldActionPerformed(evt);
}
});
backBtn.setText("Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
bananaLabel.setText("Banana ($0.99):");
checkoutBtn.setText("jButton1");
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)
.addGroup(layout.createSequentialGroup()
.addComponent(backBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE)
.addComponent(checkoutBtn))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(appleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(appleField))
.addGroup(layout.createSequentialGroup()
.addComponent(bananaLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, 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(appleLabel)
.addComponent(appleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bananaLabel)
.addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(backBtn)
.addComponent(checkoutBtn))
.addContainerGap())
);
pack();
}// </editor-fold>
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {
new dept().setVisible(true);
dispose();
}
void setApple(int a){
apple=a;
}
int getApple(){
return apple;
}
public double getTotal(){
return a+b;
}
private void appleFieldActionPerformed(java.awt.event.ActionEvent evt) {
}
public void checkoutBtnActionPerformed(java.awt.event.ActionEvent evt) {
try{
double priceOfapple = 1.99;
int quantity = Integer.parseInt(appleField.getText());
double totalamount = priceOfapple*quantity;
checkout.resultField.setText(totalamount);
}
b = Double.parseDouble(bananaField.getText());
foodList fL = new foodList(apple,banana);
if(a > 0){
a=a*1.99;
}
if(b > 0){
b=b*0.99;
}
new checkout().setVisible(true);
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(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//ArrayList<Double> orderList = new ArrayList<Double>();//ARRAYYYYY
//here
//for(int x = 0; x<= orderList.size();x++){
//}
foodDept a = new foodDept();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new foodDept().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JTextField appleField;
private javax.swing.JLabel appleLabel;
private javax.swing.JButton backBtn;
private javax.swing.JTextField bananaField;
private javax.swing.JLabel bananaLabel;
public javax.swing.JButton checkoutBtn;
// End of variables declaration
}
**********************************************************************************
/*
* 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 shopping;
import java.util.ArrayList;
import shopping.foodDept;
import shopping.foodDept;
import shopping.foodDept;
/**
*
* #author Kevin
*/
public class checkout extends javax.swing.JFrame {
/**
* Creates new form checkout
*/
public checkout() {
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() {
backBtn = new javax.swing.JButton();
purchaseBtn = new javax.swing.JButton();
resultField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
backBtn.setText("Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
purchaseBtn.setText("Purchase");
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(resultField)
.addGroup(layout.createSequentialGroup()
.addComponent(backBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 148, Short.MAX_VALUE)
.addComponent(purchaseBtn)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(resultField, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(purchaseBtn)
.addComponent(backBtn))
.addContainerGap())
);
pack();
}// </editor-fold>
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {
new foodDept().setVisible(true);
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(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//for(int x = 0; x<= orderList.size();x++){
//resultField.setText(orderList.get(x));
//}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new checkout().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton backBtn;
private javax.swing.JButton purchaseBtn;
public javax.swing.JTextField resultField;
// End of variables declaration
}
Before start, some off-topic advices:
Please read about Java Code
Conventions
and stick to them because they make your code more readable.
Try to make your GUI classes without using GUI builders and spend some time learning about Swing and writing your classes by your own hand. You'll learn lot of things that builder "hides" you and your code will be simpler and cleaner.
Every Swing application should have only one JFrame. Take a look to this topic: The Use of Multiple JFrames, Good/Bad Practice?
I suspect because of backBtn presence that you're trying to do a kind of wizard. If this is the case I'd suggest you take a look to CardLayout. There are plenty of examples in SO too.
Well the two classes needed are there, you just have to find out the way to communicate them. One approach would be passing a List<String> to the Checkout class so when the JTextArea is initialized it can take this list as data:
public class Checkout extends JDialog {
List<String> dataToBeDisplayed;
...
public void setDataToBeDisplayed(List<String> data) {
this.dataToBeDisplayed = data;
}
private void initComponents() {
JTextArea textArea = new JTextArea(20,30);
for(String line : dataToBeDisplayed) {
textArea.append(line + System.lineSeparator());
}
getContentPane().add(new JScrollPane(textArea));
}
}
The List must be set before the dialog becomes visible, just like this:
Checkout checkout = new Checkout(this, true);
checkout.setDataToBeDisplayed(data); // data must be created and populated before this call
checkout.setVisible(true);

Updating a java jframe

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
}

Categories

Resources