【发布时间】:2019-10-26 21:18:20
【问题描述】:
所以我先把我的两个类的代码放在这里。
SquareSimp.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SquareSimp
{
public static void main( String[] args )
{
FilledFrame frame = new FilledFrame();
frame.setVisible( true );
}
}
class FilledFrame extends JFrame
{
int size = 400;
public FilledFrame()
{
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butSmall.addActionListener(new ButtonHandler1(this, 200){
@Override
public void actionPerformed(ActionEvent actionEvent) {
size = 200;
panel.repaint();
}
});
butMedium.addActionListener(new ButtonHandler1(this, this.size){
@Override
public void actionPerformed(ActionEvent actionEvent) {
size = 300;
panel.repaint();
}
});
butLarge.addActionListener(new ButtonHandler1(this, this.size){
@Override
public void actionPerformed(ActionEvent actionEvent) {
size = 400;
panel.repaint();
}
});
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setSize( size+100, size+100 );
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Exercise 2.
//Anonymous implementations of listeners are very efficient when you do not need to pass parameters to the
// constructor of the implemented listener.
butMessage.addActionListener(new ActionListener()
// An anonymous function. Creates an actionListener that shows a dialog.
{
@Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "Hiiii");
}
});
}
}
class SquarePanel extends JPanel
{
FilledFrame theApp;
SquarePanel(FilledFrame app)
{
theApp = app;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(20, 20, theApp.size, theApp.size);
}
}
ButtonHandler1.java
package Lab2;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// This is a class whose object will handle the event.
public class ButtonHandler1 implements ActionListener{
private FilledFrame theApp;
private int theSize;
ButtonHandler1(FilledFrame app, int size){
theApp = app;
theSize = size;
}
public void actionPerformed(ActionEvent actionEvent) {
}
}
到目前为止,一切正常,这很棒。但是,作为要求,我被要求为每个类制作一个按钮处理程序。有人可以向我解释一下我的 buttonHandler 到底在做什么吗?我觉得与其制作匿名函数并覆盖 actionPerformed 事件,不如用更好的方法来完成它(在 buttonhandler 类中创建事件并根据按下的按钮从那里影响大小)。我不知道该怎么做,所以任何解释的帮助都会很棒!
非常感谢!
布兰登
【问题讨论】:
标签: java swing actionlistener actionevent