【问题标题】:Java GUI use one button to add multiple text fields to a text file?Java GUI 使用一个按钮将多个文本字段添加到文本文件?
【发布时间】:2015-08-13 13:49:15
【问题描述】:

我必须创建一个接受多个文本字段输入的 GUI,当用户单击一个按钮时,它会将所有输入添加到一个文本文件中。所有文本字段都与 mp3 文件的所有部分有关。 (艺术家/专辑等)然后,一旦将 mp3 文件添加到文本文件中,我必须创建一个按钮来编辑或删除它们。我对如何为多个文本字段制作“添加”按钮感到困惑。这是我目前所拥有的:

public musicLib()
{
    setLayout(new FlowLayout());

    // Song Row
    itemLabel = new JLabel("Item Code: ");
    add(itemLabel);
    itemCode = new JTextField(10);
    add(itemCode);
    descriptionLabel = new JLabel("Description: ");
    add(descriptionLabel);
    description = new JTextField(10);
    add(description);
    artistLabel = new JLabel("Artist: ");
    add(artistLabel);
    artist = new JTextField(10);
    add(artist);
    albumLabel = new JLabel("Album: ");
    add(albumLabel);
    album = new JTextField(10);
    add(album);


    // Buttons
    addButton = new JButton("Add");
    add(addButton);
    Event e = new Event(); error"no suitable constructor found"
    addButton.addActionListener(e); // error"incompatible types"

    addButton.addActionListener(new ActionListener() 
    {
    String nl = "\n",
    data = "";


public void dataWriter(String data, String fileName) throws IOException {
File file = getFileStreamPath(fileName); // error"cannot find symbol"

if (!file.exists()) {
   file.createNewFile();
}

FileOutputStream writer = openFileOutput(file.getName(),   Context.MODE_PRIVATE); // error"cannot find symbol"

for (String string: data) // error"for- each not applicable to expression type"
{
    writer.write(string.getBytes());
    writer.flush();
}

writer.close();
}








}

非常感谢你们的帮助。我只需要一些帮助来获得一个按钮来将多个文本字段输入添加到文本文件中。提前致谢!

【问题讨论】:

  • @Sipty 我不相信,我没有使用 android,只是制作一个 Java 应用程序。
  • 啊!我刚刚注意到标签,道歉!我的答案仍然成立,但您需要用您的文本字段替换编辑文本。如果你能给我你正在使用的课程的链接,我相信我可以得到一个更准确的答案。
  • @Sipty 刚刚更新了代码!
  • 在我看来,除了多字段位的文本提取之外,一切都已就绪。还是我误解了您的代码? (自从我使用纯 Java 以来已经有一段时间了,抱歉!D:)

标签: java user-interface


【解决方案1】:

这个块,将是初始 gui 设置功能的一部分:

/**
 * On click listener for the add button
 */
addButton.addActionListener(new ActionListener() {
    String nl = "\n",
        data = "";
    public void actionPerformed(ActionEvent ae){
        data += "Label: " + albumLabel.getText() + nl;
        data += "Artist: " + albumArtist.getText() + nl;
        /*
         * Repeat the same for any other text fields you have
         */
        dataWriter(data, "test.txt");

    } 
 });

这是你的文件编写器:

public void dataWriter(String data, String fileName) {
    File file = getFileStreamPath(fileName);

    if (!file.exists()) {
       file.createNewFile();
    }

    FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);

    for (String string: data){
        writer.write(string.getBytes());
        writer.flush();
    }

    writer.close();
}

【讨论】:

  • 我为此准备了一个 Java 实现,但放弃了它,因为我认为您更新的代码可以工作。让我尝试为您重新创建和更新它。
  • 您可能希望在每个数据添加的末尾添加一个换行符,以便格式化文本文件。但是,这会起作用,将所有文本放在一行上。
  • 我将它更新为对 Java 更友好,请测试并告诉我它是如何工作的。我的记忆很生疏,但唯一真正的 android/java 区别是添加侦听器并将文本从字段中取出。其他一切都一样。
  • 我现在正在尝试实现它,我会告诉你它是如何工作的!非常感谢你 ! @Sipty
  • 我有一些错误信息,我将发布我当前代码的样子,并评论错误所在。
【解决方案2】:

如果我正确理解你,你想要这样的东西;

StringBuilder sb = new StringBuilder();
sb.append("ItemLabel: "+itemLabel.getText()+"\n");
sb.append("Description: "+description.getText()+"\n");

并添加您需要的内容。当你写入文件时

out.write(sb.toString());

【讨论】:

  • 感谢您的回答,如何将其合并到我的代码中?
【解决方案3】:

我编写了这个非常快速的程序来使用Map 的字段来读取和写入字段数据。该地图由组件和元数据组成,关于如何布局以及其信息是否可导出。

还远未完成,但只需一点文件 IO,只要传入的数据与应用程序解析逻辑中定义的“模式”匹配,就可以存储和检索信息并将其发送到表单。

图1

点击“编辑”按钮后的窗口。

图2

将所有字段的数据导出为文本后输出;使用“添加”按钮。

代码

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

public class MusicApp extends JPanel {
    private static final long serialVersionUID = 6555747177061710030L;
    private static final String APP_TITLE = "Music App";
    private static final int APP_WIDTH = 800;
    private static final int APP_HEIGHT = 600;

    private static class GridItem {
        private JComponent component;
        private boolean isExportable;
        private int xPos;
        private int yPos;
        private int colSpan;
        private int rowSpan;

        public GridItem(JComponent component, boolean isExportable, int xPos, int yPos) {
            this(component, isExportable, xPos, yPos, 1, 1);
        }

        public GridItem(JComponent component, boolean isExportable, int xPos, int yPos, int colSpan, int rowSpan) {
            this.component = component;
            this.isExportable = isExportable;
            this.xPos = xPos;
            this.yPos = yPos;
            this.colSpan = colSpan;
            this.rowSpan = rowSpan;
        }
    }

    private int appWidth;
    private int appHeight;
    private Map<String, GridItem> componentMap;
    private GridBagLayout layout;
    private GridBagConstraints constraints;

    public MusicApp(int width, int height) {
        super();

        this.appWidth = width;
        this.appHeight = height;

        this.init();
        this.createChildren();
    }

    protected void init() {
        this.constraints = new GridBagConstraints();
        this.layout = new GridBagLayout();
        this.componentMap = new LinkedHashMap<String, GridItem>();

        // Disable size for now.
        //this.setPreferredSize(new Dimension(appWidth, appHeight));

        this.setLayout(this.layout);

        this.constraints.ipadx = 3;
        this.constraints.ipady = 3;
        this.constraints.insets = new Insets(8, 4, 8, 4);

        //JLabel itemLabel, descriptionLabel, artistLabel, albumLabel, priceLabel;
        //JTextField itemCode, description, artist, album, price;
        //JButton addButton,editButton, deleteButton;

        this.constraints.anchor = GridBagConstraints.LAST_LINE_END;

        componentMap.put("itemLabel", new GridItem(new JLabel("Item"), false, 0, 0, 3, 1));

        this.constraints.fill = GridBagConstraints.HORIZONTAL;

        componentMap.put("artistLabel", new GridItem(new JLabel("Artist"), false, 0, 1));
        componentMap.put("artistText", new GridItem(new JTextField(), true, 1, 1, 2, 1));

        componentMap.put("albumLabel", new GridItem(new JLabel("Album"), false, 0, 2));
        componentMap.put("albumText", new GridItem(new JTextField(), true, 1, 2, 2, 1));

        componentMap.put("priceLabel", new GridItem(new JLabel("Price"), false, 0, 3));
        componentMap.put("priceText", new GridItem(new JTextField(), true, 1, 3, 2, 1));

        componentMap.put("descriptionLabel", new GridItem(new JLabel("Description"), false, 0, 4));
        componentMap.put("descriptionText", new GridItem(new JTextField(20), true, 1, 4, 2, 1));

        componentMap.put("addButton", new GridItem(new JButton("Add"), false, 0, 5));
        componentMap.put("editButton", new GridItem(new JButton("Edit"), false, 1, 5));
        componentMap.put("deleteButton", new GridItem(new JButton("Delete"), false, 2, 5));

        ((JButton) componentMap.get("addButton").component).addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(grabFieldData());
            }
        });;

        ((JButton) componentMap.get("editButton").component).addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String[] lines = {
                    "artistText: Led Zeppelin",
                    "albumText: Houses of the Holy",
                    "priceText: 12.99",
                    "descriptionText: The fifth studio album by British rock band Led Zeppelin, released by Atlantic Records on 28 March 1973."
                };

                setFieldData(lines);
            }
        });;

        ((JButton) componentMap.get("deleteButton").component).addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearFieldData();
            }
        });;

    }

    protected void createChildren() {
        Iterator<Map.Entry<String, GridItem>> it;

        for (it = componentMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, GridItem> item = it.next();
            GridItem gridItem = item.getValue();

            this.constraints.gridx = gridItem.xPos;
            this.constraints.gridy = gridItem.yPos;
            this.constraints.gridwidth = gridItem.colSpan;
            this.constraints.gridheight = gridItem.rowSpan;

            this.add(gridItem.component, this.constraints);
        }
    }

    private String grabFieldData() {
        StringBuffer buff = new StringBuffer();
        Iterator<Map.Entry<String, GridItem>> it;

        for (it = componentMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, GridItem> item = it.next();
            GridItem gridItem = item.getValue();

            if (gridItem.isExportable) {
                if (gridItem.component instanceof JTextComponent) {
                    buff.append(item.getKey()).append(": ")
                        .append(((JTextComponent) gridItem.component).getText())
                        .append("\n");
                }
            }
        }

        return buff.toString();
    }

    private void clearFieldData() {
        Iterator<Map.Entry<String, GridItem>> it;
        for (it = componentMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, GridItem> item = it.next();
            GridItem gridItem = item.getValue();

            if (gridItem.isExportable) {
                if (gridItem.component instanceof JTextComponent) {
                    ((JTextComponent) gridItem.component).setText("");
                }
            }
        }
    }

    private void setFieldData(String[] textLines) {
        clearFieldData();

        for (String line : textLines) {
            String[] values = line.split(":\\s*");

            if (values.length == 2) {
                GridItem gridItem = componentMap.get(values[0]);

                if (gridItem.isExportable && gridItem.component instanceof JTextComponent) {
                    JTextComponent field = ((JTextComponent) gridItem.component);
                    field.setText(values[1]);
                    field.setCaretPosition(0);
                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame(APP_TITLE);

                f.setContentPane(new MusicApp(APP_WIDTH, APP_HEIGHT));
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}

【讨论】:

  • 非常感谢您这么详细的回答!以我目前的地位来说可能有点太高级了,但我会看看!谢谢! @先生。多旋风
猜你喜欢
  • 1970-01-01
  • 2019-02-13
  • 2016-01-12
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
相关资源
最近更新 更多