【发布时间】:2015-06-13 17:02:44
【问题描述】:
我真的不知道该怎么表达,但基本上:
-我有几个单独的“片段”,我正试图将它们添加到主框架上;为了防止代码变得笨拙,我让每个“片段”成为自己的类。
-我无法将面板添加到主框架上,因为类本身不是面板,而是类的方法创建了面板,这会产生我不知道如何解决的问题。
PIECE(当我让它成为一个对话框而不是一个面板时它自己工作):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PieceThing3 extends JPanel //<switched from JDialog
{
//set up variables here
private ActionListener pieceAction = new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
// Action Listener (this also works)
}
};
private void createPiece()
{
//setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//setLocationByPlatform(true);
// the above are commented out when I switch from dialog to panel
JPanel contentPane = new JPanel();
//something that uses pieceAction is here
//two buttons, b and s, with action listeners are here
contentPane.add(b);
contentPane.add(s);
add(contentPane);
//pack();
//again, commented out to switch from dialog
setVisible(true);
System.out.println("hi I'm done");
//just to check and make sure it's done
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PieceThing3().createPiece();
}
});
}
}
抱歉,这非常模糊,但复杂性并不像一般概念那么重要 - 当我让它创建自己的对话框时它可以完美运行,但现在我正试图让它在主代码中创建一个面板,如下:
大师:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CollectGUI extends JFrame{
private void createDialog(){
this.setSize(2000,1000);
this.setLocation(0,0);
this.setTitle("TITLE");
PieceThing3 pt = new PieceThing3();
//HERE, if I do pt.main(null); while it is in "dialog mode" (rather than panel) it pops up a dialog box and everything is hunky dory. But I don't know how to get it to add the method as a panel.
this.add(pt.main(null));
//this gives an error
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new CollectGUI().createDialog();
}
}
正如我在 cmets 中所说,如果我只是在 pt 设置为创建对话框时执行 pt.main(null),它会执行此操作,但如果我尝试将 pt.main(null) 添加为面板,它会抛出一个错误。谁能给我一些关于如何添加类的方法而不是类的见解?我很困惑。
谢谢!!
【问题讨论】:
-
我得到的错误是“容器类型中的方法 add(Component) 不适用于参数 (void)”,我理解这本质上是什么意思,但真的不知道如何使固定!谢谢!
-
您的代码完全没有意义。
this.add(pt.main(null));可能应该替换为pt.createPiece(); this.add(pt);。顺便说一句,您创建了一个ActionListener,它不会作为任何东西的侦听器添加,因此它永远不会被调用 -
我确实使用了 ActionListener,我只是在发布之前将其取出,因为这些部件的作用与目前将它们放在主面板上相比不太相关。零件工作正常。那个替换效果很好,谢谢!!
标签: java swing methods jframe jpanel