Java 为什么ActionListener不工作?

Java 为什么ActionListener不工作?,java,swing,Java,Swing,我一直在尝试做这件事,它确实起了作用,只是当我点击按钮时什么也没发生,这是为了一个大学项目 我所需要知道的就是如何使按钮按预期工作,使我的功能编码它做 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the

我一直在尝试做这件事,它确实起了作用,只是当我点击按钮时什么也没发生,这是为了一个大学项目

我所需要知道的就是如何使按钮按预期工作,使我的功能编码它做

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package proyecto;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;



/**
 *
 * @author Cristian
 */
public class Diseños extends JComponent implements ActionListener {

   JButton Boton1, Boton2, Boton3, Boton4, Boton5, Boton6, Boton7;





  @Override
  public void paint(Graphics g) {    


    this.Boton1=new JButton("-"); 
    this.Boton1.setBounds(90, 410, 30, 30); 
    this.Boton1.setBackground(Color.black);
    Component agregar1 = add(Boton1);



    this.Boton2=new JButton("-"); 
    this.Boton2.setBounds(150, 410, 30, 30); 
    this.Boton2.setBackground(Color.BLACK);
    Component agregar2 = add(Boton2);

    this.Boton3 =new JButton("-"); 
    this.Boton3.setBounds(210, 410, 30, 30); 
    this.Boton3.setBackground(Color.BLACK);
    Component agregar3 = add(Boton3);

    this.Boton4=new JButton("-"); 
    this.Boton4.setBounds(270, 410, 30, 30); 
    this.Boton4.setBackground(Color.BLACK);
    Component agregar4 = add(Boton4);

    this.Boton5=new JButton("-"); 
    this.Boton5.setBounds(330, 410, 30, 30); 
    this.Boton5.setBackground(Color.BLACK);
    Component agregar5 = add(Boton5);

    this.Boton6=new JButton("-"); 
    this.Boton6.setBounds(390, 410, 30, 30); 
    this.Boton6.setBackground(Color.BLACK);
    Component agregar6 = add(Boton6);

    this.Boton7=new JButton("-"); 
    this.Boton7.setBounds(450, 410, 30, 30); 
    this.Boton7.setBackground(Color.BLACK);
    Component agregar7 = add(Boton7);

    g.drawRect (570, 10, 300, 200);
    g.setColor(Color.BLACK);
    g.fillRect(570, 10, 300, 200);
    g.drawRect (570, 250, 300, 200);
    g.setColor(Color.BLACK);
    g.fillRect(570, 250, 300, 200);
    g.setColor(Color.WHITE);
    Font oldFont=getFont();
    Font fuente=new Font("Primer Jugador", Font.BOLD, 14);
    g.setFont(fuente);
    g.drawString("Primer Jugador", 580, 30);
    Font titulo=new Font("Segundo Jugador", Font.BOLD, 14);
    g.setFont(titulo);
    g.drawString("Segundo Jugador", 580, 270);
    g.drawString("[ " + Proyecto.primernombre + " ]", 580, 50);
    g.drawString("[ " + Proyecto.segundonombre + " ]", 580, 290);
    g.setColor(Color.red);
    g.fillRoundRect(10, 5, 550, 450, 50, 50);
    g.setColor(Color.WHITE);
    g.fillOval(80, 50, 50, 50);
    g.fillOval(140, 50, 50, 50);
    g.fillOval(200, 50, 50, 50);
    g.fillOval(260, 50, 50, 50);
    g.fillOval(320, 50, 50, 50);
    g.fillOval(380, 50, 50, 50);
    g.fillOval(440, 50, 50, 50);
    g.fillOval(80, 110, 50, 50);
    g.fillOval(140, 110, 50, 50);
    g.fillOval(200, 110, 50, 50);
    g.fillOval(260, 110, 50, 50);
    g.fillOval(320, 110, 50, 50);
    g.fillOval(380, 110, 50, 50);
    g.fillOval(440, 110, 50, 50);
    g.fillOval(80, 170, 50, 50);
    g.fillOval(140, 170, 50, 50);
    g.fillOval(200, 170, 50, 50);
    g.fillOval(260, 170, 50, 50);
    g.fillOval(320, 170, 50, 50);
    g.fillOval(380, 170, 50, 50);
    g.fillOval(440, 170, 50, 50);
    g.fillOval(80, 230, 50, 50);
    g.fillOval(140, 230, 50, 50);
    g.fillOval(200, 230, 50, 50);
    g.fillOval(260, 230, 50, 50);
    g.fillOval(320, 230, 50, 50);
    g.fillOval(380, 230, 50, 50);
    g.fillOval(440, 230, 50, 50);
    g.fillOval(80, 290, 50, 50);
    g.fillOval(140, 290, 50, 50);
    g.fillOval(200, 290, 50, 50);
    g.fillOval(260, 290, 50, 50);
    g.fillOval(320, 290, 50, 50);
    g.fillOval(380, 290, 50, 50);
    g.fillOval(440, 290, 50, 50);
    g.fillOval(80, 350, 50, 50);
    g.fillOval(140, 350, 50, 50);
    g.fillOval(200, 350, 50, 50);
    g.fillOval(260, 350, 50, 50);
    g.fillOval(320, 350, 50, 50);
    g.fillOval(380, 350, 50, 50);
    g.fillOval(440, 350, 50, 50);
}

    @Override
     public void actionPerformed (ActionEvent ae){       
        if(ae.getSource().equals(Boton1) && turno.Tjugador == true && colores.colorjugador[0] == 1 && matrices.matrizraya[0] == 6) {
            System.out.println("I doubt this is even working");
            turno.Tjugador = false;
            matrices.matrizraya[0] --;           
            getGraphics().setColor(Color.RED);
            getGraphics().fillOval(80, 350, 50, 50);
            repaint();
        }

    }
}
编辑:我一直在重新测试代码,但只有当我不使用if时,代码才起作用,这是为什么

编辑:好的,我解决了按钮问题,但我得到了一个新的,当我尝试更改Boton61的背景色时,我得到了以下错误:

线程“AWT-EventQueue-0”java.lang.NullPointerException中出现异常 在proyecto.Diseños.actionPerformed(Diseños.java:364)


您需要执行
Boton3.addActionListener(new Disenos())

您需要执行
Boton3.addActionListener(new Disenos())

您需要执行
Boton3.addActionListener(new Disenos())

您需要执行
Boton3.addActionListener(new Disenos())

建议:

  • 将ActionListener添加到按钮。这里的意思是
    Boton3.addActionListener(this)
  • 您不应该以任何绘制方法创建组件或将其添加到GUI中。油漆或油漆组件等油漆方法只能用于油漆和油漆。
    • 您无法直接控制何时调用绘制方法,甚至无法控制是否调用绘制方法,也无法控制调用的次数,因此,在更改GUI组件时使用绘制方法非常危险
    • 任何减慢绘制速度的操作都会使GUI的响应性变差,这是用户无法欣赏的。出于这个原因,绘画方法应该力求精简和快速,同样也应该只涉及绘画
  • 您不希望重写JComponent的paint方法,而是希望重写其paintComponent方法
  • 不要对组件调用
    getGraphics()
    ,也不要尝试使用由此获得的图形对象进行绘制。这样做会给您一个短暂的图形对象,这将使您的绘图不稳定。而是使用JVM提供给您的图形对象,在paintComponent方法中绘制所有图形
  • 您可以通过在BuffereImage上调用
    getGraphics()
    并在其中绘制来绕过上述限制,但仍然需要通过
    g.drawImage(…)
    方法在paintComponent方法中绘制BuffereImage
  • 我自己也会做一些不同的事情,包括创建一个JPanel,它使用一个GridLayout来保存带有圆形图像图标的JLabel,底部是一个JButton。然后,当按下按钮时,我会交换JLabel中需要交换的图像图标。这将更容易维护和增强,因为没有硬编码的位置

例如,您甚至可以取消列JButtons,而是使用一个JLabel网格,给它们一个鼠标侦听器,检查JLabel所在的列,然后根据按下的列添加一个彩色磁盘:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class Connect4Panel extends JPanel {
   public static final int ROWS = 6;
   public static final int COLUMNS = 7;
   public static final int DISK_WIDTH = 50;
   public static final int DISK_BORDER_WIDTH = 5;
   private static final Color FIRST_COLOR = Color.red;
   private static final Color SECOND_COLOR = Color.black;
   private Icon emptyIcon;
   private Icon firstIcon;
   private Icon secondIcon;
   private JLabel[][] diskGrid = new JLabel[ROWS][COLUMNS];
   private boolean firstTurn = true;

   public Connect4Panel() {
      emptyIcon = createIcons(new Color(0, 0, 0, 15));
      firstIcon = createIcons(FIRST_COLOR);
      secondIcon = createIcons(SECOND_COLOR);

      DiskListener diskListener = new DiskListener();
      // setBackground(Color.DARK_GRAY);
      setLayout(new GridLayout(ROWS, COLUMNS, 2, 0));
      for (int row = 0; row < diskGrid.length; row++) {
         for (int col = 0; col < diskGrid[row].length; col++) {
            JLabel disk = new JLabel(emptyIcon);
            disk.addMouseListener(diskListener);
            diskGrid[row][col] = disk;
            add(disk);
         }
      }
   }

   private Icon createIcons(Color color) {
      int width = DISK_WIDTH + 2 * DISK_BORDER_WIDTH;
      BufferedImage bImg = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = bImg.createGraphics();
      g2.setColor(color);
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      int x = DISK_BORDER_WIDTH;
      int oWidth = DISK_WIDTH;
      g2.fillOval(x, x, oWidth, oWidth);
      g2.dispose();
      return new ImageIcon(bImg);
   }

   private class DiskListener extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent e) {
         JLabel disk = (JLabel) e.getSource();
         int selectedColumn = -1;
         for (int row = 0; row < diskGrid.length; row++) {
            for (int col = 0; col < diskGrid[row].length; col++) {
               if (disk == diskGrid[row][col]) {
                  selectedColumn = col;
               }
            }
         }

         for (int row = ROWS - 1; row >= 0; row--) {
            if (diskGrid[row][selectedColumn].getIcon() == emptyIcon) {
               Icon icon = firstTurn ? firstIcon : secondIcon;
               diskGrid[row][selectedColumn].setIcon(icon);
               firstTurn = !firstTurn;
               break;
            }
         }

         // TODO check for win
      }
   }

   private static void createAndShowGui() {
      Connect4Panel mainPanel = new Connect4Panel();

      JFrame frame = new JFrame("Connect 4 Panel");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);

      JOptionPane.showMessageDialog(frame, "Click on panel to see how it works!");
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
导入java.awt.Color;
导入java.awt.Graphics2D;
导入java.awt.GridLayout;
导入java.awt.RenderingHints;
导入java.awt.event.*;
导入java.awt.image.buffereImage;
导入javax.swing.*;
@抑制警告(“串行”)
公共类Connect4Panel扩展了JPanel{
公共静态最终整数行=6;
公共静态final int COLUMNS=7;
公共静态最终整型磁盘\u宽度=50;
公共静态最终整型磁盘\u边框\u宽度=5;
私有静态最终颜色FIRST_Color=Color.red;
私有静态最终颜色SECOND_Color=Color.black;
私人图标emptyIcon;
私人图标第一图标;
私人图标;
私有JLabel[]diskGrid=新JLabel[行][列];
私有布尔值firstTurn=true;
公共连接4panel(){
emptyIcon=createIcons(新颜色(0,0,0,15));
firstIcon=创建图标(第一种颜色);
secondIcon=createIcons(第二种颜色);
DiskListener DiskListener=新的DiskListener();
//挫折背景(颜色:深灰色);
setLayout(新的GridLayout(行、列、2、0));
for(int row=0;row=0;行--){
如果(diskGrid[row][selectedColumn].getIcon()==emptyIcon){
图标图标=第一圈?第一个图标:第二个图标;
diskGrid[row][selectedColumn].setIcon(图标);
firstTurn=!firstTurn;
打破
}
}
//TODO检查是否获胜
}
}
私有静态void createAndShowGui(){
Connect4Panel主面板=新的Connect4Panel();
JFrame=新JFrame(“连接4
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class Connect4Panel extends JPanel {
   public static final int ROWS = 6;
   public static final int COLUMNS = 7;
   public static final int DISK_WIDTH = 50;
   public static final int DISK_BORDER_WIDTH = 5;
   private static final Color FIRST_COLOR = Color.red;
   private static final Color SECOND_COLOR = Color.black;
   private Icon emptyIcon;
   private Icon firstIcon;
   private Icon secondIcon;
   private JLabel[][] diskGrid = new JLabel[ROWS][COLUMNS];
   private boolean firstTurn = true;

   public Connect4Panel() {
      emptyIcon = createIcons(new Color(0, 0, 0, 15));
      firstIcon = createIcons(FIRST_COLOR);
      secondIcon = createIcons(SECOND_COLOR);

      DiskListener diskListener = new DiskListener();
      // setBackground(Color.DARK_GRAY);
      setLayout(new GridLayout(ROWS, COLUMNS, 2, 0));
      for (int row = 0; row < diskGrid.length; row++) {
         for (int col = 0; col < diskGrid[row].length; col++) {
            JLabel disk = new JLabel(emptyIcon);
            disk.addMouseListener(diskListener);
            diskGrid[row][col] = disk;
            add(disk);
         }
      }
   }

   private Icon createIcons(Color color) {
      int width = DISK_WIDTH + 2 * DISK_BORDER_WIDTH;
      BufferedImage bImg = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = bImg.createGraphics();
      g2.setColor(color);
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      int x = DISK_BORDER_WIDTH;
      int oWidth = DISK_WIDTH;
      g2.fillOval(x, x, oWidth, oWidth);
      g2.dispose();
      return new ImageIcon(bImg);
   }

   private class DiskListener extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent e) {
         JLabel disk = (JLabel) e.getSource();
         int selectedColumn = -1;
         for (int row = 0; row < diskGrid.length; row++) {
            for (int col = 0; col < diskGrid[row].length; col++) {
               if (disk == diskGrid[row][col]) {
                  selectedColumn = col;
               }
            }
         }

         for (int row = ROWS - 1; row >= 0; row--) {
            if (diskGrid[row][selectedColumn].getIcon() == emptyIcon) {
               Icon icon = firstTurn ? firstIcon : secondIcon;
               diskGrid[row][selectedColumn].setIcon(icon);
               firstTurn = !firstTurn;
               break;
            }
         }

         // TODO check for win
      }
   }

   private static void createAndShowGui() {
      Connect4Panel mainPanel = new Connect4Panel();

      JFrame frame = new JFrame("Connect 4 Panel");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);

      JOptionPane.showMessageDialog(frame, "Click on panel to see how it works!");
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}