让用户定义要编辑的XML文件的文件路径

huangapple go评论61阅读模式
英文:

Letting the user define a file path for an XML file to be edited

问题

最近,我一直在将我创建的用于编辑游戏中关卡的XML文件的Python脚本转换为Java,但我遇到了一个问题。我想要让用户设置要编辑的XML文件的路径,因为他们可能想要编辑多个文件,但按照我的代码方式,我无法弄清楚如何实现。

我已经将我的完整代码放在下面:

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class mapEdit {

    public static void main(String[] args) {
        try {
            String filePath = "B:/SteamLibrary/steamapps/common/Tasty Planet/assets/levels/bacteria.xml";
            File file = new File(filePath);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            Element root = doc.getDocumentElement();

            JFrame frame = new JFrame("Map Size Editor");

            JPanel heightPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            heightPanel.add(new JLabel("Rows of tiles to add (height)"));
            heightPanel.add(new JTextField(10));

            JPanel widthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            widthPanel add(new JLabel("Rows of tiles to add (width)"));
            widthPanel.add(new JTextField(10));

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JButton setSizeButton = new JButton("Set Size");

            setSizeButton.addActionListener(e -> {
                System.out.println("you entered " + ((JTextField) heightPanel.getComponent(1)).getText());
                float height = Float.parseFloat(root.getAttribute("height"))
                        + (Integer.parseInt(((JTextField) heightPanel.getComponent(1)).getText()) * 256);
                float width = Float.parseFloat(root.getAttribute("width"))
                        + (Integer.parseInt(((JTextField) widthPanel.getComponent(1)).getText()) * 256);
                System.println("height was: " + root.getAttribute("height"));
                root.setAttribute("height", String.valueOf(height));
                System.out.println("height is: " + root.getAttribute("height"));

                System.out.println("width was: " + root.getAttribute("width"));
                root.setAttribute("width", String.valueOf(width));
                System.out.println("width is: " + root.getAttribute("width"));

                try {
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = new StreamResult(file);
                    transformer.transform(source, result);
                    JOptionPane.showMessageDialog(frame, "Changes were successful.");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            buttonPanel.add(setSizeButton);

            JPanel contentPanel = new JPanel();
            contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
            contentPanel.add(heightPanel);
            contentPanel.add(widthPanel);
            contentPanel.add(buttonPanel);

            frame.setContentPane(contentPanel);
            frame.setMinimumSize(new Dimension(400, 200));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

我尝试向GUI添加按钮和文本输入,并使用它们来设置filePath变量,但这并没有起作用。

英文:

recently i've been converting a python script i made to edit XML files that are used as levels in a game, to java and i've found a problem.
i want to let the user set the path for the XML file to edit as there are many that they may want to edit but the way my code works i can't figure out how to do that

i have put my full code below

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class mapEdit {

    public static void main(String[] args) {
        try {
            String filePath = "B:/SteamLibrary/steamapps/common/Tasty Planet/assets/levels/bacteria.xml";
            File file = new File(filePath);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            Element root = doc.getDocumentElement();

            JFrame frame = new JFrame("Map Size Editor");

            JPanel heightPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            heightPanel.add(new JLabel("Rows of tiles to add (height)"));
            heightPanel.add(new JTextField(10));

            JPanel widthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            widthPanel.add(new JLabel("Rows of tiles to add (width)"));
            widthPanel.add(new JTextField(10));

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JButton setSizeButton = new JButton("Set Size");


            setSizeButton.addActionListener(e -> {
                System.out.println("you entered " + ((JTextField) heightPanel.getComponent(1)).getText());
                float height = Float.parseFloat(root.getAttribute("height"))
                        + (Integer.parseInt(((JTextField) heightPanel.getComponent(1)).getText()) * 256);
                float width = Float.parseFloat(root.getAttribute("width"))
                        + (Integer.parseInt(((JTextField) widthPanel.getComponent(1)).getText()) * 256);
                System.out.println("height was: " + root.getAttribute("height"));
                root.setAttribute("height", String.valueOf(height));
                System.out.println("height is: " + root.getAttribute("height"));

                System.out.println("width was: " + root.getAttribute("width"));
                root.setAttribute("width", String.valueOf(width));
                System.out.println("width is: " + root.getAttribute("width"));

                try {
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = new StreamResult(file);
                    transformer.transform(source, result);
                    JOptionPane.showMessageDialog(frame, "Changes were successful.");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            buttonPanel.add(setSizeButton);

            JPanel contentPanel = new JPanel();
            contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
            contentPanel.add(heightPanel);
            contentPanel.add(widthPanel);
            contentPanel.add(buttonPanel);

            frame.setContentPane(contentPanel);
            frame.setMinimumSize(new Dimension(400, 200));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

i have tried adding a button and text input to the GUI and using that to set the filePath variable but that didn't work

答案1

得分: 0

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.File;

public class XMLFileReader {

    public void buildGui() {
        JPanel contentPanel = new JPanel();
        try {
            // 打开文件选择对话框
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            // 文件过滤器
            FileNameExtensionFilter filter = new FileNameExtensionFilter("XML 文件", "xml");
            fileChooser.setFileFilter(filter);

            int result = fileChooser.showOpenDialog(contentPanel);
            if (result != JFileChooser.APPROVE_OPTION) {
                JOptionPane.showMessageDialog(contentPanel, "出错了,抱歉");
                return;
            }
            File selectedFile = fileChooser.getSelectedFile();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(selectedFile);
            Element root = doc.getDocumentElement();

            JPanel heightPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            heightPanel.add(new JLabel("要添加的瓷砖行数 (高度)"));
            heightPanel.add(new JTextField(10));

            JPanel widthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            widthPanel.add(new JLabel("要添加的瓷砖列数 (宽度)"));
            widthPanel.add(new JTextField(10));

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JButton setSizeButton = new JButton("设置尺寸");

            JFrame frame = new JFrame("地图尺寸编辑器");
            setSizeButton.addActionListener(e -> transformResult(heightPanel, widthPanel, root, doc, selectedFile, frame, contentPanel));
            buttonPanel.add(setSizeButton);
            contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
            contentPanel.add(heightPanel);
            contentPanel.add(widthPanel);
            contentPanel.add(buttonPanel);

            frame.setContentPane(contentPanel);
            frame.setMinimumSize(new Dimension(400, 200));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(contentPanel, "出错了,抱歉:" + ex.getMessage());
        }
    }

    private void transformResult(JPanel heightPanel, JPanel widthPanel, Element root, Document doc, File selectedFile, JFrame frame, JPanel contentPanel) {

        try {
            System.out.println("你输入了:" + ((JTextField) heightPanel.getComponent(1)).getText());
            float height = Float.parseFloat(root.getAttribute("height")) + (Integer.parseInt(((JTextField) heightPanel.getComponent(1)).getText()) * 256);
            float width = Float.parseFloat(root.getAttribute("width")) + (Integer.parseInt(((JTextField) widthPanel.getComponent(1)).getText()) * 256);
            System.out.println("高度之前是:" + root.getAttribute("height"));
            root.setAttribute("height", String.valueOf(height));
            System.out.println("高度是:" + root.getAttribute("height"));

            System.out.println("宽度之前是:" + root.getAttribute("width"));
            root.setAttribute("width", String.valueOf(width));
            System.out.println("宽度是:" + root.getAttribute("width"));

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult result2 = new StreamResult(selectedFile);
            transformer.transform(source, result2);
            JOptionPane.showMessageDialog(frame, "修改成功。");

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(contentPanel, "出错了,抱歉:" + ex.getMessage());
        }

    }
}
英文:
        import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.File;
public class XMLFileReader {
public void buildGui() {
JPanel contentPanel = new JPanel();
try {
// Open file chooser dialog
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
//File filter
FileNameExtensionFilter filter = new FileNameExtensionFilter("XML files", "xml");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(contentPanel);
if (result != JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(contentPanel, "Something is went wrong, sorry");
return;
}
File selectedFile = fileChooser.getSelectedFile();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(selectedFile);
Element root = doc.getDocumentElement();
JPanel heightPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
heightPanel.add(new JLabel("Rows of tiles to add (height)"));
heightPanel.add(new JTextField(10));
JPanel widthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
widthPanel.add(new JLabel("Rows of tiles to add (width)"));
widthPanel.add(new JTextField(10));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton setSizeButton = new JButton("Set Size");
JFrame frame = new JFrame("Map Size Editor");
setSizeButton.addActionListener(e -> transformResult (heightPanel, widthPanel, root, doc, selectedFile, frame, contentPanel));
buttonPanel.add(setSizeButton);
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(heightPanel);
contentPanel.add(widthPanel);
contentPanel.add(buttonPanel);
frame.setContentPane(contentPanel);
frame.setMinimumSize(new Dimension(400, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
} catch (Exception ex) {
JOptionPane.showMessageDialog(contentPanel, "Something is went wrong, sorry :" + ex.getMessage());
}
}
private void transformResult(JPanel heightPanel, JPanel widthPanel, Element root, Document doc, File selectedFile, JFrame frame, JPanel contentPanel) {
try {
System.out.println("you entered " + ((JTextField) heightPanel.getComponent(1)).getText());
float height = Float.parseFloat(root.getAttribute("height")) + (Integer.parseInt(((JTextField) heightPanel.getComponent(1)).getText()) * 256);
float width = Float.parseFloat(root.getAttribute("width")) + (Integer.parseInt(((JTextField) widthPanel.getComponent(1)).getText()) * 256);
System.out.println("height was: " + root.getAttribute("height"));
root.setAttribute("height", String.valueOf(height));
System.out.println("height is: " + root.getAttribute("height"));
System.out.println("width was: " + root.getAttribute("width"));
root.setAttribute("width", String.valueOf(width));
System.out.println("width is: " + root.getAttribute("width"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result2 = new StreamResult(selectedFile);
transformer.transform(source, result2);
JOptionPane.showMessageDialog(frame, "Changes were successful.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(contentPanel, "Something is went wrong, sorry :" + ex.getMessage());
}
}
}

huangapple
  • 本文由 发表于 2023年2月16日 04:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定