java将面板从方法添加到框架
我真的不知道该怎么说,但本质上:
-我有几个单独的“片段”,我正试图添加到主框架上;为了避免代码变得笨拙,我让每个“片段”都有自己的类
-我一直在把面板添加到主框架上,因为类本身不是面板,而是类的方法创建了面板,这会产生我不知道如何解决的问题
工件(当我让它制作一个对话框而不是一个面板时,它自己工作):
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();
}
}
正如我在评论中所说,如果我只是做pt。main(null)当pt设置为生成对话框时,它会这样做,但如果我尝试添加pt。main(null)作为面板,它会抛出一个错误。有谁能告诉我如何添加类的方法而不是类的方法吗?我被难住了
谢谢
# 1 楼答案
您在维护关注点分离并在许多不同组件中实现gui方面的工作无疑是正确的。试试这样:
小组1
小组2
JFrame
主要内容:
编辑: 这是一个有更多内容的讨论小组
按钮调用的操作: