Я пишу симулятор Memory Manger и работал с Jtables для отображения таблицы разделов.Я работал с другим графическим интерфейсом.Я воссоздал графический интерфейс, используя другой стиль макета (абсолютный) с JPanel, и теперь код для создания моей таблицы разделов не может быть инициализирован.
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
public class mWindow extends JFrame {
private static final long serialVersionUID = 1L;
private final FixedMemory fpMemory = new FixedMemory(this); // Fixed Partition Memory Scheme
private final Queue jobQueue = new Queue(this); // New Job Queue
public JTextField statusField;
public JComboBox<String> memScheme_cb;
public DefaultTableModel ptModel;
public List<Job> JobQueueList = new ArrayList<Job>(); // Job Queue
public List<Partition> PartTableList = new ArrayList<Partition>(); // Partition Table
// Window Constructor
public mWindow() {
// Setup Main Window ==================================================================
getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 12));
getContentPane().setLayout(null);
// Set up the panel to hold control objects (buttons, Combo Box, Status Text Field
// Setup Control Panel Area to contain buttons, Combo box and statusField ==========================
JPanel controlPanel = new JPanel();
controlPanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
controlPanel.setBounds(10, 10, 490, 80);
controlPanel.setLayout(null);
getContentPane().add(controlPanel);
// Setup statusField to update current Process ================================================
statusField = new JTextField();
statusField.setBounds(145, 46, 335, 23);
statusField.setFont(new Font("Tahoma", Font.PLAIN, 12));
statusField.setEditable(false);
statusField.setBackground(new Color(240,240,240));
statusField.setText("No Job Processes Running"); // set initial message
controlPanel.add(statusField);
// Setup button to process memory scheme==================================================
JButton btnProcScheme = new JButton("Process Memory");
btnProcScheme.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String memScheme = (String) memScheme_cb.getSelectedItem();
if ( memScheme == "Fixed Memory" ){
statusField.setText("Fixed Memory");
// Call a fixed partition scheme and create Job Queue
fpMemory.createPartition(PartTableList);
jobQueue.createJobQueue();
}else if ( memScheme == "Dynamic FirstFit" ){
statusField.setText("Dynamic FirstFit" );
}else if ( memScheme == "Dynamic BestFit" ){
statusField.setText("Dynamic BestFit");
}else if ( memScheme == "Dynamic WorstFit" ){
statusField.setText("Dynamic WorstFit");
} else if ( memScheme == ""){
statusField.setText("No Memory Scheme Selected");
}
}
});
btnProcScheme.setBounds(10, 11, 125, 23);
controlPanel.add(btnProcScheme);
// Setup combo box to choose type of memory Scheme
memScheme_cb = new JComboBox<String>();
memScheme_cb.setBounds(145, 11, 335, 23);
memScheme_cb.setModel(new DefaultComboBoxModel<String>(new String[]
{"", "Fix Memory Partition", "Dynamic First Fit Partition", "Dynamic Best Fit Partition"}));
memScheme_cb.setSelectedIndex(0);
memScheme_cb.setMaximumRowCount(80);
controlPanel.add(memScheme_cb);
// Process Job Button==================================================================
JButton btnProcJob = new JButton("Process Job Queue");
btnProcJob.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Call the Queue and process Jobs based on memory scheme
jobQueue.procFixedJobQueue();
}
});
btnProcJob.setBounds(10, 47, 125, 23);
controlPanel.add(btnProcJob);
// Setup Partition Table Area =============================================================
JPanel tablePanel = new JPanel();
tablePanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
tablePanel.setBounds(10, 90, 490, 370);
tablePanel.setLayout(null);
getContentPane().add(tablePanel);
JScrollPane partTable_sp = new JScrollPane(); // container to hold table
getContentPane().add(partTable_sp); // add container to layout
partTable_sp.setBounds(15, 95, 480, 100); // sets where container is placed
JTable partTable = new JTable(ptModel); // create new table
partTable.setPreferredScrollableViewportSize(new Dimension(480,100)); // set size of container
partTable_sp.setViewportView(partTable); // show table in container
ptModel.addColumn("Partition Size"); // add Columns to table
ptModel.addColumn("Partition Address"); //
ptModel.addColumn("Access"); //
ptModel.addColumn("Partition Status"); //
TableColumn column = new TableColumn(); // creates column variable
// Sets up predefined column widths
for (int i = 0 ; i < partTable.getColumnCount();i++){
column = partTable.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
}
// Setup snapshot Panel ================================================================
JPanel snapPanel = new JPanel();
snapPanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
snapPanel.setBounds(500, 10, 120, 450);
getContentPane().add(snapPanel);
snapPanel.setLayout(null);
Canvas snapFrame = new Canvas();
snapFrame.setBounds(505, 15, 110, 440);
snapFrame.setBackground(new Color(230,230,230));
getContentPane().add(snapFrame);
}
// draw the segment of memory in the snapshot display at the address starting location
// and the size of the memory segment (y value and the width are predetermined and are hard coded
public void displaySeg(Graphics g, int address, int size){
g.setColor(new Color(245,245,245));
g.drawRect(500,address+10, 120, size);
}
/**
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mWindow frame = new mWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Memory Manager v.01");
Dimension windowSize = new Dimension(650,510);
frame.setMinimumSize(windowSize);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Трассировка стека:
java.lang.NullPointerException
at mWindow.<init>(mWindow.java:136)
at mWindow$3.run(mWindow.java:181)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Проблема кода лежит здесь ????
JTable partTable = new JTable(ptModel); // create new table
partTable.setPreferredScrollableViewportSize(new Dimension(480,100)); // set size of container
partTable_sp.setViewportView(partTable); // show table in container
ptModel.addColumn("Partition Size"); // add Columns to table
ptModel.addColumn("Partition Address"); //
ptModel.addColumn("Access"); //
ptModel.addColumn("Partition Status"); //
TableColumn column = new TableColumn(); // creates column variable
// Sets up predefined column widths
for (int i = 0 ; i < partTable.getColumnCount();i++){
column = partTable.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
}
Оооочень ... строка 136 это "ptModel.addColumn (" Размер раздела ");"но из-за своей жизни я не могу понять, почему это потерпит неудачу (хотя я уверен, что это просто нечто, что я упустил из виду) ... А может и нет.Я сравнил его с моим исходным кодом GUI, и он отлично работает.Любая помощь будет принята с благодарностью!