简体   繁体   English

如何使用ActionListener在画布中绘制形状?

[英]How to draw shape in canvas using ActionListener?

我有一个程序,该程序具有4个文本字段和一个绘制矩形的按钮,用于输入数字(x,y,x1,y1)和添加它们的按钮的文本字段(addO),我需要知道如何使用动作侦听器画布内使用paint()方法进行绘制

The question is open and vague and the answer depends greatly on missing implementation details... 问题是开放和模糊的,答案很大程度上取决于缺少的实施细节。

Essentially, getting a value from a JTextField is as simple as calling getText on an instance of the field... 本质上,从JTextField获取值就像在字段实例上调用getText一样简单...

private JTextField field;
//...
field = new JTextField(10);
add(field);
//...
String text = field.getText();

Converting the value to int would require you to use Integer.parseInt(text) . 将值转换为int会要求您使用Integer.parseInt(text) This will throw a NumberFormatException error if the value is not a integer value. 如果该值不是整数值,则将引发NumberFormatException错误。 Equally, you could just use a JSpinner instead. 同样,您可以只使用JSpinner

Using an ActionListener is a simply as attaching an instance of ActionListener to a JButton ... 使用ActionListener就像将ActionListener的实例附加到JButton ...

JButton doStuff = new JButton("Do Stuff");
doStuff.addActionListene(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        // See previous comments about extract the field values...
    }
});

Painting in Swing is normally achieved by overriding paintComponent of a component that extends from JComponent , normally something like JPanel for example. 在Swing中绘画通常是通过重写从JComponent扩展的组件的paintComponent来实现的,例如,通常类似于JPanel

In this method you would paint whatever it is you need to... 用这种方法,您可以画任何需要的东西...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(x1, y1, x2, y2);
}

For example. 例如。

See: 看到:

For more details 更多细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM