gui类不会在不同的单独主文件

时间:2018-03-07 17:26:00

标签: java swing user-interface

如果我在GUI类中创建一个main方法,并创建一个对象,程序运行并正常工作。但是,当我尝试在另一个文件中创建此类的对象时,窗口很快就会消失。

我不确定为什么会出现这种情况,我尝试将框架设置为可见且不起作用,我还尝试创建一个方法,允许显式调用set visibility方法而不是工作要么。我不知道我做错了什么,非常感谢任何帮助。

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

public class BoxGUI extends JFrame{

    private JFrame frame;
    public BoxGUI(String text1, String text2) {

        //components 
        String title = "Test";
        frame = new JFrame(title);

        Container content = frame.getContentPane();
        content.setLayout(new GridLayout(0,2, 3, 4)); //Creates Grid layout 

        JTextArea leftTextArea = new JTextArea();
        leftTextArea.append("i am on the left");
        leftTextArea.append(text1);

        JTextArea rightTextArea = new JTextArea() {
            public boolean isManagingFocus() {
                return false;
            }
        };
        rightTextArea.append("i am on the right");
        rightTextArea.append(text2);

        content.add(leftTextArea);
        //leftTextArea.paste();

        content.add(rightTextArea);     
        //rightTextArea.paste();

        frame.pack();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);// closes frame on exit 
    }

    public void displayGUI() {
        this.frame.setVisible(true);
    }
    public void CreateTextAreaComponents(String text1,String text2) {
        String title = "Test";
        frame = new JFrame(title);

        Container content = frame.getContentPane();
        content.setLayout(new GridLayout(0,2, 3, 4)); //Creates Grid layout 

        JTextArea leftTextArea = new JTextArea();
        leftTextArea.append("i am on the left");
        leftTextArea.append(text1);

        JTextArea rightTextArea = new JTextArea() {

            public boolean isManagingFocus() {
                return false;
            }
        };
        rightTextArea.append("i am on the right");
        rightTextArea.append(text2);

        content.add(leftTextArea);
        //leftTextArea.paste();

        content.add(rightTextArea);     
        //rightTextArea.paste();

        frame.pack();
        frame.setVisible(true); 
        content.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);// closes frame on exit 
    }

    public static void main (String []alex) {
        /* 
        String text1, text2;
         text1 = "\nhi, i amm on the left";
         text2 = "\nhi, i am on the right!";
         BoxGUI test = new BoxGUI(text1, text2);
         test.displayGUI();
         */
    }
}

我的其他档案。

import javax.swing.*;
import java.util.*;
import java.io.*;

public class Project1{
    public static void main(String []args){

        String text1, text2;
        text1 = "\nhi, i amm on the left";
        text2 = "\nhi, i am on the right!";
        BoxGUI test = new BoxGUI(text1, text2);
        test.displayGUI(); 
    }
}

0 个答案:

没有答案