How can I improve the rendering of JLabels?
I am trying to create a quick and dirty swing UI. My UI has a couple of JTextFields, then a JTextArea in a JScrollPane, since the JTextArea's contents may get large.
I am using a simple BoxLayout, I didnt want to waste hours with GridBagLayout.
My problem is, when I resize the window, the JLabels become huge. They will have one single line of text sitting in huge amounts of empty space. It looks ugly and is wasteful. The JTextArea, on the other hand, will never increase in size because JScrollPane takes care of extra content. So I will have huge JTextFields and a tiny JTextArea in a scroll pane with barely one line visible.
Is there an easy way to make sure that the JTextFields never increase their height beyond one line of text 开发者_C百科? Maybe overriding getMaximumSize/getPreferredSize ? If so, what would the code be ?
The only function that will resolve this situation is JFrame.pack(), but it will change the window size(highly undesirable) and sometimes doesnt bother confining itself to the desktop.
label.setMaximumSize( label.getPreferredSize() );
Or better yet, override the getMaximumSize() method to return the preferred size.
Actually, I take that suggestion back since the maximum size of the label is the preferred size. However, that is a technique that will work with other components, like a JTextField for example when using a BoxLayout.
Post your SSCCE that demonstrates the problem.
Edit:
Actually I think the problem is that BoxLayout tries will increase the height of all the components when there is extra space. To solve this you need to use:
panel.add( Box.createVerticalGlue() );
as the last component to prevent extra space from being allocated to the components.
createVerticalGlue() does nothing O_O. Maybe I did it wrong.
Overriding maximum size works wonderfully. Why doesnt Java do it by default ???
public class TextFTest {
/**
* @param args
*/
public static void main(String[] args) {
JFrame jf = new JFrame();
class X extends JTextField {
public X(String text) {
super(text);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(super.getMaximumSize().width,
getPreferredSize().height);
}
}
jf.getContentPane().setLayout(
new BoxLayout(jf.getContentPane(), BoxLayout.Y_AXIS));
X f = new X("Hello");
jf.getContentPane().add(f);
JTextField f1 = new JTextField("Hello1");
jf.getContentPane().add(f1);
jf.getContentPane().add(Box.createVerticalGlue());
jf.validate();
jf.setSize(300, 300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
Please excuse my horrible coding standards.
精彩评论