import javax.swing.*; import java.awt.event.*; import java.awt.*; class TouChaCol{ JFrame frame; JLabel label; public static void main(String [] args){ TouChaCol ch = new TouChaCol(); ch.go(); } class LabelActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ label.setText("fuck you click me"); } } class ColorActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ frame.repaint(); } } public void go(){ frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel panel = new Panel(); label = new JLabel("yoooyo helllo who are you"); JButton button1 = new JButton("change the color"); button1.addActionListener(new ColorActionListener()); JButton button2 = new JButton("change the label"); button2.addActionListener(new LabelActionListener()); frame.getContentPane().add(BorderLayout.SOUTH,button1); frame.getContentPane().add(BorderLayout.EAST,button2); frame.getContentPane().add(BorderLayout.WEST,label); frame.getContentPane().add(BorderLayout.CENTER,panel); frame.setSize(700, 700); frame.setVisible(true); } }
import javax.swing.*; import java.awt.*; public class Panel extends JPanel{ public void paintComponent(Graphics g){ g.fillRect(0, 0, this.getWidth(), this.getHeight()); int red = (int)(Math.random() * 255); int green = (int)(Math.random() * 255); int blue = (int)(Math.random() * 255); Color myColor = new Color(red,green,blue); g.setColor(myColor); g.fillOval(70,70, 100, 100); } }
在Panel(继承自JPanel)类中方法paintComponent()
fillRect(0,0,this.width,this.height)表示在该panel的(x,y)坐标为起始,this.width和this.height也表示该面板的宽高
需要作出改变的组件,放做全局
在go中有代码:
button1.addActionListener(new ColorActionListener());
button2.addActionListener(new LabelActionListener());
在外部类对象中新建的内部类对象会与该外部类对象产生联结,内部类对象可直接调用外部类对象的实例变量,也因此,需要改变的组件做实例变量也是为了给内部对象使用
BoarderLayout.CENTER 这个中间是相对于其他组件而言的,当其左边的组件变小时,他可能会变大