java jframe添加按钮_java-向JFrame添加多个按钮,文本颜色不显示

我试图将10个按钮一个一个地添加到JPanel,然后将它们全部添加到JFrame.我需要有我的for循环,因为它必须易于更改按钮的数量.所有按钮还需要具有不同的颜色和文本(我知道它们可以使用下面的代码获得相同的颜色,但是现在还可以).

我从下面的代码中输出的只是一个带有10个白色按钮且没有文本/颜色的框架.为什么颜色,文本和动作侦听器未连接到我的按钮?

我读过其他问题,我必须注意关于frame.add(panel,frame.pack()和frame.setVisible(true)的位置,但我认为这些位置正确地位于我的forloop之外.尝试使用frame.setContentPane(panel),但这产生了相同的结果-一个带有10个白色按钮且没有文本/颜色的框架.

C主类:

public class CMain extends MyButton {

public static void main(String[] args) {

Random randomGenerator = new Random();

int numberofbuttons = 10;

JPanel panel = new JPanel();

JFrame frame = new JFrame("MyButton testing");

for (int i = 0; i < numberofbuttons; i++) {

float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();

String theText = "SWITCH ME BACK";

String theOtherText = "button nr: " + i;

Color theColor = new Color(r, g, b);

Color theOtherColor = new Color(r2, g2, b2);

MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);

panel.add(myb);

}

frame.add(panel);

frame.pack();

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

MyButton类:

public class MyButton extends JButton implements ActionListener {

private JButton button;

private Color col1;

private Color col2;

private String text1;

private String text2;

public MyButton(Color col1, Color col2, String text1, String text2) {

this.col1 = col1;

this.col2 = col2;

this.text1 = text1;

this.text2 = text2;

button = new JButton(text1);

button.setOpaque(true);

button.setBackground(col1);

button.addActionListener(this);

}

public MyButton() {

this(Color.blue, Color.red, "click = make red", "click = reset to blue");

}

public void ToggleState() {

Color initialBackground = button.getBackground();

if (initialBackground == col1) {

button.setBackground(col2);

button.setText(text2);

} else if (initialBackground == col2) {

button.setBackground(col1);

button.setText(text1);

}

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == button) {

this.ToggleState();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值