Java JAXB解组返回Null
我正在制作这个示例GUI,它可以简单地将计算机部件从一侧移动到另一侧,并能够将列表(xml)加载和保存到桌面。除了重新加载保存的xml文件外,其他一切都正常工作。我认为这与Save.java中的注释有关。尽管如此,我不确定需要什么,或者这是否是问题所在。任何帮助都将不胜感激 Window.javaJava JAXB解组返回Null,java,xml,jaxb,Java,Xml,Jaxb,我正在制作这个示例GUI,它可以简单地将计算机部件从一侧移动到另一侧,并能够将列表(xml)加载和保存到桌面。除了重新加载保存的xml文件外,其他一切都正常工作。我认为这与Save.java中的注释有关。尽管如此,我不确定需要什么,或者这是否是问题所在。任何帮助都将不胜感激 Window.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.ListSelectionModel;
import java.awt.Component;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JList;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
initialize();
}
public void addTo(JPanel displayPanel, Component contentToAdd)
{
displayPanel.add(contentToAdd);
}
public void initialize() {
//setting the dimension for the JList panels
Dimension sidePanelSize = new Dimension(180, 540);
frame = new JFrame();
frame.setBounds(100, 100, 480, 540);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creating the menu bar
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
//adding File option to menu bar
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
//adding load option to File
JMenuItem mntmLoad = new JMenuItem("Load");
mnFile.add(mntmLoad);
//adding save option to File
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
//adding exit option to File
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
//creating Jpanel that will hold JList for computer parts
//that you can choose
final JPanel itemPanel = new JPanel();
itemPanel.setPreferredSize(sidePanelSize);
itemPanel.setBackground(Color.WHITE);
itemPanel.setLayout(new BorderLayout());
//Create the model that will hold the computer items
//For loop to add the strings to the model
DefaultListModel<String> model = new DefaultListModel<>();
for (String items : new String [] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"})
model.addElement(items);
//Create JList(itemList) and set its model to the one
//holding the computer parts
final JList<String> itemList = new JList<>(model);
//Setting attributes for the JList(itemList) - font, Number of elements you can select at a time
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
itemList.setFont(new Font("SegoeUI", Font.BOLD, 11));
//adding the JList to the Panel
itemPanel.add(itemList, BorderLayout.WEST);
//adding the Panel to the frame
frame.getContentPane().add(itemPanel, BorderLayout.WEST);
//creating two panels that are used for centering the JList buttons
JPanel buttonContainer = new JPanel();
JPanel buttonList = new JPanel();
GridBagConstraints c = new GridBagConstraints();
//setting the layout managers for the panels and
//adding color to the background
buttonList.setLayout(new BoxLayout(buttonList, BoxLayout.Y_AXIS));
buttonContainer.setLayout(new GridBagLayout());
buttonContainer.setBackground(new Color(238, 238, 238));
//adding the button to add content from Jlist on the left(itemList)
//to the right JList(addToList)
JButton addButton = new JButton(">>");
buttonList.add(addButton);
//adding the button to remove content form the JList(addToList)
JButton deleteButton = new JButton("<<");
buttonList.add(deleteButton);
//setting where to start inputing element into the
//grid of the ButtonContainer
c.gridx = 0;
c.gridy = 0;
//adding the button panel container and its constraints
//to the main container
//finally adding it all to the main frame
buttonContainer.add(buttonList, c);
frame.getContentPane().add(buttonContainer, BorderLayout.CENTER);
//creating the JList that we will add and remove from
final JList<String> addToList = new JList<>(new DefaultListModel<String>());
//creating the panel to hold the JList(addToList)
//setting its size and layout in the manager
//finally adding it to the main frame
final JPanel displayPanel = new JPanel();
displayPanel.setPreferredSize(sidePanelSize);
displayPanel.setBackground(Color.WHITE);
displayPanel.add(addToList, BorderLayout.EAST);
frame.getContentPane().add(displayPanel, BorderLayout.EAST);
//Here is all the action listeners for button click events and menu events
//contains all the methods for the action events
final ActionListeners b = new ActionListeners();
//Listener that adds selected computer parts from left JList(itemList) to the right JList(addToList)
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
b.addContent(itemList, addToList);
}
});
//Listener that removes selected computer part from the JList(addToList)
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.removeContent(addToList);
}
});
//Listener that calls the save methods to save JList(addToList) content into xml
mntmSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.saveContent((DefaultListModel<String>) addToList.getModel());
}
});
//Listener that call the load methods to load xml into the JList(addToList)
mntmLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.loadContent(addToList);
}
});
//Exits the program entirely
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.exitProgram();
}
});
}
}
import java.io.File;
import javax.swing.DefaultListModel;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Load {
//loads the file into the JList to be displayed in the program
public DefaultListModel<String> loadXMLFile() {
//array that holds the content from the xml file
//model that will have xml file's content added to it
//from the array
DefaultListModel<String> modelToReturn = new DefaultListModel<>();
String[] partsList = null;
try {
String homeDir = System.getProperty("user.home");
File file = new File(homeDir + "/Desktop/xml.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Save.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Save load = (Save) jaxbUnmarshaller.unmarshal(file);
partsList = new String [load.getPartsList().length];
} catch (JAXBException e) {
e.printStackTrace();
}
//adds the strings in the arrayToReturn
//to the model that will be returned
for(int i = 0; i < partsList.length; i++)
{
modelToReturn.addElement(partsList[i]);
}
return modelToReturn;
}
}
import java.io.File;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class ActionListeners {
public void addContent(JList<String> itemList, JList<String> addToList)
{
//gets the value selected to be added to other other JList
List<String> selected = itemList.getSelectedValuesList();
//gets the model of the List to be added too
DefaultListModel<String> displayModel = (DefaultListModel<String>) addToList.getModel();
//adds the elements to the JList
for (String item: selected)
{
displayModel.addElement(item);
}
}
public void removeContent(JList<String> addToList)
{
//gets the element selected to be removed
List<String> selected = addToList.getSelectedValuesList();
//gets the model of the JList where content will be removed
DefaultListModel<String> displayModel = (DefaultListModel<String>) addToList.getModel();
//removes the selected element
for (String item: selected) {
displayModel.removeElement(item);
}
}
public void saveContent(DefaultListModel<String> addToList)
{
Save saveFile = new Save();
//adds the content in the JList to be saved
//to the object
saveFile.setPartsList(addToList);
try {
JAXBContext jaxbContext =
JAXBContext.newInstance(Save.class);
Marshaller jaxbMarshaller =
jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
String homeDir = System.getProperty("user.home");
jaxbMarshaller.marshal(saveFile, new File(homeDir + "/Desktop", "xml.xml"));
jaxbMarshaller.marshal(saveFile, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
//saves the content
//saveFile.saveFileXml();
}
public void loadContent(JList<String> addToList)
{
Load loadFile = new Load();
//gets the model of the JList that loaded content will be added too
DefaultListModel<String> newModel= (DefaultListModel<String>) addToList.getModel();
//makes sure the model is clear
newModel.removeAllElements();
//makes model that the loaded content will be set too
DefaultListModel<String> loadedModel = loadFile.loadXMLFile();
//adds the loaded elements from the file to JList's model
for(int i = 0; i < loadedModel.getSize(); i++)
{
newModel.addElement(loadedModel.get(i));
}
}
public void exitProgram()
{
//closes the entire program
System.exit(0);
}
}
import javax.swing.DefaultListModel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement (name = "lists")
public class Save {
//array that will hold the content to be saved
String[] partsListSave;
//method to set the array partsListSave
//with the content that will be saved
public void setPartsList(DefaultListModel<String> model) {
//Initialize the array with the length of the content
//to be added
partsListSave = new String[model.getSize()];
//adds the content to the array
for (int i = 0; i < model.getSize(); i++)
{
partsListSave[i] = model.getElementAt(i);
}
}
@XmlElement (name = "parts")
public String[] getPartsList() {
return partsListSave;
}
}
导入java.awt.EventQueue;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入java.awt.BorderLayout;
导入javax.swing.JButton;
导入java.awt.event.ActionListener;
导入java.awt.event.ActionEvent;
导入javax.swing.DefaultListModel;
导入javax.swing.JMenuBar;
导入javax.swing.JMenuItem;
导入javax.swing.JMenu;
导入javax.swing.ListSelectionModel;
导入java.awt.Component;
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.Font;
导入javax.swing.BoxLayout;
导入javax.swing.JList;
导入java.awt.GridBagLayout;
导入java.awt.GridBagConstraints;
公共类窗口{
私有JFrame;
公共静态void main(字符串[]args){
invokeLater(新的Runnable(){
公开募捐{
试一试{
窗口=新窗口();
window.frame.setVisible(true);
}捕获(例外e){
e、 printStackTrace();
}
}
});
}
公共窗口(){
初始化();
}
public void addTo(JPanel显示面板,组件内容添加)
{
displayPanel.add(内容添加);
}
公共无效初始化(){
//设置JList面板的尺寸
尺寸侧面板尺寸=新尺寸(180540);
frame=新的JFrame();
机架立根(100100480540);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建菜单栏
JMenuBar menuBar=新的JMenuBar();
frame.setJMenuBar(菜单栏);
//将文件选项添加到菜单栏
JMenu mnFile=新JMenu(“文件”);
menuBar.add(mnFile);
//向文件添加加载选项
JMenuItem mntmLoad=新JMenuItem(“加载”);
mnFile.add(mntmLoad);
//向文件添加保存选项
JMenuItem mntmSave=新的JMenuItem(“保存”);
mnFile.add(mntmSave);
//将退出选项添加到文件
JMenuItem mntmExit=新的JMenuItem(“退出”);
mnFile.add(mntmExit);
//创建将保存计算机部件JList的Jpanel
//你可以选择
final JPanel itemPanel=new JPanel();
itemPanel.setPreferredSize(侧面板大小);
itemPanel.setBackground(颜色:白色);
setLayout(新的BorderLayout());
//创建将保存计算机项的模型
//For循环将字符串添加到模型中
DefaultListModel=新的DefaultListModel();
对于(字符串项:新字符串[]{“机箱”、“主板”、“CPU”、“GPU”、“PSU”、“RAM”、“HDD”})
模型.附录(项目);
//创建JList(itemList)并将其模型设置为
//拿着电脑零件
最终JList项目列表=新JList(型号);
//设置JList(itemList)的属性-字体,一次可以选择的元素数
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setFont(新字体(“segoui”,Font.BOLD,11));
//将JList添加到面板
添加(itemList,BorderLayout.WEST);
//将面板添加到框架中
frame.getContentPane().add(itemPanel,BorderLayout.WEST);
//创建两个用于使JList按钮居中的面板
JPanel buttonContainer=新的JPanel();
JPanel buttonList=新的JPanel();
GridBagConstraints c=新的GridBagConstraints();
//设置面板和面板的布局管理器
//为背景添加颜色
buttonList.setLayout(新的BoxLayout(buttonList,BoxLayout.Y_轴));
buttonContainer.setLayout(新的GridBagLayout());
按钮容器。收进背景(新颜色(238238238238));
//添加按钮以添加左侧Jlist(itemList)中的内容
//到右侧JList(addToList)
JButton addButton=新JButton(“>>”);
按钮列表。添加(添加按钮);
//添加按钮以删除JList(addToList)中的内容
JButton deleteButton=newjbutton(“您的Save.java
类需要一个合适的setter方法:
public void setPartsList(String[] partsListSave) {
this.partsListSave = partsListSave;
}
为了验证这一点,我创建了文件xml.xml
:
<lists>
<parts>Part 1</parts>
<parts>Part 2</parts>
<parts>Part 3</parts>
</lists>
使用Save.java
,NPE失败。添加setter有效
最小、完整且可验证
注意
你的问题部分是基于误解
JAXB解组器(对jaxbUnmarshaller.unmarshal(file);
)的调用)不会返回null
——它会返回一个Save
的实例。
unmarshal()
本身从不返回null
(请参阅:“unmarshal方法从不返回null。”)-但是它返回的实例中的字段可能是null
在这种情况下,字段Save.partsListSave
为null
,因为JAXB无法对其进行设置,因为没有合适的setter,如上所述
您看到的NullPointerException是由于尝试使用getPartsList()返回的值引起的
,即null
,因为您的问题是XML的解组,Window.java和ActionListeners.java可能与您的问题无关,但XML.XML的内容非常相关。请参阅@Andreas我添加了其他文件,以防它们以某种方式与情况相关。请参阅我提供的MCVE链接d、 我指的是“最小”部分,你尽可能简洁地陈述你的问题,所以t
<lists>
<parts>Part 1</parts>
<parts>Part 2</parts>
<parts>Part 3</parts>
</lists>
public static void main(String[] args) throws Exception {
File file = new File("xml.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Save.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Save load = (Save) jaxbUnmarshaller.unmarshal(file);
for (String parts : load.getPartsList())
System.out.println(parts);
}