使用GUI输入然后绘制几个形状

时间:2014-06-29 21:00:22

标签: java swing user-interface event-handling jtextfield

我正在尝试创建一个允许用户输入数字的GUI,然后GUI创建一个该数量的点数组,然后绘制该数量的圆圈。但是,当我运行此代码时,GUI只显示黑色面板并使用system.out.println,它表示JTextField中的数字永远不会到达面板。如何更改我的代码以便用户可以在文本字段中输入数字,按回车键,然后GUI会绘制该数量的圆圈?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


class ControlPanel extends JPanel{

JLabel inLabel;
JTextField inText;

public ControlPanel(){

    setBackground(Color.lightGray);

    inLabel = new JLabel("Enter the number of points: ");
    inText = new JTextField(20);

    add(inLabel);
    add(inText);
}

public JTextField getInText(){
    return inText;
}

public int getNPoints(){
    int nP = Integer.parseInt(inText.getText());
    return nP;
}





}



class PiPanel2 extends JPanel{

private Point[] points;
int nPoints;
Dimension d = new Dimension();
private int X = d.width;
private int Y = d.height;
private int w = 5;
private int h = 5;

public PiPanel2(){

    setBackground(Color.BLACK);



}

public void setNPoints(int nPoints){
    this.nPoints = nPoints;
}
public int getNP(){
    return nPoints;
}


public void paintComponent(Graphics g){

    int n = getNP();
    points = new Point[n];
    System.out.println(n);


    for(int i = 0; i < n; i++){
        points[i] = new Point(Math.random(), Math.random());
    }

    g.setColor(getBackground());
    super.paintComponent(g);

    g.setColor(Color.red);
    g.drawOval(-X, -Y, X*2, Y*2);

    for(int i = 0; i < points.length; i++){

        int x = (int)(points[i].getX()*X);
        int y = (int)(points[i].getY()*Y);

        if(points[i].withinR()){

            g.setColor(Color.blue);
            g.fillOval(x, y, w, h);

        }else if(!points[i].withinR()){

            g.setColor(Color.orange);
            g.fillOval(x, y, w, h);

        }
    }   
}
}
















class PiFrame2 extends JFrame implements ActionListener{

private int X = 600;
private int Y = 600;

ControlPanel control;
PiPanel2 piPan;

public PiFrame2(){

    control = new ControlPanel();
    piPan = new PiPanel2();

    control.getInText().addActionListener(this);

    setLayout(new BorderLayout());
    // and add the panels to the frame
    getContentPane().add(control, BorderLayout.SOUTH);
    getContentPane().add(piPan, BorderLayout.CENTER);

    // this code enables you to close the window
    addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    setSize(X,Y);
    setLocation(500,0);
} 








public void actionPerformed(ActionEvent e) {

    int nPoints = control.getNPoints();

    piPan.setNPoints(nPoints);
}



}

0 个答案:

没有答案