您需要有两个面板,一个用于您的textArea
,一个用于您的输入(在本例中为按钮)。我认为你正在寻找这样的东西:
public class Test
{
public static void createFrame()
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
public static void main(String... args)
{
createFrame();
}
}
如果您希望您的框架看起来更像您正在运行的操作系统的框架,您可以.setLookAndFeel()
在显示之前添加frame
:
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
添加UIManager
看起来像什么(特别是小一点):