Reputation: 9
I don't understand why the panel.add(txtnum1)
and panel.add(button2)
doesn't show up when I compile the program. The panel.add(button)
works just fine, my compiler doesn't throw any warning or errors, did I miss something?
package gui;
import javax.swing.*;
import java.awt.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(300, 500));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
frame.getContentPane().add(panel);
JButton button = new JButton("Submit");
panel.add(button);
JTextField txtnum1 = new JTextField();
txtnum1.setPreferredSize(new Dimension(30, 50));
panel.add(txtnum1);
JButton button2 = new JButton("Clear");
panel.add(button2);
}
}
Upvotes: 0
Views: 1537
Reputation: 583
When implementing GUI applications with Swing, I like to have this approach in the code that builds the JFrame
(we assume a simple GUI that does not have JPanel
containers inside JPanel
containers and stuff like that):
JFrame
and initialize itJPanel
JFrame
(repeat from 2) for every JPanel
inside the JFrame
)JFrame
visible on the screenSo, your code would look something like this:
package gui;
import javax.swing.*;
import java.awt.*;
public class GUI {
public static void main(String[] args) {
/* step 1 */
JFrame frame = new JFrame();
frame.setSize(new Dimension(300, 500));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* step 2 */
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
/* step 3 */
JButton button = new JButton("Submit");
panel.add(button);
JTextField txtnum1 = new JTextField();
txtnum1.setPreferredSize(new Dimension(30, 50));
panel.add(txtnum1);
JButton button2 = new JButton("Clear");
panel.add(button2);
/* step 4 */
frame.getContentPane().add(panel);
/* step 5 */
frame.setVisible(true);
}
}
Tested and it works in Eclipse.
Upvotes: 2
Reputation: 177
You should call setVisible(true) at the end, after all components have been added.
Put frame.setVisible(true);
at the end and it will work as expected.
Upvotes: 0