开发者

GUI objects not showing in Java on Mac

开发者 https://www.devze.com 2022-12-10 14:13 出处:网络
I\'ve only just begun writing GUI programs, this being my second one. With both projects (both homework assignments) I have had the same issue. The GUI objects (such as JTextField) do not show when th

I've only just begun writing GUI programs, this being my second one. With both projects (both homework assignments) I have had the same issue. The GUI objects (such as JTextField) do not show when the application runs until after I resize the window or move keyboard focus to them. If I do not do one of those two things, then I'll just have an empty application window.

Any ideas why this is happening and what I could do to solve it? I'm working on Mac OS 10.6.1.

My code is below. Feel free to comment on my coding style, but please focus on the problem I'm having.

import javax.swing.*;
import java.awt.*;

public class ToDo extends JFrame {

    private int height = 30,
                width = 300;

    public ToDo() {
        this.setSize(400,400);
        this.setVisible(true);
        this.setLayout(null);
        this.setResizable(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("To Do List");
        JTextField todoItem[] = new JTextField [10];
        Container contentpane = this.getContentPane();
        contentpane.setLayout(n开发者_如何学编程ull);
        for(int i=0; i<10; i++) {
            todoItem[i] = new JTextField();
            todoItem[i].setBounds(10,(height*(i)+10),width,height);
            contentpane.add(todoItem[i]);
        }

    }

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


You have to add the elements before the component is made visible.

Put this as your last line:

        this.setVisible(true);

alt text http://img10.imageshack.us/img10/8210/capturadepantalla200911s.png

This is not OSX related, it happens in Windows also.


There are some rules about how you should never touch Swing objects from outside the Swing thread once they've been realized. I always ignore these rules, but it could well be you've been bitten by them under Mac OS.

As a step in the officially right direction, try to not do setVisible() until you've assembled the whole thing, i.e. at the bottom of the constructor.

Reference material: http://www.math.vu.nl/~eliens/documents/java/tutorial/ui/swing/threads.html


A guess: add the component before setBoundsing it.


I could be wrong--been a long time since I've done a GUI in java--but I'm guessing your issue is making the JFrame visible before you finish adding elements. I think you need to either do that afterwards, or call update on the frame.

EDIT - Also, not sure setting the layout to null is a good idea. I've always used GridBag, but it might lose its default if you set it to null.

0

精彩评论

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