長方形といくつかのボタンを備えたJFrameを作成するためのサンプルコードがあります。長方形の作成が完了しました。次に、2つのボタンを配置します。1つは開始-上、もう1つは停止-下です。
私はすべてが機能しています、少なくともその科学。ただし、コードを実行するようにスタートボタンを設定しようとすると、何も起こりません。JFrameを作成してエラーが発生したかどうかを確認しようとしましたが、コードは成功しました。JFrameは、開始ボタンで開きpaintComponent()
、停止ボタンですべてを終了することになっています。
少しのガイダンスを提供できる人はいますか、私はこのアウトを理解しようとして何日も眠っていませんでした。
public static void main (String[] args){
TwoButtonsRandomRec two = new TwoButtonsRandomRec();
two.go();
}
public void go(){
JPanel pan = new JPanel(new GridBagLayout());
START = new JButton("START");
START.addActionListener(new StartListener());
STOP = new JButton("STOP");
STOP.addActionListener(new StopListener());
pan.add(START);
pan.add(STOP);
frame = new JFrame();
frame.getContentPane().add(BorderLayout.NORTH, START);
frame.getContentPane().add(BorderLayout.SOUTH, STOP);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void GUI(){
JFrame frame2 = new JFrame();
frame2.setSize(500,500);
frame2.setVisible(true);
}
class StartListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//frame.getContentPane().add(new DrawPanel());
//System.exit(0);
//
DrawPanel panel = new DrawPanel();
}
}
class StopListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
/*
* Panel created
* rectangle drawn to random sizes
*/
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
ran = new Random();
g.setColor(new Color(ran.nextInt(255),+
ran.nextInt(255),ran.nextInt(255)));
height = ran.nextInt(getHeight());
width = ran.nextInt(getWidth());
x = ran.nextInt(getWidth()-width);
y = ran.nextInt(getHeight()-height);
g.fillRect(x,y,width,height);
//repaint();
try{
Thread.sleep(240);
}catch(InterruptedException ie){
}
repaint();
}
}
}