因此,我试图使用MVC (模型、视图、控制器)来格式化我的代码,当我试图将视图添加到实际应用程序时,我会得到一个错误:"java.lang.IllegalArgumentException:向java.awt.Container.addImpl at java.awt.Container.addImpl at java.awt.Container.add的容器添加一个窗口“,而我知道错误是什么,我不知道我应该做什么(不使用MVC或者找到某种工作),并希望得到任何帮助。下面我将得到这两个类的代码。
以下是运行应用程序的位置:
import javax.swing.*;
import java.awt.*;
/**
* Write a description of class FencingApplication here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Application
{
public static void main(String[] args){
InputView view = new InputView();
InputModel model = new InputModel();
InputController ctrl = new InputController(view, model);
JFrame window = new JFrame("");
window.setSize(500, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = new Container();
c.setLayout(new BorderLayout());
c.add( view, BorderLayout.CENTER );
JButton btList = new JButton( "List" );
JButton btPools = new JButton("Pools");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(btList);
buttonPanel.add(btPools);
c.add( buttonPanel, BorderLayout.NORTH );
btList.addActionListener( ctrl );//where is the action performed method defined
btPools.addActionListener( ctrl );
window.setVisible( true );
}
}以下是视图类:
import javax.swing.*; //Jframe/JButton/JLabel/etc
import java.awt.*; //container
import java.util.*;
/**
* Write a description of class InputView here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class InputView extends JFrame implements Observer
{
JLabel lbPaste = new JLabel("Please paste the seeding here.");
JTextArea taPaste = new JTextArea();
JButton btPools = new JButton("Pools");
JLabel lbNum = new JLabel("Please input the number of pools you want to have.");
JTextField tfNum = new JTextField();
public InputView()
{
JPanel numPanel = new JPanel();
numPanel.setLayout(new BorderLayout());
numPanel.add(lbNum, BorderLayout.NORTH);
numPanel.add(tfNum, BorderLayout.CENTER);
JPanel pastePanel = new JPanel();
pastePanel.setLayout(new BorderLayout());
pastePanel.add(lbPaste, BorderLayout.NORTH);
pastePanel.add(new JScrollPane(taPaste), BorderLayout.CENTER);
Container c = getContentPane();
c.setLayout(new GridLayout(2, 1));
c.add(numPanel);
c.add(pastePanel);
setTitle( "Pools" );
setSize( 350, 500 );//width then height
setVisible(true);
setResizable(false);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void update( Observable obs, Object obj )
{
}
}提前感谢您的帮助!
发布于 2016-04-09 05:41:18
Container是Panel、JPanel、Window、JFrame等的超类。
JFrame是一个窗口,所以您不应该将它添加到另一个组件中(实际上不能,就像您在这里发现的那样)。JFrame是顶层集装箱。
实际上,您可能根本不应该直接使用new Container()。例如,如果您想要一个面板,您应该使用JPanel。我很难准确地知道您的意图,因为将JFrame添加到另一个组件是一个错误。我看到你在c中添加了一些东西,但我没有看到你用它做任何其他事情。
所以:
JFrame是一扇窗户。JFrame有一个内容窗格,它是窗口内的面板。(默认的内容窗格实际上是一个JPanel,尽管getContentPane()将它作为Container返回。)JFrame中,可以将其添加到内容窗格中。JFrame,只需使用new创建它并调用setVisible(true)。这些是正确使用JFrame的基本知识。
如果您还没有读过秋千教程,我也强烈推荐它们。他们真的很棒。
https://stackoverflow.com/questions/36513000
复制相似问题