getting a bit confused with GridBagLayout.
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
public class MihatteFrame extends JFrame {
private JTextArea area;
private JTextField textField;
private Button b;
final static boolean shouldFill = true;
public MihatteFrame() {
setTitle("見張ってしながら...");
setSize(500,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
area = new JTextArea(5, 15);
area.setEditable(false);
area.setCursor(null);
area.setOpaque(false);
area.setFocusable(false);
area.setLineWrap(true);
area.setWrapStyleWord(true);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
this.add(area, c);
textField = new JTextField(20);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
this.add(textField);
//textField.addActionListener(this);
b = new Button("Proceed");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 2;
c.gridy = 0;
this.add(b);
setVisible(true);
}
public void displayText(String text) {
area.setText(text);
//textField.setText(text)
}
}
I understand the basics and its working well, it`s sorting out the resizing (specifically downsizing) issue.
When the text areas weight is 0 and the text fields weight is 1, there is no problem with resizing, but the text area is in the centre and not right up against the left-hand side, despite the anchoring.
When the text areas weight is anything above 0 and the text fields weight correlates (eg. 0.2/0.8), everything looks snug as a bug, and upsizing is fine, but downsizing, the text field is reduced to 1 character wide.
I dont mind the text area resizing with the frame, but I want it to return to its original size when the frame is made smaller, not shove the textfield against the proceed button.
I have read that I may need to put this in a JPanel border layout - am not sure what this would look like in code, so if anyone could tell me what goes where if that is the case, would be grateful.
So questions:
- Is there a way to make the text area stay anchored to the West AND not have the textfield reduced to a small size when resized?
- Why are my anchors not working?
- Do I need to put the text area in a JPanel with relation to another layout, and if so, where does the code go?
- Why does everyone fear GridBagLayout? The amount of "I avoid this at all costs" I`ve seen...
Thank you! (Ps. am halfway through implementing actionlistener, so if it looks half-complete, that`s why).