通过按钮将矩形绘制到画布上
Posted
技术标签:
【中文标题】通过按钮将矩形绘制到画布上【英文标题】:Painting a Rectangle to a Canvas via Button 【发布时间】:2020-10-13 19:12:22 【问题描述】:这里有个小问题。我希望在单击按钮时在画布上绘制文本。我需要像 PaintEvent 这样的东西还是必须更新画布?如果我覆盖 DrawFrame.java 中的方法paint,我会打印出文本,但如果我单击按钮,我希望它发生。
我不允许使用 Swing、FX 或其他。仅 AWT。
这是我的两个课程:
import java.awt.*;
import java.awt.event.*;
public class DrawMain extends Frame
Panel pa1;
Button bu1;
Button bu2;
Button bu3;
public static void main(String[] args)
DrawMain dm = new DrawMain();
public DrawMain()
super("Draw Main");
setLocation(0, 8);
setSize(250, 300);
DrawFrame df = new DrawFrame();
bu1 = new Button("Draw");
bu2 = new Button("Clear");
bu3 = new Button("Exit");
bu1.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println(e.getActionCommand());
df.ca1 = new Canvas()
public void paint(Graphics g)
g.drawString("Sample Text", 10, 10);
;
df.ca1.repaint();
);
bu2.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println(e.getActionCommand());
);
bu3.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println(e.getActionCommand());
System.exit(0);
);
pa1 = new Panel();
pa1.setSize(this.getSize());
pa1.setLayout(new GridLayout(3, 1));
pa1.add(bu1);
pa1.add(bu2);
pa1.add(bu3);
add(pa1);
addWindowListener(
new WindowAdapter()
@Override
public void windowClosing (WindowEvent e)
System.exit(0);
);
setVisible(true);
import java.awt.*;
import java.awt.event.*;
public class DrawFrame extends Frame
Panel pa1;
Canvas ca1;
public DrawFrame()
super("Draw Frame");
setLocation(260, 8);
setSize(1000, 750);
ca1 = new Canvas();
ca1.setBackground(Color.GREEN);
ca1.setSize(this.getSize());
pa1 = new Panel();
pa1.setSize(this.getSize());
pa1.setLocation(this.getLocation());
pa1.add(ca1);
add(pa1);
addWindowListener(
new WindowAdapter()
@Override
public void windowClosing (WindowEvent e)
System.exit(0);
);
setVisible(true);
【问题讨论】:
【参考方案1】:我已经有十多年没有使用 AWT 了,但你可以试试这个。这是一种使用按钮绘制字符串的简单方法。
public class ButtonDraw extends Panel
Frame f = new Frame();
boolean draw = false;
public static void main(String[] args)
new ButtonDraw();
public ButtonDraw()
setPreferredSize(new Dimension(200, 200));
f.add(this);
f.addWindowListener(new MyWindowListener());
// center on screen
f.setLocationRelativeTo(null);
Button b = new Button("Draw");
add(b);
b.addActionListener(ae ->
draw = true;
repaint();
);
f.pack();
f.setVisible(true);
@Override
public void paint(Graphics g)
super.paint(g);
if (draw)
g.drawString("Drawing a String", 40, 100);
private class MyWindowListener extends WindowAdapter
@Override
public void windowClosing(WindowEvent we)
System.exit(0);
【讨论】:
以上是关于通过按钮将矩形绘制到画布上的主要内容,如果未能解决你的问题,请参考以下文章
如何通过按下和拖动在 Qt Quick/QML 画布中绘制一个矩形