如何将JFrame添加到我的程序中

时间:2012-10-20 15:37:46

标签: java swing textarea awt mixing

我已经创建了GUIPanel,但是我需要将它添加到我拥有的程序中;当我尝试从主类中运行其他程序时,GUIPanel将无法运行,但是当我不执行它时(如果这是有道理的)。

This is what happens when I run the program 这是我运行程序时发生的事情

This is the GUIPanel I want the output to print to

我希望输出打印到此GUIPanel(我必须删除对TourServer的调用以使其运行),如果您正在考虑“为什么不将它留在命令提示符中,您没有任何东西在你的GUIPanel中,除了文本区域之外呢?“,那很好,因为我打算稍后再添加更多内容:D

总结:我需要从GUIPanel类运行TourServer程序,当我尝试它时不会打开GUI面板本身

这是主要课程:

import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.*;
import javax.swing.*;
import java.io.*;


/**
 *
 * @author Dan
 */
public class GUIPanel extends JFrame {
    private PrintStream outStream;
    /**
     * Creates new form GUIPanel
     */
    public GUIPanel() {
        initComponents();
    }
    private void init() throws IOException {
        jTabbedPane1.add("Main", jPanel);
        jPanel.add(textArea1);
        setOutputStream();
        TourServer.init(cmd);//Calling the program, I'm assuming I might be doing this wrong.
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {

        textArea1 = new java.awt.TextArea();
        jPanel = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();



        textArea1.setPreferredSize(new java.awt.Dimension(432, 300));



        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Game Manager");
        setBounds(new java.awt.Rectangle(0, 0, 400, 450));
        setPreferredSize(new java.awt.Dimension(450, 420));
        getContentPane().setLayout(new java.awt.FlowLayout());

        try {
            init();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        jTabbedPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTabbedPane1.setFocusable(false);
        jTabbedPane1.setOpaque(true);
        getContentPane().add(jTabbedPane1);
        jTabbedPane1.getAccessibleContext().setAccessibleName("");

        pack();
    }




    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
    cmd = args;
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {  java.util.logging.Logger.getLogger(GUIPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIPanel().setVisible(true);
            }
        });
    }

    private static String[] cmd;
    private javax.swing.JPanel jPanel;
    private javax.swing.JTabbedPane jTabbedPane1;
    private java.awt.TextArea textArea1;

      //Written by MadProgrammer
        public class CapturePane extends JPanel implements Consumer {

        private TextArea output;

        public CapturePane() {
            jPanel.setLayout(new BorderLayout());
            jPanel.add(new JScrollPane(output));
        }

        @Override
        public void appendText(final String text) {
            if (EventQueue.isDispatchThread()) {
                output.append(text);
                output.setCaretPosition(output.getText().length());
            } else {

                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        appendText(text);
                    }
                });

            }        
    }
 }

    public interface Consumer {        
        public void appendText(String text);        
    }

    public class StreamCapturer extends OutputStream {

        private StringBuilder buffer;

        public StreamCapturer() {
            buffer = new StringBuilder(128);
            buffer.append("");
        }

        @Override
        public void write(int b) throws IOException {
            char c = (char) b;
            String value = Character.toString(c);
            buffer.append(value);
            if (value.equals("\n")) {
                textArea1.appendText(buffer.toString());
                buffer.delete(0, buffer.length());
            }
        }        
    }  

}

这是TourServer Class

         // TourServer.java
 /*
   The top-level Tour server, which waits for client connections
   and creates TourServerHandler threads to handle them.

   Details about each client are maintained in a TourGroup object
   which is referenced by each thread.

   Very similar to the multithreaded Chat server.
*/

import java.net.*;
import java.io.*;


public class TourServer
{
  static int PORT = 0;

  private TourGroup tg;
  static GameSession gameSession=new GameSession();
  public TourServer()
  // wait for a client connection, spawn a thread, repeat
  {
    tg = new TourGroup();
    try {
      ServerSocket serverSock = new ServerSocket(PORT);
      Socket clientSock;

      while (true) {
        new GUIPanel("Waiting for a client...");
        clientSock = serverSock.accept();
        new TourServerHandler(clientSock, tg).start();
      }
    }
    catch(Exception e)
    {  e.printStackTrace(); }
  }  // end of TourServer()


  // -----------------------------------

  public static void init(String args[]) {
      if (Integer.parseInt(args[0]) > 0) {
        PORT = Integer.parseInt(args[0]);
      } else {
          PORT = 5550;
      }
        new GUIPanel("Port set to: "+PORT);
        new TourServer();
    }
} // end of TourServer class

1 个答案:

答案 0 :(得分:0)

你的GUI类中有这个构造函数:

public GUIPanel() {
        initComponents();
    }

在init函数之后添加这3个函数:

public GUIPanel() {
        initComponents();
        validate();
        pack();
        show();
    }

我确定之后的窗口会出现。不要停止在这一点,但尝试改进这个解决方案,因为如果我的内存服务,至少有一个这些函数被弃用。对不起,但我从Java 1.4开始就没有真正使用Swing。