java frame 按钮变色_如何更改JFrame中的字体颜色

字体颜色由3个单选按钮选择。

当我按下按钮,然后makeStyleSheet函数做出一个CSS。

在这个CSS中,只定义了一种颜色。

但字体颜色没有改变....

为什么?

@SuppressWarnings("javadoc")

public class Sample extends JFrame {

JRadioButton[] radio;

JTextPane textPane;

HTMLEditorKit kit;

HTMLDocument doc;

JButton btnNewButton;

ButtonGroup group;

List list;

/**

* @param args

*/

public static void main(String[] args) {

Sample frame = new Sample();

ActionListener action = new MyButtonAction(frame.kit, frame.doc, frame.list);

frame.addAction(action);

frame.setVisible(true);

}

private void addAction(ActionListener action) {

btnNewButton.addActionListener(action);

}

@SuppressWarnings("javadoc")

public Sample() {

doc = new HTMLDocument();

textPane = new JTextPane();

kit = new HTMLEditorKit();

setBounds(100, 100, 450, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

getContentPane().setLayout(null);

textPane.setEditorKit(kit);

textPane.setDocument(doc);

textPane.setContentType("text/html");

textPane.setBounds(12, 13, 282, 229);

getContentPane().add(textPane);

btnNewButton = new JButton("HTML");

btnNewButton.setBounds(303, 211, 117, 31);

getContentPane().add(btnNewButton);

group = new ButtonGroup();

list = new ArrayList();

JRadioButton rdbtnRed = new JRadioButton("apple", true);

JRadioButton rdbtnYellow = new JRadioButton("banana");

JRadioButton rdbtnGreen = new JRadioButton("mellon");

list.add(rdbtnRed);

list.add(rdbtnYellow);

list.add(rdbtnGreen);

group.add(rdbtnRed);

group.add(rdbtnYellow);

group.add(rdbtnGreen);

rdbtnRed.setBounds(302, 161, 113, 21);

getContentPane().add(rdbtnRed);

rdbtnYellow.setBounds(302, 138, 113, 21);

getContentPane().add(rdbtnYellow);

rdbtnGreen.setBounds(302, 115, 113, 21);

getContentPane().add(rdbtnGreen);

}

}

class MyButtonAction implements ActionListener {

HTMLEditorKit kit;

HTMLDocument doc;

List list;

public MyButtonAction(HTMLEditorKit kit, HTMLDocument doc, List list) {

this.kit = kit;

this.doc = doc;

this.list = list;

}

@Override

public void actionPerformed(ActionEvent e) {

String tag = null;

for(JRadioButton btn : list) {

if (btn.isSelected()){

tag = btn.getText();

}

}

kit.setStyleSheet(makeStyleSheet(tag));

try {

kit.insertHTML(doc, doc.getLength(), "apple,banana,mellon", 0, 0, null);

} catch (IOException e1) {

e1.printStackTrace();

} catch (BadLocationException e1) {

e1.printStackTrace();

}

}

private StyleSheet makeStyleSheet(String tag) {

StyleSheet styleSheet = new StyleSheet();

styleSheet.addRule("." + tag + " {color: red;}");

return styleSheet;

}

}

+0

textPane.setForeground(Color.BLUE);应该工作 –

+1

不要使用setBounds()。 Swing旨在与布局经理一起使用。 –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值