我不确定java图形如何工作。它似乎
自己执行某件事,所以我试图打破它
下。
我正在尝试创建空白的JPanel,然后只绘制到它
一旦单击了JButton,但它不起作用
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class testGui {
// global ======================================================================
static gui gc_gui;
// main ========================================================================
public static void main(String[] args) {
gc_gui = new gui();
gc_gui.cv_frame.setVisible(true);
listeners();
}
// action listeners ============================================================
public static void listeners() {
ActionListener ll_square = new ActionListener() {
public void actionPerformed(ActionEvent event) {
gc_gui.cv_content.draw(graphic);
}
};
gc_gui.cv_button.addActionListener(ll_square);
}
// gui =========================================================================
public static class gui {
JFrame cv_frame;
JButton cv_button;
content cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_button = new JButton("Square");
cv_content = new content();
cv_content.setBackground(Color.BLACK);
cv_content.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_button);
cv_frame.add(cv_content);
}
}
// content =====================================================================
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
}
public void update() {
super.repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(Color.RED);
graphic2D.fillRect(10, 10, 100, 100);
}
}
}
我创建了内容JPanel而没有绘制功能
调用,然后尝试使用ActionListener调用它
尽管由于图形变量而崩溃。
使用Java图形实用程序的正确方法是什么?
更新
也许我不是在问这个问题,但是有可能
创建一个空白图像。
然后在按钮之后绘制其他图像到该图像(正方形)
被点击了吗?
不仅使用全局变量更新尺寸,还生成
新图像到现有图像
最佳答案
但是可以创建空白图像。然后在单击按钮后在该图像(正方形)上绘制其他图像?
查看Custom Painting Approaches中两种常见的绘画方法。
该示例允许您使用鼠标绘制矩形。在您的情况下,逻辑将更简单,因为单击按钮时仅调用addRectangle(...)
方法即可。当然,您需要以某种方式设置矩形的大小/位置。