I am new to Java Applet programming and Java in general but I am very good in C# and C++. Anyway I am making a simple calculator with a JTextField, JButton and JLabel. But the JButton and JTextField take up the whole screen and the strangest thing is I set the size and it is not setting the size. So what am I doing wrong? Here is the code below so somebody can please help me; I will appreciate any answers.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.swing.JApplet;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JTextField;
/**
*
* @author Danny
*/
public class Applet extends JApplet {
private JButton button1;
private JTextField textBox1;
@Override
public void paint(Graphics g)
{
g.setFont(new Font("Courier", Font.PLAIN, 12));
g.drawString("Enter a number: ", 36, 36);
return;
}
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
@Override
public void init() {
button1 = new JButton("Calculate");
textBox1 = new JTextField("number");
textBox1.setFont(new Font("Courier", Font.PLAIN, 12));
textBox1.setSize(100, 36);
button1.setSize(100, 36);
textBox1.setLocation(new Point(36, 76));
button1.setLocation(new Point(36, 70));
Container c = getContentPane();
c.add(button1);
c.add(textBox1);
c.setBackground(Color.gray);
}
// TODO overwrite start(), stop() and destroy() methods
}
You need to take layouts into consideration here. A JApplet’s contentPane uses BorderLayout by default, and if you add a component to BorderLayout without a second parameter telling it where to add it, it will be added BorderLayout.CENTER and will fill as much space as possible. The key to solving this is to learn as much as possible about layout managers and use this information to your advantage. You can find this information here: Visual Guide to the Layout Managers.
Note that often we nest JPanels, each using its own coder-friendly layout manager, in order to achieve complex but easy to manage layouts.
e.g.,
Note also that setSize is usually ignored by most layout managers. Instead preferredSize is usually honored, but setting this should be avoided as instead you’ll want the components themselves to set their preferredSize based on their contents or other properties (such as rows and columns for a JTextArea or columns for a JTextField, or String text for a JLabel).