Reputation:
This program is for math test in a Gui. The header "This test consists..." shows up when I run the gui. When I add more labels and I run the program, the frames is empty. Could somebody help me. Another thing, I would like to add more math problems one after the other. e.g. Exercise 1, and below exercise 2, 3, etc etc. I do not know how to do it either.
public class University {
public static void main (String [] args) {
MathTest mt = new MathTest();
mt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mt.setSize(320, 700);
mt.setVisible(true);
}
}
.
public class MathTest extends JFrame {
public MathTest() {
super("Persistent University- Math Test");
JLabel info = new JLabel(" This test consists of 10 exercises.", SwingConstants.CENTER);
info.setVerticalAlignment(SwingConstants.TOP);
add(info);
JLabel exone = new JLabel("Exercise 1: How much is 1 added to 1?");
JLabel ansone = new JLabel("Your answer, please");
JTextField stu = new JTextField(4); //this for the student to type the answer
add(exone);
add(ansone);
add(stu);
Upvotes: 0
Views: 44
Reputation: 347314
The default layout manager for a JFrame
is a BorderLayout
.
A BorderLayout
by default will only allow a single component to occupy each of it's 5 available positions.
When no constraint is supplied, the default position (or constraint) for BorderLayout
is CENTER
, meaning you are effectively removing the last component you added when you add the next (technically not true, but the effect is close enough to appear to be the same thing)
Take a look at How to Use BorderLayout for more details and Laying Out Components Within a Container for possible solutions...
Upvotes: 1
Reputation: 1954
Make sure your label variable names are not being added to the base panel twice. For example:
JLabel info = new JLabel();
add(info);
info = new JLabel();
add(info);
Will not add two JLables. You need a new object reference for every add()
call.
Please use pack()
after that, of course, before you call setVisible()
.
Also, if you clear your panel, call getContentPane().removeAll()
so that you do not leave those JComponents lingering.
Upvotes: 0