Zmiana koloru tla i tekstu

0

Witam pisze prosty notatnik w Javie juz wiekszosc mam za soba ale teraz utknełem na
zmianie koloru tła i tekstu (w programie mam klase rysujaca tak ze na menu mam obok wyboru koloru np kwadracik z danym kolorem)
wrzucam oczywiscie tylko istotne fragmenty kodu

public class Notepad extends JFrame implements ActionListener {

private Icon[] icons = { new IconA(Color.blue), new IconA(Color.yellow),new IconA(Color.orange)}
			  //elementy klasy rysujacej kolorowe kwadraciki

Notepad() {
					
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);		
                                                               
		List<JMenuItem> colors2 = createMenuColors(" Blue", "Yellow","Orange", );   background
		List<JMenuItem> colors2 = createMenuColors(" Blue", "Yellow","Orange", );	 foreground	 

                       for (JMenuItem mi : colors) {
			
                                  mi.addActionListener(this);
		           foreground.add(mi);
		}
		for (JMenuItem m : colors2) {
			                                     //petle tworzace samo menu
			m.addActionListener(this);  //wyglada to tak np ze mamy options->background>wyborkoloru		
			background.add(m);
                     }

                      options.add(foreground);
	           options.add(background);


                     public void actionPerformed(ActionEvent e) {
                       **//Tu powinnna byc obsluga  actionListnera **
                       }


private List<JMenuItem> createMenuColors(String... items) {
		List<JMenuItem> list = new ArrayList<JMenuItem>();
		int x = 0;
		for (String s : items) {
			JMenuItem a = new JMenuItem(s, icons[x]);
			a.addActionListener(this);
			
			list.add(a);
			x++;
		}                //to metoda tworzaca menu+kolorowy kwadracik 
		return list;

Macie moze jakies pomysly jak napisac obsluge ActionListnera
Pewnie jest to wmiare proste ale chyba juz za dlugo siedze nad tym programem
z gory dzieki za wszelkie rady.

0

Prezent niedzielny, wygrzebałem na dysku kolorowy edytor z czasów nauki Swinga.

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

public class BarwnyEdytorek extends JFrame implements ActionListener
{
    private JTextArea ta=new JTextArea(15,40);
    //------------------------
    public static void main(String args[])
    {
        new BarwnyEdytorek();
    }
    //------------------------
    public BarwnyEdytorek()
    {
        super("Barwny edytor");
        ta.setFont(new Font("Verdana",Font.PLAIN,13));
        ta.requestFocus();

        JPanel przyciski=new JPanel();
        przyciski.setLayout(new GridLayout(0,1,5,5));
        JButton b=new JButton("Kolor tła");
        b.addActionListener(this);
        b.setActionCommand("Tło");
        przyciski.add(b);

        b=new JButton("Kolor pisma");
        b.addActionListener(this);
        b.setActionCommand("Tekst");
        przyciski.add(b);
		
        b=new JButton("Zamiana kolorów");
        b.addActionListener(this);
        b.setActionCommand("Change");
        przyciski.add(b);

        b=new JButton("Zwiększenie liter");
        b.addActionListener(this);
        b.setActionCommand("Up");
        przyciski.add(b);

        b=new JButton("Zmniejszenie liter");
        b.addActionListener(this);
        b.setActionCommand("Down");
        przyciski.add(b);

        add(przyciski,"West");
        JScrollPane sp=new JScrollPane(ta);
        add(sp,"Center");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
    //------------------------
    public void actionPerformed(ActionEvent ae)
    {
        String str=ae.getActionCommand();
        if (str.equals("Up"))
        {
            Font f=ta.getFont();
            ta.setFont(new Font(f.getName(),f.getStyle(),f.getSize()+1));
            return;
        }
        if (str.equals("Down"))
        {
            Font f=ta.getFont();
            ta.setFont(new Font(f.getName(),f.getStyle(),f.getSize()-1));
            return;
        }
        if (str.equals("Tekst"))
        {
            Color kolor=JColorChooser.showDialog(this,"Kolor tekstów",ta.getForeground());
            if (kolor!=null)
            {
                ta.setForeground(kolor);
            }
            return;
        }
        if (str.equals("Tło"))
        {
            Color kolor=JColorChooser.showDialog(this,"Kolor tła",ta.getBackground());
            if (kolor!=null)
            {
                ta.setBackground(kolor);
            }
            return;
        }
        if (str.equals("Change"))
        {
            Color temp=ta.getBackground();
            ta.setBackground(ta.getForeground());
            ta.setForeground(temp);
        }
    }
}
0

Dzieki to juz mi duzo rozjasnilao
Juz zmienia kolorki ale na razie na taki jak mu wrzuce w kodzie
ale jak zrobic aby zmienial na taki jak jest na przycisku

for (JMenuItem m : colors2) {
			m.setBorder(BorderFactory.createRaisedBevelBorder());
			
			m.setActionCommand("kolor");
			m.addActionListener(this);			
			background.add(m);}

 String str=e.getActionCommand();
		  if(str.equals("kolor"))   {
			  
	        textArea.setBackground(Color.green);  // jak zrobic aby tu byl konkretny kolor z przycisku :)
		  }
1

Stwórz HashMap<String,Color> kolory. Dla każdej pozycji menu (new JMenuItem("Orange",)) dodaj pozycje do kolory: kolory.put("Orange",Color.ORANGE);
W obsłudze zdarzeń: setBackground(kolory.get(getActionCommand()));

0

Sorki ze dalej zawracam gitare ale ale dzis mam jakis gorszy dzien chyba z java :)
HashMapy to cos nowego dla mnie i troch improwizuje :)
HashMap chyba ok dodalem do niej elementy tylko wywala mi bledy przy obsludze zdarzen
moglbys rzucuc fachowym okiem z gory dzieki

public class Notepad extends JFrame implements ActionListener {
 
private Icon[] icons = { new IconA(Color.blue), new IconA(Color.yellow),new IconA(Color.orange)}
                          
 HashMap<String,Color>kolory=new HashMap<String,Color>() ;  to jest moja HashMap 

Notepad() {
 
                JMenuBar menuBar = new JMenuBar();
                setJMenuBar(menuBar);                
 
                List<JMenuItem> colors2 = createMenuColors(" Blue", "Yellow","Orange", );   
                List<JMenuItem> colors2 = createMenuColors(" Blue", "Yellow","Orange", );  

              
                       kolory.put("Orange",Color.ORANGE); tu dodaje elementy do Hashmap
		kolory.put("Blue",Color.BLUE);
		kolory.put("Yellow",Color.YELLOW);


                       for (JMenuItem mi : colors) {
                           m.setActionCommand("kolor");
                           mi.addActionListener(this);
                           foreground.add(mi);
                }
                for (JMenuItem m : colors2) {
                        m.setActionCommand("kolor");                                    
                        m.addActionListener(this);                  
                        background.add(m);
                     }
 
                      options.add(foreground);
                   options.add(background);
 
 
                     String str=e.getActionCommand();
		  if(str.equals("kolor"))   {
	    textArea.setBackground(kolory.get(getActionCommand())); Zamieszałem sie juz strasznie z tym :)
                                                                                  //tu wywala mi blad ze nie widzi metody getActionComand()                     
                       }
  
private List<JMenuItem> createMenuColors(String... items) {
                List<JMenuItem> list = new ArrayList<JMenuItem>();
                int x = 0;
                for (String s : items) {
                        JMenuItem a = new JMenuItem(s, icons[x]);
                        a.addActionListener(this);
                       

                        list.add(a);
                        x++;
                }                
                return list;
1

W Twojej wersji wszystkie pozycje menu mają takie samo actionCommand (tzn. "kolor"). Zatem po actionCommand nie rozróżnisz w co kliknięto. Proponuję takie zmiany:

    private ArrayList<JMenuItem> createMenuColors(String co,String... items) //pierwszy argument co opisuje czy chodzi o tło czy o kolor tekstu
    {
                ArrayList<JMenuItem> list = new ArrayList<JMenuItem>();
                int x = 0; //nie wiem po co ta zmienna
                for (String s : items)
                {
                        JMenuItem a = new JMenuItem(s);
                        a.setActionCommand(co+" "+s);
                        a.addActionListener(this);


                        list.add(a);
                        x++;
                }
                return list;
    }
//wywołania tej funkcji
                ArrayList<JMenuItem> colors = createMenuColors("kolor"," Blue", "Yellow","Orange");
                ArrayList<JMenuItem> colors2 = createMenuColors("tło"," Blue", "Yellow","Orange");
//dodanie pozycji do menu
                for (JMenuItem mi : colors)
                {
                           foreground.add(mi);
                }
                for (JMenuItem m : colors2)
                {
                        background.add(m);
                }
//obsługa zdarzeń
  public void actionPerformed(ActionEvent e)
  {
                str=a.getActionCommand();
                if(str.startsWith("kolor"))  //str ma postać "kolor Blue" 
               {
                      String[] tokens=str.split(" "); //robi z str dwuelementową tablicę {"kolor","Blue"}
                      textArea.setForeground(kolory.get(tokens[1]));
               }
                if(str.startsWith("tło"))  //str ma postać "tło Blue" 
               {
                      String[] tokens=str.split(" "); //robi z str dwuelementową tablicę {"tło","Blue"}
                      textArea.setBackground(kolory.get(tokens[1]));
               }
0

Dzieki juz chyba ktorys raz z rzedu mi pomagasz z java :)
Jak jestes z trojmiasta zapraszam na piwo :)

Podobnie mozna chyba zrobic menu zmiany wielkosci czcionki?

1 użytkowników online, w tym zalogowanych: 0, gości: 1