Я пытаюсь создать базовый макет сетки в панели с вкладками с помощью строки меню.Использование диспетчера макетов и JFrame, NullPointerException
В строке меню будет основной файл JMenu с элементом меню выхода и цветом JMenu, который изменит цвет шрифта и цвета фона.
Одна вкладка рассчитает функцию PMT, используемую в Excel.
Вторая вкладка будет вычислять будущую стоимость как используемую в Excel.
Заключительная вкладка - это простой макет справки.
При попытке просмотреть макет и основные функции я получаю исключение NullPointerException. Exception, как представляется, вызывается в строке 208 (где TextArea будет отображать вычисления для функции PMT) в строке 52 (где вызывается createPage1()), а в строке 263 (где mainframe создается как «Финансы»).
Последний из которых я действительно не понимаю цели и ее функциональность. Это незавершенное производство, и никакие формулы не добавлены, и не было добавлено все actionListeners. Единственное, что я хочу сейчас - это посмотреть макет.
public class Finance extends JFrame{
private JTabbedPane tabPane;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu colorMenu;
private JMenuItem exitItem;
private JRadioButtonMenuItem blueItem;
private JRadioButtonMenuItem blackItem;
private JRadioButtonMenuItem redItem;
private JRadioButtonMenuItem whiteItem;
private JRadioButtonMenuItem defItem;
private JButton calc1;
private JButton calc2;
TextArea text;
public Finance(){
setTitle("Finance");
setBackground(Color.GRAY);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createPage1();
createPage2();
createPage3();
tabPane = new JTabbedPane();
tabPane.addTab("Loan Payment", panel1);
tabPane.addTab("Future Value", panel2);
tabPane.addTab("Help", panel3);
topPanel.add(tabPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildMenuBar();
pack();
}
public void buildMenuBar(){
menuBar = new JMenuBar();
buildFileMenu();
buildColorMenu();
menuBar.add(fileMenu);
menuBar.add(colorMenu);
setJMenuBar(menuBar);
}
public void buildFileMenu(){
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(exitItem);
}
public void buildColorMenu(){
defItem = new JRadioButtonMenuItem("Deafult", true);
defItem.setMnemonic(KeyEvent.VK_D);
defItem.addActionListener(new ColorListener());
blueItem = new JRadioButtonMenuItem("Blue");
blueItem.setMnemonic(KeyEvent.VK_B);
blueItem.addActionListener(new ColorListener());
blackItem = new JRadioButtonMenuItem("Black");
blackItem.setMnemonic(KeyEvent.VK_L);
blackItem.addActionListener(new ColorListener());
whiteItem = new JRadioButtonMenuItem("White");
whiteItem.setMnemonic(KeyEvent.VK_W);
whiteItem.addActionListener(new ColorListener());
redItem = new JRadioButtonMenuItem("Red");
redItem.setMnemonic(KeyEvent.VK_R);
redItem.addActionListener(new ColorListener());
ButtonGroup group = new ButtonGroup();
group.add(blueItem);
group.add(blackItem);
group.add(whiteItem);
group.add(redItem);
colorMenu = new JMenu("Color");
colorMenu.setMnemonic(KeyEvent.VK_C);
colorMenu.add(defItem);
colorMenu.addSeparator();
colorMenu.add(blueItem);
colorMenu.add(blackItem);
colorMenu.add(whiteItem);
colorMenu.add(redItem);
}
private class ExitListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
private class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(blackItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.BLACK);
panel3.setBackground(Color.BLACK);
}
else if(redItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.RED);
panel2.setBackground(Color.RED);
panel3.setBackground(Color.RED);
}
else if(whiteItem.isSelected()){
panel1.setForeground(Color.BLACK);
panel2.setForeground(Color.BLACK);
panel3.setForeground(Color.BLACK);
panel1.setBackground(Color.WHITE);
panel2.setBackground(Color.WHITE);
panel3.setBackground(Color.WHITE);
}
else if(blueItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.BLUE);
panel2.setBackground(Color.BLUE);
panel3.setBackground(Color.BLUE);
}
else if(defItem.isSelected()){
panel1.setForeground(Color.GRAY);
panel2.setForeground(Color.GRAY);
panel3.setForeground(Color.GRAY);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.BLACK);
panel3.setBackground(Color.BLACK);
}
}
}
public void createPage1(){
panel1 = new JPanel();
panel1.setLayout(new GridLayout(5, 2));
calc1 = new JButton("Calculate Payments");
JTextField loan = new JTextField();
JTextField months = new JTextField();
JTextField irp1 = new JTextField();
JTextField pymnt = new JTextField();
text = new TextArea();
panel1.add(new JLabel("Loan Amount:"));
panel1.add(loan);
panel1.add(new JLabel("Payment Length in Months:"));
panel1.add(months);
panel1.add(new JLabel("Interest Rate Percentage:"));
panel1.add(irp1);
panel1.add(new JLabel("Payment Amount (Fixed):"));
panel1.add(pymnt);
panel1.add(calc1);
panel2.add(text);
}
public void createPage2(){
panel2 = new JPanel();
panel2.setLayout(new GridLayout(5,2));
calc2 = new JButton("Calculate Future Value");
JTextField length = new JTextField();
JTextField value = new JTextField();
JTextField monthly = new JTextField();
JTextField irp2 = new JTextField();
JTextField fv = new JTextField();
panel2.add(new JLabel("Initial Value:"));
panel2.add(value);
panel2.add(new JLabel("Monthly Contribution:"));
panel2.add(monthly);
panel2.add(new JLabel("Interest Rate Percentage:"));
panel2.add(irp2);
panel2.add(new JLabel("Length in Years:"));
panel2.add(length);
panel1.add(calc2);
panel2.add(fv);
}
public void createPage3(){
panel3 = new JPanel();
panel3.setLayout(new GridLayout(3,3));
JButton button1 = new JButton("Input");
JButton button2 = new JButton("Output");
JButton button3 = new JButton("Input");
JButton button4 = new JButton("Output");
JButton button5 = new JButton("Navigation");
JButton button6 = new JButton("Information");
panel3.add(new JLabel("Loan Payment:"));
panel3.add(button1);
panel3.add(button2);
panel3.add(new JLabel("Future Value:"));
panel3.add(button3);
panel3.add(button4);
panel3.add(new JLabel("Basic Info:"));
panel3.add(button5);
panel3.add(button6);
}
public static void main(String args[]){
@SuppressWarnings("unused")
Finance mainFrame = new Finance();
}
Полный выход заключается в следующем:
Exception in thread "main" java.lang.NullPointerException
at Finance.createPage1(Finance.java:208)
at Finance.<init>(Finance.java:52)
at Finance.main(Finance.java:263)
Все Помощь приветствуется и ценится. Я больше ищу причину ошибки и общие способы ее устранения, чем для конкретного решения. Не стесняйтесь быть как суждение о кодировании, как хотите, но если что-то можно упростить или изменить, прокомментируйте, как это сделать.
Спасибо, я только что увидел ошибку. Был поиск чего-то большего, чем плохая копия/вставка. Спасибо за ответы – SealsOnSaturn