2014-12-01 25 views
0

我試圖在java中創建按鈕,用這個代碼繪製一些東西。我在NetBeans圖形模式下的java代碼有問題

import java.applet.Applet; 
import java.awt.*; 
import java.awt.event.*; 

public class primeraapplet extends Applet implements ActionListener{ 

    Button bt1, bt2, bt3; 
    int type=-1; 

    @Override 
    public void init() { 
    setLayout(null); 
    bt1= new Button("Linia"); 
    bt2=new Button("Rectangle"); 
    bt2=new Button("Rodona"); 

    bt1.addActionListener(this); 
    bt2.addActionListener(this); 
    bt3.addActionListener(this); 

    bt1.setBounds(10, 20, 100, 50); 
    bt2.setBounds(120, 20, 100, 50); 
    bt3.setBounds(10, 20, 100, 50); 

    bt1.setForeground(Color.blue); 
    bt1.setBackground(Color.black); 

    bt1.setFont(new Font("times New Roman", Font.BOLD,16)); 
    bt2.setForeground(Color.red); 
    bt2.setBackground(Color.yellow); 
    bt2.setFont(new Font("times New Roman", Font.BOLD,16)); 

    bt3.setForeground(Color.black); 
    bt3.setBackground(Color.white); 
    bt3.setFont(new Font("times New Roman", Font.BOLD,16)); 

    add(bt1); 
    add(bt2); 
    add(bt3); 

    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     Button ref; 
     ref = (Button) e.getSource(); 
     if (ref==bt1) 
      type=1; 
     else if (ref==bt2) 
      type=2; 
     else 
      type=3; 
     repaint(); 
    } 

    @Override 
    public void paint(Graphics g) { 
     if (type==1) 
      g.drawLine(100, 65, 90, 150); 
     else if (type==2) 
      g.drawRect(100, 65, 90, 190); 
     else if(type==2) 
      g.drawOval(100, 65, 90, 90); 
    } 
} 

,這讓我這個錯誤:

java.lang.NullPointerException 
    at primeraapplet.init(primeraapplet.java:34) 
    at sun.applet.AppletPanel.run(AppletPanel.java:434) 
    at java.lang.Thread.run(Thread.java:745) 
+0

很高興指出錯誤實際發生在哪一行,尤其是因爲我刪除了一堆無用的評論。 – 2014-12-01 19:01:17

+0

在你的'paint()'方法中,爲什麼你有兩個具有完全相同條件的'else-if'語句?此外,該if語句將需要大括號或它不會工作。在'actionPerformed()'中同上。同樣使用'paint()'''''''''''''''''''''''''''''''但是從未聲明這裏有很多事情要做。 – 2014-12-01 19:10:02

+0

避免使用'null'佈局,像素完美的佈局是現代UI設計中的一種幻覺。影響組件的個體大小的因素太多,其中沒有一個可以控制。該API旨在與佈局經理一起工作,放棄這些將導致無法結束的問題和問題,您將花費越來越多的時間來糾正 – MadProgrammer 2014-12-02 00:36:08

回答

0
@Override 
    public void init() { 
    setLayout(null); 
    bt1= new Button("Linia"); 
    bt2=new Button("Rectangle"); 
    bt3=new Button("Rodona"); //You had bt2=new Button("Rodona"); 

變量錯誤代碼。你不能用同樣的變量和新的Button一起設置相同的nam!

1

你爲什麼要設置您的佈局爲空?

setLayout(null); // shouldn't this line be the source of your problems?