我是Java Applet編程和Java的新手,但我在C#和C++中非常出色。無論如何,我正在用JTextField,JButton和JLabel製作一個簡單的計算器。但JButton和JTextField佔據了整個屏幕,最奇怪的是我設置了大小,並沒有設置大小。那麼我做錯了什麼?這裏是下面的代碼,所以有人可以幫助我;我會感謝任何答案。添加JButton控件到JApplet並且JButton填充整個屏幕
/*
* 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
}
很抱歉,但我跟你的 「經驗法則」 不同意。通常將組件放在自己的JPanel中並不是一個好主意。更好的方法是瞭解佈局管理器並使用這些知識正確使用它們。 –
即使使用正確的佈局過程如果您嘗試將「原始」組件添加到容器,Swing會出現奇怪的情況。我不是說每個組件都粘貼到單獨的JPanel中。 –
你能舉個例子嗎? –