用java画三角形import javax.swing.*; import java.awt.*; import java.awt.event.* 20
1个回答
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* 格子绘图演示
* @author hardneedl
*/
final class Trang extends JFrame{
private static final Dimension SIZE = new Dimension(600,400);
public Dimension getMinimumSize() {return SIZE;}
public Dimension getMaximumSize() {return SIZE;}
public Dimension getPreferredSize() {return SIZE;}
public String getTitle() {return "Trang";}
private JComponent canvas;
private Observable containerSizeObserval = new Observable(){
public void notifyObservers() {
setChanged();
super.notifyObservers();
}
public void notifyObservers(Object arg) {
setChanged();
super.notifyObservers(arg);
}
};
private Trang() throws HeadlessException {
super();
init();
addListeners();
doLay();
}
private void init() {
TranBrush brush = new TranBrush();
containerSizeObserval.addObserver(brush);
canvas = new MyCanvas() {
Brush getBrush() {
return brush;
}
};
}
private void doLay(){
getContentPane().add(canvas, BorderLayout.CENTER);
pack();
setVisible(true);
}
private void addListeners(){
//通知画笔重绘
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
super.componentResized(e);
containerSizeObserval.notifyObservers(e.getComponent().getSize());
}
});
}
public static void main(String... args) {
SwingUtilities.invokeLater(Trang::new);
}
abstract private static class MyCanvas extends JComponent {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
getBrush().paint(g);
}
abstract Brush getBrush();
}
/**
* 画笔
*/
private interface Brush {
void paint(Graphics g);
}
private static class TranBrush implements Brush, Observer {
private Dimension rectangeSize = new Dimension();
private Color color = Color.YELLOW;
private Polygon polygon = new Polygon(new int[]{12,80,55}, new int[]{20,20,124},3);
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.BLACK);
g2.fillRect(0,0, rectangeSize.width, rectangeSize.height);
g2.setColor(color);
g2.draw(polygon);
}
public void update(Observable o, Object arg) {
if (arg instanceof Dimension) {
rectangeSize.setSize((Dimension) arg);
}
if (arg instanceof Color) {
color = (Color) arg;
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询