Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: GUI и Java FX приложения > TextComponent


Автор: belarusrulez 30.6.2009, 20:17
каким образом можно менять в любом из всех текстовых компонентов цвет фона выделенного текста и сам цвет текста
желательно с примером smile
премного благодарен smile

Автор: dorogoyIV 1.7.2009, 03:18
как то так:
Код

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class ColorText extends JFrame
                       implements ActionListener
{
 JColorChooser chooser = new JColorChooser();
 JTextPane jtp = new JTextPane();
 Color c = Color.BLACK;
 JButton f = new JButton("Foreground");
 JButton b = new JButton("Background");

 public ColorText()
 {
  JToolBar tb = new JToolBar();
  tb.add(f);
  tb.add(b);
  add(tb, "North");

  add(new JScrollPane(jtp));

  f.addActionListener(this);
  b.addActionListener(this);

  f.setFocusable(false);
  b.setFocusable(false);
 }

 public void actionPerformed(ActionEvent e)
 {
  Color color = chooser.showDialog(jtp, "", c);

  if(color != null)
   c = color;

  SimpleAttributeSet sas = new SimpleAttributeSet();

  if(e.getSource().equals(f))
  {
   StyleConstants.setForeground(sas, c);
   StyleConstants.setBackground(sas,
     StyleConstants.getBackground(jtp.getCharacterAttributes()));
  }
  else
  {
   StyleConstants.setBackground(sas, c);
   StyleConstants.setForeground(sas,
     StyleConstants.getForeground(jtp.getCharacterAttributes()));
  }

  jtp.setCharacterAttributes(sas, true);
 }

 public static void main(String [] args)
 {
  JFrame f = new ColorText();
  f.setBounds(100, 100, 400, 300);
  f.setDefaultCloseOperation(3);
  f.setVisible(true);
 }
}

Автор: belarusrulez 1.7.2009, 09:28
замечательно, спасибо smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)