【问题标题】:adding multiple small panels to a frame将多个小面板添加到框架
【发布时间】:2014-09-30 17:36:47
【问题描述】:

我正在尝试在 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);

}
}

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

【问题讨论】:

  • 也许你的框架根本不是空的。尝试使用 setBorder() 为面板添加边框,这样您就可以实际看到 JPanel。
  • 在你把所有的视觉组件放在一起之前调用 setVisible(true) 也是错误的
  • Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。

标签: java swing jpanel layout-manager null-layout-manager


【解决方案1】:

您正在使用 .setBounds(..,..) 安排组件的位置,在这种情况下为 JPanel ,您应该将其用于顶级容器(JFrameJWindowJDialog 或 @ 987654327@.) 不是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);

}

【讨论】:

    【解决方案2】:

    我会使用 LayoutManager 来放置所有控件并直接访问内容窗格。 How to use 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);
        }
    }
    

    【讨论】:

    • +1。进一步说明。 Swing GUI 应在 EDT 上创建和更新。有关详细信息,请参阅Concurrency in Swing
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多