将多个小面板添加到框架中



我试图用java制作一个简单的接口,但在一个框架中添加多个面板时遇到了问题。我希望它是一个咖啡馆软件,这样就会有多张桌子。这是我的代码

public class CafeView extends JFrame{
private JButton takeMoneyBtn = new JButton("Hesabı Al");
public CafeView(){
    JPanel table1 = new JPanel();
    this.setSize(800,600);
    this.setLocation(600, 200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    table1.setBounds(100, 100, 150, 150);
    table1.setLayout(null);
    this.add(table1);
    table1.add(takeMoneyBtn);
}
}

当我运行它时,我只看到一个空框架。在这段代码中,我只是尝试添加一个简单的面板,如果我能做到,我也可以添加其他面板。那么,我该如何解决这个问题,并将许多小面板添加到一个框架中,我缺少什么呢?谢谢你的帮助。(没有一个主要的方法,因为我从另一个类调用这个接口类。)

您正在安排组件的位置,在本例中是JPanel使用.setBounds(..,..),您应该将其用于顶级容器(JFrameJWindowJDialogJApplet),而不是JPanel。因此删除:

table1.setBounds(100, 100, 150, 150);

LayoutManager提供我们来安排组件,请参阅LayoutManager

   public class CafeView extends JFrame{
private JButton takeMoneyBtn = new JButton("Hesabı Al");
public CafeView(){
    JPanel table1 = new JPanel();
    this.setSize(800,600);
    this.setLocation(600, 200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
   //table1.setBounds(100, 100, 150, 150);
    //table1.setLayout(null);
    this.add(table1,BorderLayout.CENTER);
    table1.add(takeMoneyBtn);
}

我会使用LayoutManager来放置所有控件并直接访问内容窗格。如何使用FlowLayout

public class CafeView extends JFrame{
private JButton takeMoneyBtn = new JButton("Hesabı Al");
public CafeView(){
    JPanel table1 = new JPanel();
    this.setSize(800,600);
    this.setLocation(600, 200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = this.getContentPanel();
    c.setLayout(new FlowLayout());
    c.add(table1);
    c.add(takeMoneyBtn);
    //c.add() more stuff..
    this.setVisible(true);
    }
}

最新更新