繁体   English   中英

从不同的类添加面板到框架?

[英]add panel to frame from different class?

好的,我试着总结一下我的问题。 我试图从不同的类添加一个jpanel。 在那个类中我有print方法,我从文件中获取输入并将其附加到JTextArea,这是第二个代码块。 我想将该面板添加到GUI类中的框架。 当前代码正确输出第一个块中的按钮。 但是单击选项只会略微扩大窗口并且全部为黑色。 按钮保持在那里,但覆盖黑色窗口。 =(

package GamePackage;

import java.*;

import javax.swing.*

public class CopyOfGUI extends JFrame {
static String config = null;
static JFrame frame;
static JPanel panel;

private static final long serialVersionUID = 1L;

public CopyOfGUI() {
    frame = new JFrame("Sheep City");
    panel = new JPanel();
    JButton options = new JButton("OPTIONS"); 
    JButton start = new JButton ("START");
    JButton controls = new JButton ("CONTROLS");

    panel.add(options);
    panel.add(start);
    panel.add(controls);


    frame.add(panel);

    options.addActionListener(new actionReadConfig(config)); 

    frame.pack();
    frame.setVisible(true);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}

public static void main (String[] args) {
    if (args.length > 0) 
        {config = args[0];}
    CopyOfGUI gui = new CopyOfGUI();    

}
//Here is where the options button loads the read in argument for the config file
class actionReadConfig implements ActionListener {
    String config = null;
    public actionReadConfig(String config) {
        this.config = config;
    }
    public void actionPerformed(ActionEvent e) {
        try {
            GameBoard.loadConfig(this.config);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

}

这是代码,我试图将文件从文件读取添加到文本区域,将其添加到面板,然后返回到原始框架。

public static int print(ConfigurationManager cm) {
    //code gere
    JPanel configPanel = new JPanel(new BorderLayout());
    configPanel.setBorder(BorderFactory.createTitledBorder("Configuration Manager"));
    JTextArea area = new JTextArea();
    area.append("Before we get started lets setup our configurations shall we?\n");
    area.append("These are the default configurations.\n");
    area.append("*************************\n");
    //for loop here {
        //area.append output
    //}
    area.append("*************************\n");
    area.append("Would you like to change any of these values? (yes/no)\n");
    area.setEditable(false);
    configPanel.add(area, BorderLayout.SOUTH); //Idk if any of this is right 
    CopyOfGUI.frame.add(configPanel);
    CopyOfGUI.frame.remove(CopyOfGUI.panel);
    CopyOfGUI.frame.pack();
    CopyOfGUI.frame.setVisible(true);
    CopyOfGUI.frame.repaint();

之后会有更多代码,但在我担心其余部分之前,我需要前一部分工作。 Thx提前。

我不确定调用print方法的位置但你可以将面板变成一个类变量并将它放在一个公共getter中,这样你就可以将它添加到框架中(假设print方法在另一个类中)。

private JPanel configPanel;

public JPanel getConfigPanel()
{
    return configPanel;
}

然后,您可以使用该方法并将其添加到您的框架:

frame.add(someClass.getConfigPanel);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM