【发布时间】:2017-08-02 00:45:31
【问题描述】:
我希望将多个 GUI 类放入一个窗口中。我通过创建一个“主”gui 类来尝试这个,它创建了我制作的单个 gui 的对象 - 但是它们都显示在自己的单独窗口中。
如何将它们全部添加到一个窗口中?
我以为我只是在创建容器,然后可以将其放入主容器中。
这是我的代码:
StockGUI 类
public class StockGUI extends Frame implements ActionListener
{
// instance variables - replace the example below with your own
private JTextPane currentStockValue = new JTextPane();
Font f = new Font(Font.SANS_SERIF, 1, 30);
/**
* Constructor for objects of class StockGUI
*/
public StockGUI()
{
//calling the super constructor from class Frame
super("Stock Market Display");
//setting the window size of the GUI
setSize(600, 600);
//selecting a predefined layout for the GUI
setLayout(new GridLayout());
currentStockValue.setFont(f);
add(currentStockValue);
setVisible(true);
}
用户界面类
public class UserGUI extends Frame implements ActionListener
{
// instance variables - replace the example below with your own
private JTextPane currentStockValue = new JTextPane();
private JButton createUser;
private JLabel enterUsername;
private JTextField username;
Font f = new Font(Font.SANS_SERIF, 1, 30);
/**
* Constructor for objects of class UserGUI
*/
public UserGUI()
{
// initialise instance variables
super("User Info");
//setting the window size of the GUI
setSize(600, 400);
//selecting a predefined layout for the GUI
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
enterUsername = new JLabel("Enter your new username:");
enterUsername.setFont(f);
username = new JTextField();
username.setFont(f);
createUser = new JButton("Create User");
createUser.setFont(f);
createUser.addActionListener(this);
add(enterUsername);
add(username);
add(createUser);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
图形界面类
public class GUI extends Frame
{
// instance variables - replace the example below with your own
private UserGUI userui;
private StockGUI stockgui;
/**
* Constructor for objects of class GUI
*/
public GUI()
{
// initialise instance variables
super("User Info");
//setting the window size of the GUI
setSize(600, 400);
//selecting a predefined layout for the GUI
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
stockgui = new StockGUI();
userui = new UserGUI();
//add(userui);
//add(stockgui);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
setVisible(true);
}
【问题讨论】:
-
因为你所有的类都继承
Frame这是一个顶级窗口。它们需要变成小部件并放置在容器类中
标签: java swing user-interface interface