java怎么在panel面板里添加文字 20
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
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);
AffineTransform affineTransform = AffineTransform.getTranslateInstance(120,120);
affineTransform.rotate(60);
g2.setTransform(affineTransform);
g2.setColor(Color.BLACK);
g2.fillRect(0,0, rectangeSize.width, rectangeSize.height);
g2.setColor(color);
g2.drawString("我就这么写字符串!",0,0);
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;
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询