【问题标题】:Java JPanel Reusable viewJava JPanel 可重用视图
【发布时间】:2014-10-26 10:41:02
【问题描述】:

我创建了一组按钮,我希望它们位于应用程序每个页面的顶部。

不必在每个类中重新创建设置,是否可以创建一次并将其包含在每个类中,类似于 Android 中的可重用视图。

我的按钮设置代码如下:

public Buttons() {
        setLayout(null);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.setBounds(10, 11, 89, 23);
        add(btnNewButton);

        JButton btnNewButton_1 = new JButton("New button");
        btnNewButton_1.setBounds(101, 11, 89, 23);
        add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("New button");
        btnNewButton_2.setBounds(192, 11, 89, 23);
        add(btnNewButton_2);

        textField_2 = new JTextField();
        textField_2.setBounds(104, 42, 86, 20);
        add(textField_2);
        textField_2.setColumns(10);

        System.out.println("HELLO");
    }

我创建类的代码如下:

public static void gui(){
        frame = new JFrame("name");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);
        frame.setLayout(new BorderLayout());
        frame.add(new Buttons(), BorderLayout.WEST);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setBounds(200, 0, 500, 500);
    }

我尝试在此方法中添加以下行以添加第二组按钮:

frame.add(new Extras(), BorderLayout.CENTER);

但它只会将第二个对象添加到显示中。

【问题讨论】:

  • 1) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 将JToolBar 放入BorderLayoutPAGE_START 中。在CENTER 中放置一个(带有)CardLayout 的面板。将“页面”面板添加到卡片布局。完成。
  • 什么是附加功能?什么是“第二对象”?我不明白你的问题是什么。
  • 从文档中您可以看到 frame.add 需要提供组件和约束,以便将它们添加到框架中。因此,Extras 是我希望添加到框架中的对象(类)的名称。当我说第二个时,我的意思是这一行有 2 个实例:'frame.add(new Buttons(), BorderLayout.WEST);'和'frame.add(new Extras(), BorderLayout.CENTER);'。当它们都出现在代码中时,只有最后一个写入的出现在显示中。

标签: java swing user-interface layout-manager uicollectionreusableview


【解决方案1】:

创建一个类(或方法),该类(或方法)创建一个 JPanel,其中包含您想要的所有按钮。然后,只需将该 JPanel 的一个新实例添加到您的 GUI。伪代码:

public JPanel createButtons() {
  JPanel panel = new JPanel();
  // add buttons to panel
  return panel;
}
public void gui() {
  frame = new JFrame("name");
  frame.setLayout(new BorderLayout());
  frame.add(createButtons(), BorderLayout.WEST);
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2015-02-04
    相关资源
    最近更新 更多