// a simple exmple that can show the basis of swing
-------------------------------------------------------------------------
// import pakages which we need
import javax.swing.*;
import java.awt.*;
public class HelloCsdn
{
public static void main(String[] args)
{
HelloCsdnFrame frame=new HelloCsdnFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/** this part we construct a new frame HelloCsdnFrame
*/
-------------------------------------------------------------------------
class HelloCsdnFrame extends JFrame{
public HelloCsdnFrame()
{
setTitle("Hello CSDN.NET");
setSize(WIDTH,HEIGHT);
HelloCsdnPanel panel=new HelloCsdnPanel();
Container c=getContentPane();
c.add(panel);
}
public static final int WIDTH=300;
public static final int HEIGHT=200;
}
/**this part we extend our HelloCsdnFram to JFrame and
construct a new object HelloCsdnPanel and add it on the frame
/*
--------------------------------------------------------------------
class HelloCsdnPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Hello CSDN.NET",MESSAGE_X,MESSAGE_Y);
}
public static final int MESSAGE_X=100;
public static final int MESSAGE_Y=100;
}
/** A panel that display a message
*/
我把此程式分為3part.每一部分都有注釋,這一段代碼是做什麼用的。 一起來分析此程式:
在第一部分
// import pakages which we need
import javax.swing.*;
import java.awt.*;
public class HelloCsdn
{
public static void main(String[] args)
{
HelloCsdnFrame frame=new HelloCsdnFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/** this part we construct a new frame HelloCsdnFrame
*/
class HelloCsdnFrame extends JFrame{
public HelloCsdnFrame()
{
setTitle("Hello CSDN.NET");
setSize(WIDTH,HEIGHT);
HelloCsdnPanel panel=new HelloCsdnPanel();
Container c=getContentPane();
c.add(panel);
}
public static final int WIDTH=300;
public static final int HEIGHT=200;
}
/**this part we extend our HelloCsdnFram to JFrame and
construct a new object HelloCsdnPanel and add it on the frame
/*
class HelloCsdnPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Hello CSDN.NET",MESSAGE_X,MESSAGE_Y);
}
public static final int MESSAGE_X=100;
public static final int MESSAGE_Y=100;
}
/** A panel that display a message
*/ 繼續我們繼承剛建立的HelloCsdnPanel