我的swing应用程序中遇到JTextArea
的问题。 JTextArea放置在面板的顶部,其宽度应相对于下面的组件。我使用setLineWrap
和setWrapStyleWord
来实现这一目标。
然而,当我打包框架时,下面面板中的组件不会完全可见。我尝试过使用三种不同的布局管理器:BorderLayout
,GridBagLayout
和BoxLayout
。
奇怪的是,使用BorderLayout
和GridBagLayout
,我可以通过pack ()
两次调用JFrame
方法来解决问题。
这里有一个当前情况的截图,在"第二行框架"我两次调用pack方法,除了使用BoxLayout
:
示例代码:
import java.awt.*;
import javax.swing.*;
public class TextAreaWrappingTest
{
public static void main (String [] a) {
SwingUtilities.invokeLater (new Runnable () {
@Override public void run () {
try {
UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
createAndShowGUI ();
}
catch (Exception e) {
e.printStackTrace ();
}
}
});
}
private static void createAndShowGUI () {
int locX = 0, locY = 0, maxHeight = 0;
for (int i = 0; i < 2; i ++) {
locX = 0;
locY = maxHeight;
for (String layoutType : new String [] {"BorderLayout", "BoxLayout", "GridBagLayout"}) {
JFrame frame = new JFrame ("Test");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setContentPane (new MainPanel (layoutType));
frame.pack ();
if (i == 1) frame.pack ();
frame.setLocation (locX, locY);
locX += frame.getWidth () + 10;
maxHeight = Math.max (locY, frame.getHeight () + 10);
frame.setResizable (false);
frame.setVisible (true);
}
}
}
}
class MainPanel extends JPanel
{
public MainPanel (String layoutType) {
// Creating components
JTextArea textArea = new JTextArea ("This text area shows a useful message for the user. The lines should wrap relative to the center panel preferred width.");
textArea.setEditable (false);
textArea.setFont (getFont ());
textArea.setLineWrap (true);
textArea.setWrapStyleWord (true);
JPanel centerPanel = new JPanel (new FlowLayout (FlowLayout.LEFT, 10, 0));
centerPanel.add (new JLabel ("Label :"));
centerPanel.add (new JTextField (20));
// Adding components
if (layoutType.equals ("BorderLayout")) {
setLayout (new BorderLayout (0, 20));
add (textArea, BorderLayout.NORTH);
add (centerPanel, BorderLayout.CENTER);
}
else if (layoutType.equals ("GridBagLayout")) {
setLayout (new GridBagLayout ());
GridBagConstraints c = new GridBagConstraints ();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
add (textArea, c);
c = new GridBagConstraints ();
c.gridy = 1;
c.insets = new Insets (20, 0, 0, 0);
add (centerPanel, c);
}
else if (layoutType.equals ("BoxLayout")) {
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
add (textArea);
add (centerPanel);
}
else throw new IllegalArgumentException ("Invalid layoutName argument");
}
}
我试图在这里找到类似的答案,但我没有设法解决这个问题。我该怎么做才能避免那个双包()?