自学的第五篇博客
利用Jpanel设计一个程序
import java.awt.*; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.*; public class JPanelExample extends JFrame { JButton[] buttons; JPanel panel1; CustomPanel panel2; public JPanelExample(){ super("面板示例"); Container container = getContentPane();//创建一个内容面板容器 container.setLayout(new BorderLayout());//设置该窗口布局 panel1 = new JPanel(new FlowLayout()); buttons = new JButton[4]; for(int i=0;i<buttons.length;i++){ buttons[i] = new JButton("按钮"+(i+1)); panel1.add(buttons[i]);//添加按钮 } panel2 = new CustomPanel(); container.add(panel1,BorderLayout.NORTH); container.add(panel2,BorderLayout.CENTER); pack(); setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub JPanelExample jpe=new JPanelExample(); jpe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class CustomPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); g.drawString("welcome to java shape world", 20, 20); g.drawRect(20, 40, 130, 130);//画矩形 g.setColor(Color.green); g.fillRect(20,40,130,130); g.drawOval(160, 40, 100, 100);//画椭圆型 g.setColor(Color.orange); g.fillOval(160, 40, 100, 100); } public Dimension getPreferredSize(){ return new Dimension(200,200); } }
运行结果:
2.基于JFrame实现的窗口界面,窗口界面中间有一个按钮组件。
代码:
import java.awt.*; import javax.swing.*; public class JFrameDemo { JFrame f; JButton b; Container c; public JFrameDemo(){ f = new JFrame("JFrame Demo"); b = new JButton("Press me"); c=f.getContentPane();//获取内容面板容器 c.add(b);//为内容面板容器添加按钮组件 f.setSize(200,200); f.setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub new JFrameDemo(); } }
运行结果:
其实以上这些都是一些基础知识,从下次开始就会稍稍复杂一点。