日期:2014-05-20 浏览次数:20742 次
package chapter11; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; public class ButtonDemo extends JFrame implements ActionListener{ //Declare a panle for displaying message private MessagePanel messagePanel; //Declare two buttons to move the message left and right private JButton jbtLeft,jbtRight; public static void main(String[] args){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ e.printStackTrace(); } ButtonDemo frame=new ButtonDemo(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(800,200); frame.setVisible(true); frame.setResizable(false); } /** * Default constructor */ public ButtonDemo(){ setTitle("Button Demo"); //Create a MessagePanel instance and set colors messagePanel=new MessagePanel("Welcome to Java"); messagePanel.setBackground(Color.yellow); JPanel jpButtons=new JPanel(); jpButtons.setLayout(new FlowLayout()); jpButtons.add(jbtLeft=new JButton("<=")); jpButtons.add(jbtRight=new JButton("=>")); jbtLeft.setMnemonic('L'); jbtRight.setMnemonic('R'); //jbtLeft.setIcon(new ImageIcon("left.gif")); jbtLeft.setToolTipText("Move message to letf"); jbtRight.setToolTipText("Move message to right"); getContentPane().setLayout(new BorderLayout()); getContentPane().add(jpButtons,BorderLayout.SOUTH); getContentPane().add(messagePanel,BorderLayout.CENTER); jbtLeft.addActionListener(this); jbtRight.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jbtLeft){ left(); } else if(e.getSource()==jbtRight){ right(); } } private void left(){ int x=messagePanel.getX(); if(x>10){ messagePanel.setX(x-10); messagePanel.repaint();//////////////////////////////////////////// } } private void right(){ int x=messagePanel.getX(); if(x<300){ messagePanel.setX(x+10); messagePanel.repaint(); } } } class MessagePanel extends JPanel{ private boolean centered; private String message; private int x=20; private int y=20; public MessagePanel(String message){ this.message=message; } public int getX(){ return x; } public void setX(int x){ this.x=x; } public int getY(){ return y; } public void setY(int y){ this.y=y; } /** * Paint the message */ public void paintComponent(Graphics g){ super.paintComponent(g); g.setFont(new Font("",Font.BOLD,20)); g.drawString(message, x, y); } public Dimension getPreferredSize(){ return new Dimension(200,50); } public Dimension getMinimumSize(){ return new Dimension(200,50); } }