Ссылка (?) Проблема с окнами в графическом интерфейсе - PullRequest
2 голосов
/ 25 июля 2011

- EDIT-- У меня есть приветственное окно, состоящее из двух JLabels. Он имеет ссылку на таймер, считающий от 3 до 0. По истечении этого времени на месте предыдущего автоматически появится новое окно «UsedBefore», содержащее JLabel и переключатели. Когда я запускаю «Launcher», появляется первое окно со счетчиком, отображающим 3,2,1,0, а затем ничего не происходит.

Я думаю, что проблема заключается в плохих ссылках, но я не уверен. У меня есть класс "Launcher":

public static void main(String[] args) {

    javax.swing.SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            Welcome window = new Welcome();
            window.setVisible(true);
        }
    });

} // end main

Где я запускаю окно «Добро пожаловать»:

public Welcome() {
    init();
}

public void init() {

    // here I'm adding stuff to the window and then I have:     

    setLayout(cardLayout);
    add(big, "1welcome");
//  UsedBefore.MakeUsedBeforeWindow(); // ???
    new MyTimer(this).start();

} // end init

это идет к MyTimer, который выполняет обратный отсчет и:

 welcome.showNextWindow(); // private Welcome welcome;

мы возвращаемся в класс «Добро пожаловать»:

public void showNextWindow() {
    cardLayout.next(this);
}

public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

private static void createAndShowGUI() {
    JFrame frame = new JFrame("My Frame");
    frame.getContentPane().add(new Welcome());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(550, 450);
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

и, наконец, класс "UsedBefore":

public UsedBefore() {           
        super(new BorderLayout());
        init();         
    }

    public void MakeUsedBeforeWindow() {            

        String q = "Have you used GUI before?";
        JPanel area = new JPanel(new BorderLayout());
        add(area, "2usedBefore?");
        area.setBackground(Color.white);
        JLabel textLabel = new JLabel("<html><div style=\"text-align: center;\">"
                + q + "</html>", SwingConstants.CENTER);
        textLabel.setForeground(Color.green);
        Font font = new Font("SansSerif", Font.PLAIN, 30);
        textLabel.setFont(font);
        textLabel.setBorder(new EmptyBorder(0, 0, 250, 0)); //top, left, bottom, right
        area.add(textLabel, SwingConstants.CENTER);
        add(area, "2usedBefore?");          
    }

со своим основным:

        public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

public static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("RadioButtons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane - not sure how to do it
//          JComponent newContentPane = new UsedBefore();
//          newContentPane.setOpaque(true); //content panes must be opaque
//          frame.setContentPane(newContentPane);
//          frame.getContentPane().add(new UsedBefore());

        //Display the window.
        frame.setSize(550, 450);
        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        }

Это довольно путешествие. Извините за большое количество кода, я надеюсь, что путь свободен. Как только у меня появятся 1-> 2-> 3 ссылки, я смогу сделать все остальное, поэтому любая помощь приветствуется. Спасибо.

1 Ответ

0 голосов
/ 12 сентября 2011

Я предлагаю немного другой подход.Почему бы не создать JPanel вместо Windows и добавить / удалить эти JPanel в нужное время.

Ex (здесь сначала отображается панель welcome с уменьшающимся счетчиком, а когда счетчик достигает 0, *Панель 1006 * показана):

public class T extends JFrame {

private int couterValue = 3;
private JPanel welcome;
private JLabel counter;

private JPanel other;
private Timer timer;

public T() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    buildWelcomePanel();
    buildOtherPanel();

    add(welcome);
    setSize(550, 450);
    setLocationRelativeTo(null);
    setVisible(true);

    timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            if (couterValue == 0) {
                timer.cancel();
                // Switch the panels as the counter reached 0
                remove(welcome);
                add(other);
                validate();
            } else {
                counter.setText(couterValue + ""); // Update the UI counter
                couterValue--;
            }
        }
    }, 0, 1000);

}

private void buildWelcomePanel() {
    welcome = new JPanel();
    counter = new JLabel();
    welcome.add(counter);
}

private void buildOtherPanel() {
    other = new JPanel();
    JLabel otherStuff = new JLabel("Anything else ...");
    other.add(otherStuff);
}

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