I am working on a Java project for college that involves us setting up a TCP Server and Client. I have that part working and now to add more of a feel to my project I want to add a GUI.
We have not begun learning about GUI's in Java yet. However I want to try as I think it would be a useful exercise. I have a very basic GUI set up and the appropriate ActionListener set for the button. My next problem is positioning my panels so they look neat and tidy on the Frame...
At the moment I have all the components in one panel as seen below:
public ClientGUI(){
//Initialise Frame
frame = new JFrame("TCP Client");
//Initialise Panel 1 & Components
p1 = new JPanel();
//Set Layout
p1.setLayout(new GridLayout(1,2));
//Label 1 - For TextArea
l1 = new JLabel("Chat Log");
p1.add(l1);
//TextArea - To display conversation
t1 = new JTextArea(10,10);
p1.add(t1);
//Label 2 - For TextField
l2 = new JLabel("Message");
p1.add(l2);
//Message Box - For user input
t2 = new JTextField(10);
p1.add(t2);
//Button 1 - To send message
b1 = new JButton("Send");
p1.add(b1);
//Add panels to frame
frame.add(p1);
//Frame properties...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
//Add Event listener to button
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
//do something
t1.setText(t2.getText());
}
});
I would love for it to look something like the rough wireframe below.
I'd appreciate any feedback anyone might have! Thanks very much.
What you want is called the BoxLayout, which feeds UI elements in columns or rows. And then you can nest them one inside another, e.g. have one horizontal box layout panel as an element in another that is vertical (kind of like nested HTML tables). So all of your elements would go in a top level vertical BoxLayout and the line that has JLabel2 and JTextField would be its own horizontal BoxLayout nested in the top level vertical layout. Here is a pretty decent tutorial about layout managers and it includes the BoxLayout.