这是我启动窗口时的样子:
这就是我想要的:
这是我用过的代码:
主要:
public void main()
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGui();
}
});
}
创建并展示gui
public static void createAndShowGui()
{
Frame chatPanel = new Frame();
JFrame frame = new JFrame("Chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(chatPanel);
//Ensure the frame is the minimum size it needs to display properly
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
框
public class Frame extends JPanel implements ActionListener
{
public static JTextArea textArea_send = new JTextArea(5, 14);
public static JTextArea textArea_receive = new JTextArea(15, 20);
private JButton send_button = new JButton("Send");
private JLabel receiver = new JLabel("Salon");
public Frame()
{
//Set the frame icon to an image loaded from a file.
//this.setIconImage(new ImageIcon(url).getImage());
JPanel AreaGrid = new JPanel();
AreaGrid.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = gbc.gridy = 0; =
gbc.gridwidth = GridBagConstraints.REMAINDER; =
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.insets = new Insets(10, 15, 0, 0);
this.add(receiver, gbc);
/* Next component*/
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.;
gbc.weighty = 1.;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START; // pas WEST.
gbc.insets = new Insets(30, 15, 0, 10);
this.add(new JScrollPane(textArea_receive,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), gbc);
/* next component */
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.BASELINE;
gbc.insets = new Insets(15, 15, 15, 10);
this.add(new JScrollPane(textArea_send,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), gbc);
/* Button */
gbc.gridx = 1;
this.add(send_button);
textArea_receive.setEditable(false);
textArea_send.setEditable(true);
send_button.addActionListener(this);
DefaultCaret caret = (DefaultCaret)textArea_receive.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
我希望我的窗户保持这样的组织,如果我们扩展或减少它,只有两个textArea会改变大小。目前,textAreas不会调整大小。
欢迎任何建议!
提前致谢,
维克多
答案 0 :(得分:2)
您的课程延伸JPanel
。 JPanel的默认布局管理器是FlowLayout
,这就是组件按原样显示的原因。
JPanel AreaGrid = new JPanel();
AreaGrid.setLayout(new GridBagLayout());
上面的代码什么都不做,因为你从不向“areaGrid”面板添加任何组件。摆脱那些陈述。
您需要做的是设置类本身的布局,因为您将所有组件直接添加到自定义类中:
//JPanel AreaGrid = new JPanel();
//AreaGrid.setLayout(new GridBagLayout());
this.setLayout( new GridBagLayout() );