package com.demo1;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main(String[] args) {
TwoButtons gui = new TwoButtons();
gui.go();
}
public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change Label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("Change Circle");
colorButton.addActionListener(new ColorListener());
label = new JLabel("I'm a label");
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton); //把button加到frame的pane上
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton); //把button加到frame的pane上
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(300, 300); // 设定frame的大小
frame.setVisible(true); // 最后把frame显示出来
}
class LabelListener implements ActionListener{ //单一的类中做出不同的ActionListener
public void actionPerformed(ActionEvent e) {
label.setText("Ouch"); //内部可以存取label
}
}
class ColorListener implements ActionListener{ //单一的类中做出不同的ActionListener
public void actionPerformed(ActionEvent e) {
label.setText("12345");
// frame.repaint();//用户按下按钮时就要求frame重新绘制
}
}
}
运行结果:
点击结果
package com.demo1;
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel { //创建JPanel的子类
public void paintComponent(Graphics g){ //Graphics g 此方法,要由系统来调用
g.setColor(Color.orange); //把g想象成绘图装置,告诉它要用什么颜色画出什么形状
g.fillRect(20, 50, 100, 100);
}
public void paintComponent2(Graphics g){ //Graphics g 此方法,要由系统来调用
Image image = new ImageIcon("dog.jpg").getImage(); //dog.jpg图片文件名
g.drawImage(image, 3, 4, this); //此处坐标代表图案左上角的位置离panel的左方边缘3个像素,离顶端向下4个像素
}
}
关注公众号:工控技术之家,可留言提问相关问题,有需要可发送源代码