java简单GUI程序
我刚刚制作了这个程序,在我的面板上添加了一个按钮,但我无法继续使用actionListener使按钮工作。他们的图片应显示在面板上,当按钮单击时,图片应更改为其他图片。请帮帮我,谢谢!这是我的密码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawPanelThree extends JPanel
{
private JButton button;
public DrawPanelThree()
{
button = new JButton();
setLayout(new BorderLayout());
add(button, BorderLayout.SOUTH);
button.setText("Start");
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(90, 40, 100, 50);
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
g.fillRect(260, 10, 10, 10);
g.fillRect(10, 120, 10, 10);
g.fillRect(260, 120, 10, 10);
g.setColor(new Color(255, 215, 0));
g.fillOval(120, 45, 40, 40);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setTitle("Rectangle");
frame.setSize(new Dimension(300, 200));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawPanelThree panel = new DrawPanelThree();
frame.add(panel);
panel.setBackground(Color.CYAN);
frame.setVisible(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
}
}
}
# 1 楼答案
您必须将ActionListener添加到按钮,如下所示:
您也可以在声明ActionListener时定义它,但这只是一般的想法。您希望在构造函数中声明
JButton
之后立即添加ActionListener希望这有帮助