我正在尝试使用grid [x] [y] .setPressedBackgroundColor(getColor());设置背景但我收到此错误消息
error: cannot find symbol
grid[x][y].setPressedBackgroundColor(getColor());
^
symbol: method setPressedBackgroundColor(Color)
location: class JButton
1 error
Process completed.
以下是JButton的代码。 ButtonGrid
构造函数中抛出了错误:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ButtonGrid {
class MyButton extends JButton {
public Color hoverBackgroundColor;
public Color pressedBackgroundColor;
public MyButton() {
this(null);
}
public MyButton(String text) {
super("text");
super.setContentAreaFilled(false);
}
@Override
public void paintComponent(Graphics g) {
if (getModel().isPressed()) {
g.setColor(pressedBackgroundColor);
} else if (getModel().isRollover()) {
g.setColor(hoverBackgroundColor);
} else {
g.setColor(getBackground());
}
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
@Override
public void setContentAreaFilled(boolean b) {
}
public Color getHoverBackgroundColor() {
return hoverBackgroundColor;
}
public void setHoverBackgroundColor(Color hoverBackgroundColor) {
this.hoverBackgroundColor = hoverBackgroundColor;
}
public Color getPressedBackgroundColor() {
return pressedBackgroundColor;
}
public void setPressedBackgroundColor(Color pressedBackgroundColor) {
this.pressedBackgroundColor = pressedBackgroundColor;
}
}
JFrame frame=new JFrame(); //creates frame
JButton[][] grid; //names the grid
public ButtonGrid(int width, int length){
int count = 1; //counting variable
frame.setLayout(new GridLayout(width,length)); //sets the layout
grid=new JButton[width][length]; //sets the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton("( "+ count++ +" )"); //creates new button
grid[x][y].setForeground(getColor()); //sets text color
grid[x][y].setHorizontalTextPosition(SwingConstants.CENTER); //centers text
grid[x][y].setBorder(null); //removes border
grid[x][y].setBackground(getColor()); //sets color of jbutton
grid[x][y].setPressedBackgroundColor(getColor());
frame.add(grid[x][y]); //adds button to grid
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public Color getColor() {
int rval = (int)Math.floor(Math.random() * 256);
int gval = (int)Math.floor(Math.random() * 256);
int bval = (int)Math.floor(Math.random() * 256);
return new Color(rval, gval, bval);
}
public static void main(String[] args) {
new ButtonGrid(3,3);//makes new ButtonGrid with 2 parameters
}
}
答案 0 :(得分:2)
将JButton[][]
更改为MyButton[][]