我希望将我的Frame分成两个JPanel,右边的JPanel用作输入和显示的textarea。 但是,我无法在其中输入任何内容,也无法显示任何内容。 代码如下:
JPanel jp1, jp2;
public DemoFrame() {
jp1 = new JPanel();
jp2 = new JPanel();
JLabel label = new JLabel("text");
JTextArea ta = new JTextArea(100,100);
ta.setText("some text");
ta.setSize(300, 300);
jp2.add(label);
jp2.add(ta);
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jp1, jp2);
this.getContentPane().add(jsp);;
setBounds(300, 200, 500, 500);
setVisible(true);
jsp.setDividerLocation(0.5);//
}
答案 0 :(得分:3)
恭喜你,你已成为许多阴谋问题的受害者。
主要罪魁祸首是FlowLayout
,它是JPanel
的默认布局管理器。基本上,当您向面板添加相当大的JTextArea
时,FlowLayout
会尽可能地在可用空间的约束范围内尽可能地尊重首选大小。由于我不是100%肯定的原因,这意味着将组件布置在容器的可见边界之外。
如果输入足够的文字,您将开始看到它。
虽然有很多方法可以解决这个问题,但它们基本上是相同的解决方案 - 使用不同的布局管理器。
对于此示例,我刚刚使用BorderLayout
代替
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
private JPanel jp1, jp2;
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
jp1 = new JPanel();
jp2 = new JPanel(new BorderLayout());
JLabel label = new JLabel("text");
JTextArea ta = new JTextArea(50, 50);
ta.setText("some text");
jp2.add(label, BorderLayout.NORTH);
jp2.add(new JScrollPane(ta));
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jp1, jp2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(jsp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}