私の目的は、ペイントタイプのアプリケーションを作ることです。JPanelに追加されたJButtonにActionListenerを追加する方法は?
は ..ご提案いただきありがとうございますが、コードのエラーが依然としてあります。 NetBeans IDEのエラーで
:「クラスのメソッドaddActionListenerが所与のタイプに適用することはできないが」線button1.addActionListener(パネル)で起こります。
私はそれをActionListenerにキャストするために提案を使用しました。その行はbutton1.addActionListener((ActionListener)パネル)です。 それでも以下の「声明場合は、」エラーが発生します。あなたの助け
おかげで再びシンボル変数「Button1を」見つけることができません。 ここは変更されたコードです。私は変数名を変更し、コードを簡単にするためにアダプタクラスを使用しました。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class r extends JPanel
{
public int x1,x2,y1,y2;
public static double SWITCH;
public r()
{
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent m)
{
x1=m.getX();
y1=m.getY();
repaint();
}
public void mouseReleased(MouseEvent m)
{
x1=x2=y1=y2=0;
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent m)
{
x2=m.getX();
y2=m.getY();
repaint();
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(SWITCH == 2)
{
g.drawRect(x1, y1, x2, y2);
}
else if (SWITCH == 3)
{
g.drawOval(x1,y1,x2,y2);
}
else
{
g.drawString("qwe", x1, y1);
}
}
}
public class q extends JFrame implements ActionListener
{
public static void main(String[] args)
{
q window = new q();
window.setVisible(true);
window.setSize(1024, 800);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cont = window.getContentPane();
cont.setLayout(new GridLayout(2,2));
r panel = new r();
JPanel BPanel = new JPanel();
cont.add(panel);
cont.add(BPanel);
BPanel.setBackground(Color.blue);
JButton button1,button2;
button1 = new JButton("Rect");
button2 = new JButton("Oval");
BPanel.add(button1);
BPanel.add(button2);
button1.addActionListener((ActionListener) panel);
button2.addActionListener((ActionListener) panel);
}
public void actionPerformed(ActionEvent a)
{
Object obj;
obj=a.getSource();
if (obj== button1)
{
SWITCH = 2;
repaint();
}
else
{
SWITCH = 3;
repaint();
}
}
}
さらに、私はもっと意味のある変数とクラス名を使用するように勧めます。 「q」、「z1」、「r」などはかなり混乱しており、長期的には多くの問題を引き起こす可能性があります。 – Thomas