import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RecJFrame extends JFrame implements ActionListener,ComponentListener {
private JRadioButton colorsbutton[]; //單選按鈕組
private RecNCanvas canvas; //自定義畫布組件
public RecJFrame()
{
super("圖畫—顏色"); //框架邊布局
Dimension dim=getToolkit().getScreenSize(); //獲得屏幕分辨率
this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2); //窗口居中
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addComponentListener(this); //注冊組件事件監聽器
JToolBar toolbar=new JToolBar(); //創建工具欄,默認水平方向
this.getContentPane().add(toolbar,"North"); //工具欄添加到框架內容窗格北部
JButton button_color = new JButton("選擇顏色");
toolbar.add(button_color);
button_color.addActionListener(this);
String colors[]={"紅","黃","藍"};
ButtonGroup bgroup = new ButtonGroup(); //按鈕組
colorsbutton = new JRadioButton[colors.length]; //單選按鈕數組
for (int i=0; i<colorsbutton.length; i++)
{
colorsbutton[i]=new JRadioButton(colors[i]); //單選按鈕
colorsbutton[i].addActionListener(this);
bgroup.add(colorsbutton[i]); //單選按鈕添加到按鈕組
toolbar.add(colorsbutton[i]); //單選按鈕添加到工具欄
}
canvas = new RecNCanvas(); //創建自定義畫布組件
this.getContentPane().add(canvas,"Center");
this.setVisible(true); //創建自定義畫布組件this.getBackground()Color.yellow
}
public void actionPerformed(ActionEvent e) //按鈕動作事件處理方法
{
if(e.getActionCommand().equals("紅"))
{
canvas.setColor(Color.red);
}
if(e.getActionCommand().equals("藍"))
{
canvas.setColor(Color.blue);
}
if(e.getActionCommand().equals("黃"))
{
canvas.setColor(Color.yellow);
}
if (e.getActionCommand().equals("選擇顏色"))
{
Color c=JColorChooser.showDialog(this,"選擇顏色",Color.blue); //彈出JColorChooser顏色選擇對話框,返回選中顏色
canvas.setColor(c);
}
}
public void componentHidden(ComponentEvent arg0) {}
public void componentMoved(ComponentEvent arg0) {}
public void componentResized(ComponentEvent arg0) {}
public void componentShown(ComponentEvent arg0) {}
public static void main(String arg[])
{
new RecJFrame();
}
}
class RecNCanvas extends Canvas
{
private Color color;
public void setColor(Color color)
{
this.color=color;
}
public void paint(Graphics g)
{
int x0=this.getWidth()/4;
int y0=this.getHeight()/4;
g.setColor(this.color);
g.drawRect(x0,y0,250,100);
}
}
沒有repaint
再設置顏色後repaint
public void actionPerformed(ActionEvent e) //按鈕動作事件處理方法
{
if(e.getActionCommand().equals("紅"))
{
canvas.setColor(Color.red);
}
if(e.getActionCommand().equals("藍"))
{
canvas.setColor(Color.blue);
}
if(e.getActionCommand().equals("黃"))
{
canvas.setColor(Color.yellow);
}
if (e.getActionCommand().equals("選擇顏色"))
{
Color c=JColorChooser.showDialog(this,"選擇顏色",Color.blue); //彈出JColorChooser顏色選擇對話框,返回選中顏色
canvas.setColor(c);
}
canvas.repaint();//需要在這裡加上repaint,
}