I want a JTextArea
in a certain position. I tried several things like using different LayoutManager
s, no LayoutManager
at all, setLayout(null)
etc. Whatever I do, it seems like setBounds()
, setLocation()
and setSize()
aren't working here, but I read about it and it said it should work. So what am I doing wrong?
The JTextArea
is always too high and the position doesn't change if I change the Parameters in setBounds()
.
public class textarea extends JPanel {
public static void main(String[] args){
JFrame frame = new JFrame("text area");
textarea content = new textarea();
frame.setContentPane(content);
frame.setLocation(120,70);
frame.pack();
frame.setVisible(true);
frame.setSize(700,500);
}
JPanel PanelForText;
public textarea(){
setBackground(Color.LIGHT_GRAY);
setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
txtArea txt = new txtArea();
PanelForText = new JPanel();
PanelForText.setPreferredSize(new Dimension(500,300));
PanelForText.setBorder(BorderFactory.createEtchedBorder());
PanelForText.add(txt);
add(PanelForText);
}
}
public class txtArea extends JPanel {
boolean textAreaCreated = false;
public txtArea(){
setBackground(Color.WHITE);
setPreferredSize(new Dimension(496, 290));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.GRAY);
g.fillRect(50, 25, 400, 245);
if (!textAreaCreated)
createTextArea();
}
public void createTextArea() {
JTextArea Text = new JTextArea();
Text.setBounds(500,300,300,300);
Text.setOpaque(false);
Text.setWrapStyleWord(true);
Text.setLineWrap(true);
Text.setBorder(BorderFactory.createLineBorder(Color.RED));
add(Text);
textAreaCreated = true;
}
}
Here is what I want it to look like:
And here is what it currently looks like:
I did a few tutorials where they used JTextField
s that were added to JPanel
s, but I was wondering if I could just use a JTextField
or JTextArea
for more text WITHOUT adding it to a Panel first!
Like I said, I was looking up "how to set JTextArea
position" and it said to use setBounds()
. Apparently that's not correct.. So again, all I want to know is how to do it better. Also: I did read a lot about the LayoutManager
s, but for me trying to use it is more helpful than just reading about it...
I tried that with rows and columns, but it didn't change the fact that the JTextArea
was not in the right position.
What I did was (in the CreateTextArea method):
public void createTextArea() {
JTextArea Text = new JTextArea(5,1);
Text.setOpaque(false);
Text.setWrapStyleWord(true);
Text.setLineWrap(true);
Text.setBorder(BorderFactory.createLineBorder(Color.RED));
add(Text);
textAreaCreated = true;
}