我正在制作一个程序,您可以使用 JButtons 选择选择排序或合并排序,并使用 Graphics 以条形图的形式对 int 数组进行排序,其中数组中的每个元素都是一个条形。
但由于某种原因,编译器没有收到我的按钮按下操作,我尝试使用
if 语句中的 (selection.equals(e.getSource())
但它不起作用,我是否遗漏了一些明显的东西?
public class Animation extends Canvas implements ActionListener{
JPanel panel;
JButton Selection;
JButton Merge;
boolean selection, merge;
int[] random = new int[25];
Sorter sort = new Sorter();
public Animation(){
Selection = new JButton("Selection sort");
Selection.addActionListener(this);
Selection.setActionCommand("select");
Merge = new JButton("Merge sort");
Merge.addActionListener(this);
Merge.setActionCommand("merge");
panel = new JPanel();
panel.add(Selection);
panel.add(Merge);
setBackground(Color.WHITE);
selection=false;
merge=false;
}
public void actionPerformed(ActionEvent e) {
if("select".equals(e.getActionCommand())){
selection = true;
repaint();
}
else if("merge".equals(e.getActionCommand())){
merge = true;
repaint();
}
}
public void paint (Graphics window){
Random r = new Random();
for(int i=0; i<random.length; i++){
int randomInt = r.nextInt(100) + 1;
random[i] = randomInt;
}
window.setColor(Color.MAGENTA);
if(selection==true){
for(int i=0; i< random.length-1; i++){
int smallest = i;
for(int j = i+1; j< random.length; j++){
if(random[j] < random[smallest])
smallest = j;
}
if( smallest != i) {
int least = random[smallest];
random[smallest] = random[i];
random[i] = least;
drawIt(random, window);
window.setColor(Color.WHITE);
drawIt(random, window);
window.setColor(Color.MAGENTA);
}
}
}
drawIt(random, window);
}
public void drawIt (int[] a, Graphics window1){
int x=128;
int height = 200;
for(int i=0; i<a.length; i++){
window1.drawLine(x, 200, x, height-a[i]);
window1.drawLine(x+1, 200, x+1, height-a[i]);
window1.drawLine(x+2, 200, x+2, height-a[i]);
x+=20;
}
try {
Thread.currentThread().sleep(100);
} catch(Exception ex) {
}
}
}
这是运行它的主类:
public class AnimationRunner extends JFrame{
private static final int WIDTH = 800;
private static final int HEIGHT = 250;
JButton Selection;
JButton Merge;
public AnimationRunner()
{
super("Sorting Animation");
setSize(WIDTH,HEIGHT);
Animation a = new Animation();
Merge = new JButton("Merge sort");
Selection = new JButton("Selection sort");
Merge.setSize(120, 30);
Selection.setSize(120,30);
Merge.setLocation(200, 30);
Selection.setLocation(400, 30);
this.add(Merge);
this.add(Selection);
((Component)a).setFocusable(true);
getContentPane().add(new Animation());
setVisible(true);
}
public static void main( String args[] )
{
AnimationRunner run = new AnimationRunner();
}
}
最佳答案
您为主类中的每个操作创建一个按钮,并将它们添加到 JFrame 中。您还创建了动画类的两个实例。您创建的一个,设置可聚焦然后不执行任何操作。然后创建另一个并将其添加到 JFrame 的 contentPane 中。
在动画构造函数中,您再次为每个操作创建一个按钮,这次设置操作命令。然后将它们添加到面板中。该面板从未添加到任何内容中,因此永远不会看到这些按钮。
您看到的按钮不是您为其定义操作命令的按钮。
此外,您应该避免使用 setSize()
和 Use Layout Managers定义组件的大小。
关于java - JButton 不适合我吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21742172/