构建动态JPanel的最佳方法

时间:2012-06-06 20:34:22

标签: java swing design-patterns user-interface jpanel

我正在构建一个包含多个字段的JPanel,但根据产品,字段可能会有所不同。
每个产品都有一些常用字段和一些特定字段。 使用一些接口,可以对字段进行分组,以构建带有所有必需字段的引用JPanel,如下所示:

public class VPNProduct extends JPanel implements VPNFields{
    //use and positioning of the fields
}

interface VPNFields extends CommonFields{
    //particular VPN fields
}

interface CommonFields{
    //fields common to all products
}

我的问题是,有一些最佳实践或技术可以让它更容易或更有条理,包括面板中字段的位置?

提前致谢。

2 个答案:

答案 0 :(得分:3)

有一些优雅的方法可以做到这一点。首先,一个界面将有你的get / set方法来访问你的字段。因此,您将拥有公共字段的界面以及其他领域的其他界面。公共字段接口(因为它将被共享)应该实现为抽象类。这个抽象类将扩展JPanel并构造你的JLabel,JComboBoxes等,并将它们放在布局管理器中。

然后对于您需要添加更多字段的任何其他类,您将创建一个类并让它扩展您的抽象类(所以现在它是一个JPanel,其中已经创建并布置了所有公共字段)并实现了一个接口与你的额外领域。这些额外的字段,您将不得不创建他们的Swing组件并将它们添加到当前具有公共字段的布局管理器。

如果您提供一些字段示例或给我们提示结构,我可以起草一些代码示例,以便您可以看到。

一个代码示例,显示了可用于公司和学校的常用字段,以及我们如何使用源自1个JPanel抽象类的表单创建2个JFrame:

package stackoverflow.test;

public interface CommonFields {

    public void setName(String name);

    public void setLastName(String lastName);

    public void setAge(int age);

    public String getName();

    public String getLastName();

    public int getAge();
}

-

package stackoverflow.test;

public interface SchoolFields {

    public void setSchoolName(String schoolName);

    public void setGrade(int grade);

    public void setHonorsProgram(boolean isHonors);

    public String getSchoolName();

    public int getGrade();

    public boolean hasHonorsProgram();
}

-

package stackoverflow.test;

public interface CompanyFields {

    public void setCompanyName(String companyName);

    public void setJobTitle(String jobTitle);

    public void setAddress(String address);

    public String getCompanyName();

    public String getJobTitle();

    public String getAddress();
}

-

package stackoverflow.test;

import java.awt.GridLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AbstractJPanel extends JPanel implements CommonFields {

    private static final long serialVersionUID = 150030761086805569L;

    private JTextField nameField = null;
    private JTextField lastNameField = null;
    private JTextField ageField = null;
    private JLabel nameLabel = null;
    private JLabel lastNameLabel = null;
    private JLabel ageLabel = null;


    public AbstractJPanel() {
        super(new GridLayout(0, 2));

        nameField = new JTextField();
        lastNameField = new JTextField();
        ageField = new JTextField();

        nameLabel = new JLabel("Name: ");
        lastNameLabel =new JLabel("Last Name: ");
        ageLabel = new JLabel("Age: ");

        add(nameLabel);
        add(nameField);
        add(lastNameLabel);
        add(lastNameField);
        add(ageLabel);
        add(ageField);
    }

    public void setName(String name) {
        nameField.setText(name);
    }

    public void setLastName(String lastName) {
        lastNameField.setText(lastName);
    }

    public void setAge(int age) {
        ageField.setText(""+age);
    }

    public String getName() {
        return nameField.getText();
    }

    public String getLastName() {
        return lastNameField.getText();
    }

    public int getAge() {
        return Integer.parseInt(ageField.getText());
    }
}

-

package stackoverflow.test;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class SchoolPanel extends AbstractJPanel implements SchoolFields {

    private static final long serialVersionUID = -6201476099194804075L;

    private JTextField schoolNameField = null;
    private JTextField gradeField = null;
    private JCheckBox honorsCheckBox = null;
    private JLabel schoolNameLabel = null;
    private JLabel gradeLabel = null;
    private JLabel honorsLabel = null;

    public SchoolPanel() {
        super();


        schoolNameLabel = new JLabel("School Name: ");
        gradeLabel = new JLabel("Grade: ");
        honorsLabel = new JLabel("Is Honors: ");

        schoolNameField = new JTextField();
        gradeField = new JTextField();
        honorsCheckBox = new JCheckBox();

        add(schoolNameLabel);
        add(schoolNameField);
        add(gradeLabel);
        add(gradeField);
        add(honorsLabel);
        add(honorsCheckBox);
    }

    @Override
    public void setSchoolName(String schoolName) {
        schoolNameField.setText(schoolName);
    }

    @Override
    public void setGrade(int grade) {
        gradeField.setText(""+grade);
    }

    @Override
    public void setHonorsProgram(boolean isHonors) {
        honorsCheckBox.setSelected(isHonors);
    }

    @Override
    public String getSchoolName() {
        return schoolNameField.getText();
    }

    @Override
    public int getGrade() {
        return Integer.parseInt(gradeField.getText());
    }

    @Override
    public boolean hasHonorsProgram() {
        return honorsCheckBox.isSelected();
    }
}

-

package stackoverflow.test;

import javax.swing.JLabel;
import javax.swing.JTextField;

public class CompanyPanel extends AbstractJPanel implements CompanyFields {

    private static final long serialVersionUID = 7834845724312492112L;

    private JTextField companyNameField = null;
    private JTextField jobTitleField = null;
    private JTextField addressField = null;
    private JLabel companyNameLabel = null;
    private JLabel jobTitleLabel = null;
    private JLabel addressLabel = null;

    public CompanyPanel() {
        super();

        companyNameLabel = new JLabel("Company Name: ");
        jobTitleLabel = new JLabel("Job Title: ");
        addressLabel = new JLabel("Address: ");

        companyNameField = new JTextField();
        jobTitleField = new JTextField();
        addressField = new JTextField();

        super.add(companyNameLabel);
        super.add(companyNameField);
        super.add(jobTitleLabel);
        super.add(jobTitleField);
        super.add(addressLabel);
        super.add(addressField);
    }

    @Override
    public void setCompanyName(String companyName) {
        companyNameField.setText(companyName);
    }

    @Override
    public void setJobTitle(String jobTitle) {
        jobTitleField.setText(jobTitle);
    }

    @Override
    public void setAddress(String address) {
        addressField.setText(address);
    }

    @Override
    public String getCompanyName() {
        return companyNameField.getText();
    }

    @Override
    public String getJobTitle() {
        return jobTitleField.getText();
    }

    @Override
    public String getAddress() {
        return addressField.getText();
    }

}

-

package stackoverflow.test;

import java.awt.BorderLayout;

import javax.swing.JFrame;

public class MainClass {

    public MainClass() {
        JFrame frame1 = new JFrame();
        frame1.setLayout(new BorderLayout());
        frame1.add(new CompanyPanel());
        frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame1.setSize(500, 500);
        frame1.setVisible(true);


        JFrame frame2 = new JFrame();
        frame2.setLayout(new BorderLayout());
        frame2.add(new SchoolPanel());
        frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame2.setSize(500, 500);
        frame2.setVisible(true);
    }


    public static final void main(String ... args) {
        new MainClass();
    }
}

答案 1 :(得分:1)

考虑不是以一种好的方式做出来的,因为我不知道你为此使用了什么类型的字段,所以将一些想象的字段设为JLabel s,看看。我希望这可以解释我想从我这边提供什么,以及你可以看到的一个小方向: - )

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Products
{
    private JComboBox productBox;
    private String[] productNames;
    private JLabel imageLabel;
    private Icon desktopIcon = UIManager.getIcon("OptionPane.informationIcon");
    private Icon keyboardIcon = UIManager.getIcon("OptionPane.errorIcon");
    private Icon mouseIcon = UIManager.getIcon("OptionPane.warningIcon");

    private MainPanel mainPanel;
    private JPanel fieldPanel;
    private AdditionalFields additional;

    public Products()
    {
        productNames = new String[]{
                                    "Desktop",
                                    "Keyboard",
                                    "Mouse"
                                   };
    }

    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("Products");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        imageLabel = new JLabel();

        JPanel contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        contentPane.setBorder(
                        BorderFactory.createTitledBorder(
                                                "Products : "));
        contentPane.setLayout(new GridLayout(0, 1, 2, 2));
        contentPane.add(imageLabel);

        fieldPanel = new JPanel();

        fieldPanel.setOpaque(true);
        fieldPanel.setBackground(Color.WHITE);
        fieldPanel.setBorder(
                    BorderFactory.createEmptyBorder(
                                            5, 5, 5, 5));
        fieldPanel.setLayout(new GridLayout(0, 1, 2, 2));

        productBox = new JComboBox(productNames);
        productBox.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JComboBox cbox = (JComboBox) ae.getSource();
                String product = (String) cbox.getSelectedItem();
                fieldPanel.removeAll();
                if (product.equals("Desktop"))
                {
                    mainPanel = new MainPanel("DESKTOP", "50000");
                    imageLabel.setIcon(desktopIcon);
                    fieldPanel.add(mainPanel);  
                    fieldPanel.revalidate();
                    fieldPanel.repaint();                   
                }
                else if (product.equals("Keyboard"))
                {
                    mainPanel = new MainPanel("Keyboard", "50");
                    additional = new AdditionalFields("Keyboard");
                    imageLabel.setIcon(keyboardIcon);
                    fieldPanel.add(mainPanel);  
                    fieldPanel.add(additional);
                    fieldPanel.revalidate();
                    fieldPanel.repaint();                   
                }
                else if (product.equals("Mouse"))
                {
                    mainPanel = new MainPanel("Mouse", "30");
                    additional = new AdditionalFields("Mouse");
                    imageLabel.setIcon(mouseIcon);
                    fieldPanel.add(mainPanel);  
                    fieldPanel.add(additional);
                    fieldPanel.revalidate();
                    fieldPanel.repaint();                   
                }
            }
        });

        contentPane.add(fieldPanel);

        frame.getContentPane().add(contentPane, BorderLayout.CENTER);
        frame.getContentPane().add(productBox, BorderLayout.PAGE_END);

        frame.setSize(300, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new Products().createAndDisplayGUI();
            }
        });
    }
}

class MainPanel extends JPanel
{
    private JLabel nameLabel;
    private JLabel valueLabel;
    private JTextField nameField;
    private JTextField valueField;

    public MainPanel(String name, String value)
    {
        setOpaque(true);
        setBackground(Color.WHITE);
        nameLabel = new JLabel("Name : ");
        nameField = new JTextField(name, 10);
        valueLabel = new JLabel("Value : ");
        valueField = new JTextField(value, 10);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.weightx = 0.5;
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(nameLabel, gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        add(nameField, gbc);
        gbc.gridx = 0;
        gbc.gridy = 1;
        add(valueLabel, gbc);
        gbc.gridx = 1;
        gbc.gridy = 1;
        add(valueField, gbc);
    }   
}

class AdditionalFields extends JPanel
{
    private JLabel noOfButtons;
    private JLabel noButField;

    public AdditionalFields(String product)
    {       
        setOpaque(true);
        setBackground(Color.WHITE);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.weightx = 0.5;
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.gridy = 0;
        if (product.equals("Keyboard"))
        {
            noOfButtons = new JLabel(product);
            noButField = new JLabel("110 KEYS", JLabel.CENTER); 
        }   
        else if (product.equals("Mouse"))
        {
            noOfButtons = new JLabel(product);  
            noButField = new JLabel("3 BUTTONS", JLabel.CENTER);
        }   
        add(noOfButtons, gbc);  
        gbc.gridx = 1;
        gbc.gridy = 0;
        add(noButField, gbc);
    }
}