gpt4 book ai didi

java - 绘图到按钮单击

转载 作者:行者123 更新时间:2023-11-30 04:56:48 24 4
gpt4 key购买 nike

我有一个问题,我花了几个小时试图解决,如果您能帮助我,我会很高兴。我的程序是一种带有 Swing GUI 的图形绘制程序。我有一个用于绘图的 Draw2 类,覆盖了 PaintComponent。 GUI 有一个控制类。控件和绘图窗口是单独的 JFrames。我想做的是在单击按钮时进行绘制,但我在对象之间的通信方面遇到了问题。我尝试在 PaintComponent 方法中使用 if 条件来实现绘制按钮单击,如果 boolean 值为 true,则该方法应该绘制,如果不是,则不应绘制。我将在按钮的 Action 监听器中将 boolean 值更改为 true 并重新绘制窗口。如何在 DrawAction 方法中访问 Draw2 的实例?抱歉,如果我的问题很愚蠢,但我刚刚开始学习 Java。 (我在这里看到了类似的主题,但我并没有真正理解那里的答案)所以我的代码的相关部分:

public class Draw2 extends JPanel{
boolean toDraw;

public void paintComponent (Graphics g) {
super.paintComponent(g);
if (toDraw == true){
//Draw Graph
}
}

}

public class Control extends JPanel{
private JButton jButton1;
private JButton jButton2;

void createControl(){
JButton1 = new JButton("Draw");
jButton1.addActionListener(new DrawAction());

//Other JTextfields, JComboBoxes, etc. with groupLayout
}

//inner class:
public class DrawAction implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
//How should I change toDraw in the instance of Draw2
//repaint the "canvas"
}
}

}

public static void main(String[] args){

JFrame frame = new JFrame("Control");
JFrame frame2 = new JFrame("Draw");


Draw2 gp = new Draw2();
control cont = new control();
cont.createControl(frame);



gp.setPreferredSize(new Dimension(0,0));

//Control Frame
frame.setSize(800,330);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(cont, BorderLayout.NORTH);
frame.setVisible(true);

//Drawing Frame
frame2.setSize(800,600);
frame2.setLocation(0, 330);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame2.add(gp);
frame2.setVisible(true);
}

提前致谢

最佳答案

我将扩展createControl(frame),因此它也将Draw2作为参数:

createControl(frame, gp)

这个新的builder方法将在您的Control类中设置Draw2的实例。

public class Control extends JPanel
{
private JButton jButton1;
private JButton jButton2;
private Draw2 draw;

关于java - 绘图到按钮单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com