有很多不同的方式,也有很多不同LayoutManager
的使用方法。在这里阅读更多关于它们的信息:
这是我制作的一个示例,它使用GridBagLayout
:
//necessary imports
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class Test {
/**
* Default constructor for Test.class
*/
public Test() {
initComponents();
}
public static void main(String[] args) {
/**
* Set look and feel of app
*/
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
/**
* Create GUI and components on Event-Dispatch-Thread
*/
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Test test = new Test();
}
});
}
/**
* Initialize GUI and components (including ActionListeners etc)
*/
private void initComponents() {
JFrame jFrame = new JFrame("Chat Test");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setResizable(false);
//Initialise Panel 1 & Components
JPanel p1 = new JPanel(new GridBagLayout());
JPanel p2 = new JPanel(new GridBagLayout());
//Label 1 - For TextArea
JLabel l1 = new JLabel("Chat Log");
//TextArea - To display conversation
final JTextArea t1 = new JTextArea(10, 10);
JScrollPane pane = new JScrollPane(t1);
//Label 2 - For TextField
JLabel l2 = new JLabel("Message");
//Message Box - For user input
final JTextField t2 = new JTextField(10);
//Button 1 - To send message
JButton b1 = new JButton("Send");
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1;
gc.gridx = 0;
gc.gridy = 0;
p1.add(l1, gc);
gc.gridx = 0;
gc.gridy = 1;
p1.add(pane, gc);
GridBagConstraints gc2 = new GridBagConstraints();
gc2.fill = GridBagConstraints.HORIZONTAL;
gc2.weightx = 1;
gc2.gridx = 0;
gc2.gridy = 0;
gc2.ipadx = 10;
p2.add(l2, gc2);
gc2.gridx = 1;
gc2.gridy = 0;
p2.add(t2, gc2);
gc2.gridx = 1;
gc2.gridy = 1;
p2.add(b1, gc2);
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
//do something
t1.setText(t2.getText());
}
});
jFrame.add(p1, BorderLayout.CENTER);
jFrame.add(p2, BorderLayout.SOUTH);
//pack frame (size JFrame to match preferred sizes of added components and set visible
jFrame.pack();
jFrame.setVisible(true);
}
}