开发者

Inconsistent results in Eclipse for Java Swing

I am teaching myself Java and I am reading "Java All in One Desk Reference For Dummies." I am currently using the code provided in the book to practice Swing. Here is the code I am using that comes from the book: `import javax.swing.*;

public class JavaBook6 extends JFrame
{



public static void main(String[] args) 
{
     new JavaBook6();

}

public JavaBook6()
{
    this.setSize(400, 400);
    this.setLocation(500, 0);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setTitle("Sample");
    this.setVisible(true);


    JPanel pnlMain = new JPanel();
    JCheckBox chkMy = new JCheckBox("Save");
    JButton btnMy = new JButton("Search");
    JTextField txtMy = new JTextField(20);

    pnlMain.add(chkMy);
    pnlMain.add(txtMy);
    pnlMain.add(btnMy);
    this.add(p开发者_JAVA百科nlMain);




}
}

I seem to get inconsistent results when I press run. A window always shows up. However, sometimes the only thing displayed in the window is the Frame title and other times the components such as JCheckBox, JTextArea and JButton show up, as I would expect.

My question is why do the components show up sometimes and not others? I have tried using other components and get the same inconsistent results.

As I stated I am a beginner and I therefore have a very basic understanding of how java works, so please forgive me if the answer to my question is obvious.


I'm not too impressed with the text book:

  1. The GUI should be created on the EDT. Read the section from the Swing tutorial on Concurrency for more information. I would also recommend you use the examples from the tutorials since they incorporate the suggestions from the tutorial.

  2. Component must be added to the GUI before the setVisible( true ) method is invoked. (There are ways around this, but for now keep it simple and follow this rule).


You generally need to do...

this.pack();

before it will display everything.

I suspect if you resize the window, everything shows up?

Adding the pack() tells the layout manager to position and size all the components. Also if you resize the window or force it to refresh in some way it will also display the components.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜