2

我正在构建一个包含多个字段的 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
}

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

提前致谢。

4

2 回答 2

3

有一些优雅的方法可以做到这一点。首先,一个接口将具有您的 get/set 方法,这些方法将访问您的字段。因此,您将有一个用于公共字段的接口和用于其他字段的其他接口。公共字段接口(因为它将被共享)应该实现为抽象类。这个抽象类将扩展 JPanel 并构建您的 JLabel、JComboBoxes ...等,并将它们布置在布局管理器中。

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

如果您提供一些现场示例或向我们提供有关结构的提示,我可以起草一些代码示例以便您查看。

一个代码示例,显示可用于 Company 和 School 的公共字段,以及我们如何创建 2 个 JFrame,其表单均源自 1 个 JPanel 抽象类:

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();
    }
}
于 2012-06-08T15:07:22.073 回答
1

想的不是很好,因为我不知道你用的是什么类型的字段,所以做了一些虚构的字段JLabels,看看。我希望这能很好地解释我试图从我身边提供的东西,以及你可以看到的一个小方向:-)

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);
    }
}
于 2012-06-08T14:09:05.153 回答