Use arrayList to display in JTextArea - java

I want to be able to display all items in an arrayList in a JTextArea. This is the code I have but it does not work.
public void display()
{
JPanel display = new JPanel();
display.setVisible(true);
JTextArea a;
for (Shape ashape : alist)
{
System.out.println("");
System.out.println(ashape.toString());
a = new JTextArea(ashape.toString());
display.add(a);
}
Container content = getContentPane();
content.add(display);
}

Move
JTextArea a;
inside for loop, like so:
for (Shape ashape : alist) {
System.out.println("");
System.out.println(ashape.toString());
//initialise a here
JTextArea a = new JTextArea(ashape.toString());
display.add(a);
}
Container content = getContentPane();
content.add(display);
}
Also, what does it mean "it doesn't work" in your program?

There are a couple of ways to achieve this. To start with, your example code is creating a new JTextArea for each Shape, but it is only ever adding the last to the UI.
Assuming you want to display all the information in a single text area, you could simply use JTextArea#append, for example
JTextArea a = new JTextArea();
for (Shape ashape : a list)
{
System.out.println(ashape.toString());
a.append(ashape.toString() + "\n")
}
Container content = getContentPane();
content.add(display);
Ps- you may want to wrap the text area within a JScrollPane so it can overflow

Related

How to drag and drop an image from label to label?

I'm new in using the DnD in java.I'm trying to drag an drop an image from a label to another. The first label is the source, the second is the destination. My trouble is that I need to drag the image from the source and recognize that i'm dropping on the correct destination; if the destination is correct the image from the source must disappear, else must come back to the source and notify it to the user using a window message or just a System.out.println(). I've tried using TransferHandler, DragSource, but I didn't get a single good result.
How to drag and drop an image from label to label?
The Drag Listener
public class DragMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
The Source labels that contain the images
public ShipsGUI() {
// setBorder(new EmptyBorder(10,10,10,10));
setLayout(new GridLayout(2, 5));
MouseListener listener = new DragMouseAdapter();
for (int i = 0; i < 10; i++) {
JPanel p = new JPanel(new BorderLayout(5, 0));
JLabel a = new JLabel(ship,JLabel.CENTER);
a.setName("ship");
JLabel n = new JLabel("[" + Integer.toString(i + 1) + "]");
n.setForeground(Color.BLUE);
// a.setBorderPainted(false);
// a.setBackground(Color.white);
// a.setOpaque(true);
//a.setIcon(ship,JLabel.CENTER);
a.setTransferHandler(new TransferHandler("icon"));
a.addMouseListener(listener);
p.add(a);
p.add(n, BorderLayout.LINE_START);
add(p);
}
}
The destination (it's a grid fo labels)
public NewAreaGioco(int r,int c, boolean enable){
this.setLayout(new GridLayout(r,c,1,1));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
JLabel l= new JLabel(" ");
l.setSize(30, 30);
l.setBorder(BorderFactory.createLineBorder(Color.BLUE));
if(enable)l.setTransferHandler(new TransferHandler("icon"));
add(l);
}//fine for
}//fine for
}
Well, you can't use the default TransferHandler class. You need to make your own.
I would start by looking at the DropDemo and ListTransferHandler class found on the examples page of the Drag and Drop tutorial.
A couple of change that I think you will need to make:
export an image instead of text. I think the link provided by Sergiy above might help.
The key point is in the exportDone(...) method. Your cleanup code would set the icon of the source component to null.
You will probably need to read the tutorial to understand the concept of these two classes.

JLabels created from an ArrayList<String> won't appear * when others will *

I am not new to GUI or swing programming, just as a disclaimer.
In my class that extends JPanel, I have an ArrayList< String > opponentNames that I want to use to create JLabels. I have an ArrayList< JLabel > labels to contain the JLabels. I used this list and also I tried to add directly to the frame which is why both are in the code block below. I know that I should just use one.
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
Then later on I added test JLabels in the same exact manner without using my ArrayList < String >:
for(int i = 0; i < 5; i++){
JLabel label = new JLabel(""+i);
label.setVisible(true);
labels.add(label);
this.add(label);
}
This adds 5 JLabels to my panel.
Later on I tried adding all of ArrayList < JLabel > labels again to the panel:
for(JLabel l : labels){
System.out.println(l.getText());
System.out.println(l.isVisible());
this.add(l);
}
In the console, every single label prints out with the proper text (the numbers and the Strings from ArrayList < String> opponentNames) but the only things that appear on the screen are the JLabels 0...4, twice.
TL;DR: All of my JLabels exist and are set visible, but only some are appearing on the screen.
edit: I had a typo: is supposed to be label.setVisible(true); in the first for loop. This code here is not copied and pasted, it is greatly simplified. That was/is not the error in my code.
edit2: Here is runnable code. Of course when I tested it my problem isn't happening here, so that tells me that there is an issue elsewhere in my code.
import javax.swing.JFrame;
public class JLabelTestMain {
public static void main(String[] args) {
TestJLabelCode panel = new TestJLabelCode();
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.validate();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
}
Then the other class:
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestJLabelCode extends JPanel{
private ArrayList<String> opponentNames;
private ArrayList<JLabel> labels;
public TestJLabelCode(){
opponentNames = new ArrayList<String>();
labels = new ArrayList<JLabel>();
opponentNames.add("client1");
opponentNames.add("client2");
opponentNames.add("client3");
opponentNames.add("client4");
opponentNames.add("client5");
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
for(int i=0; i<5; i++){
JLabel label = new JLabel(""+i);
label.setVisible(true);
labels.add(label);
this.add(label);
}
for(JLabel label : labels){
System.out.println(label.getText());
System.out.println(label.isVisible());
add(label);
}
}
}
I assume this, so your class, extends JFrame (or another Swing container, like a JPanel) and that's why you use this.add().
In the first for loop, you add the String s to your frame, not the JLabel.
It should be
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
instead of
for(String s : opponentNames){
JLabel label = new JLabel(s);
s.setVisible(true);
labels.add(s);
this.add(s);
}
Your current code shouldn't even compile, since String doesn't contain a method setVisible(boolean) and if your ArrayList is generic and thus only takes JLabels.
I found out the source of my error. This is a very small piece of a very large networked game. I accidentally created this panel twice. I was repainting the first instance of it, which was initialized without client/opponent names, even though I was properly updating the second instance of it. The print statements in the console were coming from the second instance, while the first instance was the only one displayed.
Thank you to #HovercraftFullOfEels and #Zhedar for your help.

Display an ArrayList<Object> in JTextArea of another class

I have spent all day on the Web and on this site looking for an answer to my problem, and hope you guys can help. First of all, I am trying to display the contents of an ArrayList to a JTextArea when I select the 'report' JButton. The array list is in another class separate from the text area. My problem stems from the fact that the array list is an array of objects, so that when I try to display it I get the error:
The method append(String) in the type JTextArea is not applicable
for the arguments (ArrayList.Account.TransactionObject>)
I can display the array list just fine in the console window but am stumped when it comes to displaying it in the text area. I'm under the assumption that there must be some kind of issue converting the Object to a String, because I have been unable to cast it to a String or call a toString method with the array list. Here is the relevant parts of my code.....
This is the portion in the AccountUI class where I created the JTextArea:
private JPanel get_ReportPane()
{
JPanel JP_reportPane = new JPanel(new BorderLayout());
Border blackline = BorderFactory.createLineBorder(Color.BLACK);
TitledBorder title = BorderFactory.createTitledBorder(blackline, "Transaction Report");
title.setTitleJustification(TitledBorder.CENTER);
JP_reportPane.setBorder(title);
/* Create 'labels' grid and JLabels */
JPanel report_labels = new JPanel(new GridLayout(2, 1, 5, 5));
report_labels.add(new JLabel("Current Account Balance: ", SwingConstants.RIGHT));
report_labels.add(new JLabel("Account Creation Date: ", SwingConstants.RIGHT));
JP_reportPane.add(report_labels, BorderLayout.WEST);
/* Create 'data' grid and text fields */
JPanel JP_data = new JPanel(new GridLayout(2, 1, 5, 5));
JP_data.add(TF_balance2 = new JTextField(10));
TF_balance2.setBackground(Color.WHITE);
TF_balance2.setEditable(false);
JP_data.add(TF_created = new JTextField(10));
TF_created.setBackground(Color.WHITE);
TF_created.setEditable(false);
JP_reportPane.add(JP_data, BorderLayout.CENTER);
/* Create 'buttons' grid and buttons */
JPanel JP_buttons = new JPanel(new GridLayout(2, 1, 5, 5));
JButton JB_report = new JButton("Report");
JB_report.setBackground(Color.GRAY);
JB_report.setMargin(new Insets(3, 3, 3, 3));
JB_report.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
reportAccount();
}
});
JP_buttons.add(JB_report);
JButton JB_close = new JButton("Close");
JB_close.setBackground(Color.GRAY);
JB_close.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
System.exit(0);
}
});
JP_buttons.add(JB_close);
JP_reportPane.add(JP_buttons, BorderLayout.EAST);
/* Create text area and scroll pane */
reportArea.setBorder(blackline);
reportArea.setForeground(Color.BLUE);
reportArea.setLineWrap(true);
reportArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(reportArea);
reportArea.setEditable(false);
JP_reportPane.add(scrollPane, BorderLayout.SOUTH);
return JP_reportPane;
}
This is the method (called from JB_reportAction listener class shown above) where I try to display the array list in the text area (also in AccountUI class):
/**
* Method used to display account transaction history in the text field.
*/
protected void reportAccount()
{
reportArea.append(A.getTransactions());
}
And this is the method in the Account class that I am able to display the Array contents in a console output, but have been unable to figure out how to pass the Array contents to the AccountUI class as a String to display in the text area:
public ArrayList<TransactionObject> getTransactions()
{
for (int i = 0; i < transactionList.size(); i++)
{
System.out.println(transactionList.get(i));
System.out.println("\n");
}
return transactionList;
}
I hope I have clarified my issue without confusing anyone. Any insight would be much appreciated.
Call toString() on the list:
reportArea.append(A.getTransactions().toString());
Or, if you want to display the elements of the list in a different format, loop over the elements:
for (TransactionObject transaction : A.getTransactions()) {
reportArea.append(transaction.toString());
reportArea.append("\n");
}
Loops and types are an essential part of programming. You shouldn't use Swing if you don't understand loops and types.
Also, please respect the Java naming conventions. Variables start with a lower-case letter, and don't contain underscore. They're camelCased.
If you want to append content of objects in ArrayList to JTextArea you can use this :
for (Object obj : arrayList) {
textArea.append(obj.toString() + "");
}
You have to implement and override toString for TransactionObject.

Java iterate through JList which contains JPanel - JLabel

I am trying to iterate over a JList where each item contains:
JPanel - JLabel
Currently what i have is:
System.out.println("Reading all list items:");
System.out.println("-----------------------");
for (int i = 0; i < menuList.getModel().getSize(); i++) {
Object item = menuList.getModel().getElementAt(i);;
System.out.println("Item = " + item);
}
The output i get is:
Item =
javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Instead i want to access the text that is inside the JPanel.
How could this be done?
Edit:
This is how i add my JPanel to the JList
menuList = new JList(v);
v = new Vector <String> ();
menuList.setListData(v);
.....
// get our images
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
// add the images to jlabels with text
JLabel pingLabel = new JLabel("Hi there", pingImage, JLabel.LEFT);
// create the corresponding panels
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// add the labels onto the panels
pingPanel.add(pingLabel);
v.add(pingPanel);
So the text i want to find is "Hi there"
Then what you need is to check for the elements inside that JPanel. I mean, a panel is a container of UI elements, that said, you need to check for the elements, once you checked for that you need to compare whether it is a label or not, if it is a label then you will be able to get the text of that label.
Can't you show us the code, probably could be easier if you provide the snippet.

Refreshing JPanel and Switching JTabbedPane in ActionPerfmored

private void buttonAddJobActionPerformed(java.awt.event.ActionEvent evt) {
try {
retrieveID();
String sqlStm = "INSERT INTO Job (employerID,title,description,type,salary,benefits,vacancies,closing,requirement,placement,applyTo,status,posted,location) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sqlStm);
pst.setInt(1,id);
pst.setString(2,txtTitle.getText());
pst.setString(3,areaDescription.getText());
pst.setString(4,comboType.getSelectedItem().toString());
pst.setString(5,txtSalary.getText());
pst.setString(6,areaBenefits.getText());
pst.setString(7,txtVac.getText());
Date close;
close = txtDate.getDate();
pst.setString(8,sdf.format(close));
pst.setString(9,areaReq.getText());
pst.setString(10,comboPlace.getSelectedItem().toString());
pst.setString(11,txtWeb.getText());
pst.setString(12,comboStatus.getSelectedItem().toString());
Date now = new Date();
pst.setString(13,sdf.format(now));
pst.setString(14,txtLoc.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"You have successfully added a job");
//empty all JTextfields
//switch to another
I am trying to empty the set of JTextFields in the JPanel, but instead of emptying them one by one, can I just refresh the panel? if so, how do you do this. i tried repaint(), revalidate() these dont work. perhaps I am wrong here.
I would also like to switch the JTabbedPane to another Pane, but this doesnt work when I try with this...
JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
sourceTabbedPane.setSelectedIndex(0);
can someone show an example code how to do this.
You could loop through all components that are contained in the panel, and if they are text components, clear their value. The code would be something like this:
private void clearTextFields(Container container)
{
int count = container.getComponentCount();
for (int i = 0; i < count; i++)
{
Component component = container.getComponent(i);
if (component instanceof Container) {
clearTextFields((Container) component);
}
else if (component instanceof JTextComponent) {
((JTextComponent) component).setText("");
}
}
}
This method works recursively and takes care of the case when your panel contains another panel which contains the text fields.
Keep all your JTextFields in a container, and iterate over that container to empty them.
So, somewhere:
ArrayList<JTextField> textFields = new ArrayList<JTextField>();
After all fields are actually created (with JTextField txtTitle = new JTextField() or similar):
textFields.add(txtTitle);
textFields.add(areaDescription);
// ... add all others here
And finally, when you need to clear them all:
for (JTextField tf : textFields) {
tf.setText("");
}

Categories

Resources