I have a GUI, which is based on Swing's JPanelthat uses BorderLayout.In the north panel i have added a new JPanel which uses FlowLayout and contains two textField and other components. When I change the text of textField and invisible some componets inside this panel, this textField keeps resizing. How can I avoid this? I would like the textField to keep the same size whatever happens. I've tried setSize, setPreferredSize, setMinimumSize with no success.
txtSource = new WebTextField(source);
txtSource.setMaximumSize(new Dimension(30,20));
txtSource.setMinimumSize(new Dimension(20, 20));
txtSource.setEditable(false);
txtDestination = new WebTextField(destination);
txtDestination.setMaximumSize(new Dimension(30,20));
txtDestination.setMinimumSize(new Dimension(20, 20));
before:
after:
When I change the text of textField and invisible some componets inside this panel, this textField keeps resizing.
This example shows text fields at a constant size. Can you add an SSCCE of code that does not?
import java.awt.*;
import javax.swing.*;
class TextFieldSize {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextField smallField = new JTextField(5);
JTextField largeField = new JTextField(20);
JPanel gui = new JPanel(new FlowLayout());
gui.add( smallField );
gui.add( largeField );
JFrame f = new JFrame("Text Field Size");
f.add(gui);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
//This works best for me:
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class NoResizeJTextField {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,300));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("Text: "));
JTextField tf = new JTextField(30);
tf.setMaximumSize(tf.getPreferredSize());
tf.setMinimumSize(tf.getPreferredSize());
panel.add(tf);
frame.add(panel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.pack();
frame.setVisible(true);
}
});
}
}
您无法按照自己的意愿执行此操作,有些LayoutManagers
会忽略setXxxSize
,但是您可以使用接受setXxxSize
fe BoxLayout
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.