[英]simple GUI program
我刚创建了一个在面板上添加按钮的程序,但是我无法继续使用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)
{
}
}
}
您必须将ActionListener添加到按钮,如下所示:
button.addActionListener(new MyCoolActionListener());
您也可以在声明ActionListener时定义它,但这是一般的想法。 您想在构造函数中声明JButton
之后立即添加ActionListener。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.