我的代码如下它对我来说很好,但是我的教授说他正在收到一个错误,因为我的类中没有几个变量被声明为final.
Eclipse在我的机器上似乎没有这个问题,所以我不知道如何解决我看不到的错误.
@H_404_7@解决方法
我明白,一些变量需要在嵌套类中工作,但是我创建的变量似乎工作正常,最终还是没有.
import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Random; public class JColorFrame extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { JColorFrame frame = new JColorFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public JColorFrame() { setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); setBounds(100,100,522,339); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5,5,5)); contentPane.setLayout(new BorderLayout(0,0)); setContentPane(contentPane); JPanel panel = new JPanel(); contentPane.add(panel,BorderLayout.NORTH); JPanel panel_1 = new JPanel(); contentPane.add(panel_1,BorderLayout.WEST); JPanel panel_2 = new JPanel(); contentPane.add(panel_2,BorderLayout.EAST); JPanel panel_3 = new JPanel(); contentPane.add(panel_3,BorderLayout.SOUTH); Color[] color = new Color[8]; color[0] = Color.black; color[1] = Color.white; color[2] = Color.red; color[3] = Color.blue; color[4] = Color.green; color[5] = Color.yellow; color[6] = Color.magenta; color[7] = Color.orange; JButton btnChangeColor = new JButton("Change Color"); btnChangeColor.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Random random = new Random(); int random_1 = random.nextInt(4); switch (random_1) { case 0: int random_2 = random.nextInt(8); panel.setBackground(color[random_2]); break; case 1: random_2 = random.nextInt(8); panel_1.setBackground(color[random_2]); break; case 2: random_2 = random.nextInt(8); panel_2.setBackground(color[random_2]); break; case 3: random_2 = random.nextInt(8); panel_3.setBackground(color[random_2]); break; } } }); contentPane.add(btnChangeColor,BorderLayout.CENTER); } }