1 Attachment(s)
Problem with placing text with JPanels
Hi! I want to place text-message within 4 JFrames. Running code shows only one message screen-shot is attached.
Would you please suggest the way how to solve this.
Code Java:
package test4_windows;
import java.awt.*;
import javax.swing.*;
public class OutPutWindow {
public OutPutWindow (String msg){
JFrame f = new JFrame("Frame Head");
JTextArea ta = new JTextArea(msg);
f.setSize(300, 300);
//Creating JPanel
JPanel contentPanel1 = new JPanel();
contentPanel1.setBackground(Color.yellow); //set background color
contentPanel1.add(ta); // add text area with message
JPanel contentPanel2 = new JPanel();
contentPanel2.setBackground(Color.green);
contentPanel2.add(ta);
JPanel contentPanel3 = new JPanel();
contentPanel3.setBackground(Color.red);
contentPanel3.add(ta);
JPanel contentPanel4 = new JPanel();
contentPanel4.setBackground(Color.white);
contentPanel4.add(ta);
Container pane = f.getContentPane();
pane.setLayout(new GridLayout(2,2));
pane.add(contentPanel1);
pane.add(contentPanel2);
pane.add(contentPanel3);
pane.add(contentPanel4);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Attachment 1168
Re: Problem with placing text with JPanels
Can you explain what the posted is supposed to do?
Where are the 4 JFrames.
Where are you trying to put text in a JPanel?
Re: Problem with placing text with JPanels
You cannot add a component to multiple containers. When you add the JTextArea to contentPane1, it is added to contentPane1, but when you then add the same JTextArea to contentPane2, it removes it from contentPane1 and then adds it to contentPane2.
On this tutorial: (Using Top-Level Containers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)), it says:
Quote:
Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.
Re: Problem with placing text with JPanels
Thanks for the hint. I've created separate JTextArea for each frame. So it works!
Re: Problem with placing text with JPanels
Sorry, I have forgotten to describe the problem.
In fact the problem is exactly as it was posted within next reply. I can not place same text (JTextArea) four times within four different frames. The only last assignment of JtextArea is displayed.
Re: Problem with placing text with JPanels
A component can only be in one container. The last container it is added to will be its location.