Schreibprogramm nur markierten Text in kursiv oder fett schreiben

Feuersternmc

Mitglied
Also ich bin jetzt noch nicht so erfahren in Java. Ich programmiere grade ein Schreibprogramm.
Das habe ich bis jetzt:
Java:
package Schreibprogramm;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class main {
    ActionListener listener = new ActionListener()
    {
       public void actionPerformed(ActionEvent event)
       {
          int mode = 0;
          if (bold.isSelected()) mode += Font.BOLD;
          if (italic.isSelected()) mode += Font.ITALIC;
          textArea.setFont(new Font("Serif", mode, 13));
       }
    };
  JTextArea textArea;
  JButton save;
  JButton load;
  JCheckBox bold;
  JCheckBox italic;
  void initUI() {

    
    JFrame frame = new JFrame("Schreibprogramm");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textArea = new JTextArea(24, 80);
    save = new JButton("Speichern");
    save.addActionListener(e -> saveToFile());
    load = new JButton("Öffnen");
    load.addActionListener(e -> load());
    bold = new JCheckBox("<html><b>Fett</b></html>");
    bold.addActionListener(listener);
    italic = new JCheckBox("<html><i>Kursiv</i></html>");
    italic.addActionListener(listener);
  
    frame.add(new JScrollPane(textArea));
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(save);
    buttonPanel.add(load);
    buttonPanel.add(bold);
    buttonPanel.add(italic);
    frame.add(buttonPanel, BorderLayout.SOUTH);
    frame.setSize(500, 400);
    frame.setVisible(true);


  }
  protected void load() {
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(load);
   
          if (returnVal == JFileChooser.APPROVE_OPTION) {
              File file = fc.getSelectedFile();
              showText(file);
          }
    }
   
    private void showText(File file){
        StringBuffer buf = new StringBuffer();
        if(file.exists( )){
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String line = "";
                while((line = reader.readLine( )) != null){
                    buf.append(line+"\n");
                }
                reader.close( );
            }
            catch (FileNotFoundException e) {
                e.printStackTrace( );
            }
            catch (IOException e) {
                e.printStackTrace( );
            }
        }
        this.textArea.setText(buf.toString( ));
    }
   
    protected void save() {
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(save);
   
          if (returnVal == JFileChooser.APPROVE_OPTION) {
              File file = fc.getSelectedFile();
              saveText(file);
          }
    }
   
    private void saveText(File file) {
        try {
            FileWriter writer = new FileWriter(file);
            String text = this.textArea.getText( );
            writer.write(text);
            writer.flush( );
            writer.close( );
        }
        catch (IOException e) {
            e.printStackTrace( );
        }
    }
  
  
  protected void saveToFile() {
    JFileChooser fileChooser = new JFileChooser();
    int retval = fileChooser.showSaveDialog(save);
    if (retval == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();
      if (file == null) {
        return;
      }
      if (!file.getName().toLowerCase().endsWith(".nico")) {
        file = new File(file.getParentFile(), file.getName() + ".nico");
      }
      try {
        textArea.write(new OutputStreamWriter(new FileOutputStream(file),
            "utf-8"));
        Desktop.getDesktop().open(file);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    new test1().initUI();
  }
}
Nun ja, grade bin ich dabei Fett und Kursiv in mein Schreibprogramm zu "machen"(bzw. zu programmieren) Ich würde es aber gerne so machen, das nur der markierte Text fett bzw. kursiv zu schreiben. Wie mache ich das am besten?
 
Hallo.

Mit ein JTextArea ist es nicht möglich. Du solltest auf JEditorPane oder JTextPane verwenden.
Methode getSelectionStart und getSelectionEnd ist in dem Fall vom Interesse.

Grüße
 
Ich habe jetzt sehr viel gegoogelt, im Forum gesucht und programmiert und habe es auch geschafft. Nun ja aber dadurch funktioniert meine save und load Methode nicht mehr... Ich schätze es liegt daran, das ich jetzt einen JTextPane benutze
Ich habe 2 Klassen:
EditorComponent (Das ist die Main Klasse)
Java:
package Schreibprogramm;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.GraphicsEnvironment;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
public class EditorComponent extends JPanel implements ActionListener, ItemListener {
  private static final long serialVersionUID = 2232612551746729177L;
 
  private JTextPane pane = null;
  private EditorDocument doc = null;
  private JButton bold = null;
  private JButton italic = null;
 
  private JButton underline = null;
 
  private JButton foreground = null;
 
  private JButton background = null;
 
  private JButton pic = null;
 
  private JComboBox<String> fonts = null;

  private JComboBox<Integer> size = null;

  private JToolBar bar = null;

  private JFileChooser imch = null;
  public EditorComponent() {
    setLayout(new BorderLayout());

    this.doc = new EditorDocument();
    this.pane = new JTextPane(this.doc);

    this.bold = new JButton("<html><b>Fett</b><html>");
    this.italic = new JButton("<html><i>Kursiv</i></html>");
    this.underline = new JButton("<html><u>Untertrichen</u></html>");
    this.foreground = new JButton("<html><font color=\"red\">Schrift Farbe</font></html>");
    this.background = new JButton("<html><bg-color=\"red\">Hintergrund Farbe</bg-color></html>");
    this.pic = new JButton("Bild einfügen");
    this.fonts = new JComboBox<String>();
    this.size = new JComboBox<Integer>();
    this.bar = new JToolBar();
    this.imch = new JFileChooser();

    this.imch.setFileFilter(new FileFilter() {
      public boolean accept(File f) {
        if (f.isDirectory()) {
          return true;
        }
        if (f.getAbsolutePath().toLowerCase().endsWith(".png")) {
          return true;
        }
        if (f.getAbsolutePath().toLowerCase().endsWith(".jpg")) {
          return true;
        }
        return f.getAbsolutePath().toLowerCase().endsWith(".jpeg");
      }
      public String getDescription() {
        return "Image (*.jpg, *.jpeg, *.png)";
      }
    });
   
    for (int i = 8; i < 52; i += 2) {
      this.size.addItem(i);
    }
  
    String[] font = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    for (int i = 0; i < font.length; i++) {
      this.fonts.addItem(font[i]);
    }
   
    add(this.pane);
    add(this.bar, BorderLayout.NORTH);
    this.bar.add(this.bold);
    this.bar.add(this.italic);
    this.bar.add(this.underline);
    this.bar.add(this.fonts);
    this.bar.add(this.size);
    this.bar.add(this.foreground);
    this.bar.add(this.background);
    this.bar.add(this.pic);
 
    this.bold.addActionListener(this);
    this.italic.addActionListener(this);
    this.underline.addActionListener(this);
    this.foreground.addActionListener(this);
    this.background.addActionListener(this);
    this.pic.addActionListener(this);
    this.fonts.addItemListener(this);
    this.size.addItemListener(this);
  }
  public void actionPerformed(ActionEvent evt) {
    int start = this.pane.getSelectionStart();
    int end = this.pane.getSelectionEnd();
   
    if (start >= end) {
      start = 0;
      end = this.pane.getText().length();
    }
  
    if (evt.getSource() == this.bold) {

      this.doc.setBold(start, end, !this.doc.isBold(start));
    }
  
    else if (evt.getSource() == this.italic) {
     
      this.doc.setItalic(start, end, !this.doc.isItalic(start));
    }
   
    else if (evt.getSource() == this.underline) {
     
      this.doc.setUnderline(start, end, !this.doc.isUnderline(start));
    }
   
    else if (evt.getSource() == this.foreground) {
      Color col = JColorChooser.showDialog(this, "Schriftfarbe auswählen", Color.BLACK);
      if (col != null) {
        this.doc.setForeground(start, end, col);
      }
    }
   
    else if (evt.getSource() == this.background) {
      Color col = JColorChooser.showDialog(this, "Hintergrundfarbe auswählen", Color.WHITE);
      if (col != null) {
        this.doc.setBackground(start, end, col);
      }
    }
   
    else if (evt.getSource() == this.pic) {
      int retval = this.imch.showOpenDialog(this);
      if (retval == JFileChooser.APPROVE_OPTION) {
        this.pane.replaceSelection("");
        try {
          this.doc.setIcon(this.pane.getCaretPosition(), new ImageIcon(this.imch.getSelectedFile().getAbsolutePath()));
        }
        catch (BadLocationException ble) {
          ble.printStackTrace();
        }
      }
    }
  }
  public void itemStateChanged(ItemEvent evt) {
   
    if (evt.getStateChange() == ItemEvent.SELECTED) {
     
      int start = this.pane.getSelectionStart();
      int end = this.pane.getSelectionEnd();
      if (start >= end) {
        start = 0;
        end = this.pane.getText().length();
      }
     
      if (evt.getSource() == this.fonts) {
        this.doc.setFont(start, end, this.fonts.getSelectedItem().toString());
      }
      else if (evt.getSource() == this.size) {
        this.doc.setFontSize(start, end, Integer.parseInt(this.size.getSelectedItem().toString()));
      }
    }
  }
    JButton save;
    JButton load;
  void initUI() {
      Panel Buttonpanel = new Panel();

        save = new JButton("Speichern");
        save.addActionListener(e -> saveToFile());
        load = new JButton("Öffnen");
        load.addActionListener(e -> load());
        Buttonpanel.add(save);
        Buttonpanel.add(load);
        JFrame frame = new JFrame("Schreibprogramm by Nico M.");
        frame.add(new JScrollPane(new EditorComponent()));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setVisible(true);
        frame.add(Buttonpanel, BorderLayout.SOUTH);
       
  }
  protected void load() {
      final JFileChooser fc = new JFileChooser();
      int returnVal = fc.showOpenDialog(load);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            showText(file);
        }
  }
  private void showText(File file){
      StringBuffer buf = new StringBuffer();
      if(file.exists( )){
          try {
              BufferedReader reader = new BufferedReader(new FileReader(file));
              String line = "";
              while((line = reader.readLine( )) != null){
                  buf.append(line+"\n");
              }
              reader.close( );
          }
          catch (FileNotFoundException e) {
              e.printStackTrace( );
          }
          catch (IOException e) {
              e.printStackTrace( );
          }
      }
      this.pane.setText(buf.toString( ));
  }
  protected void save() {
      final JFileChooser fc = new JFileChooser();
      int returnVal = fc.showSaveDialog(save);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            saveText(file);
        }
  }
  private void saveText(File file) {
      try {
          FileWriter writer = new FileWriter(file);
          String text = this.pane.getText( );
          writer.write(text);
          writer.flush( );
          writer.close( );
      }
      catch (IOException e) {
          e.printStackTrace( );
      }
  }


protected void saveToFile() {
  JFileChooser fileChooser = new JFileChooser();
  int retval = fileChooser.showSaveDialog(save);
  if (retval == JFileChooser.APPROVE_OPTION) {
    File file = fileChooser.getSelectedFile();
    if (file == null) {
      return;
    }
    if (!file.getName().toLowerCase().endsWith(".nico")) {
      file = new File(file.getParentFile(), file.getName() + ".nico");
    }
    try {
      pane.write(new OutputStreamWriter(new FileOutputStream(file),
          "utf-8"));
      Desktop.getDesktop().open(file);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

public static void main(String[] args) {
  new EditorComponent().initUI();
}

}
und das EditorDocument
Java:
package Schreibprogramm;
import java.awt.Color;

import javax.swing.ImageIcon;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class EditorDocument extends DefaultStyledDocument {
  private static final long serialVersionUID = -2191570369962370294L;
  public void setIcon(int pos, ImageIcon ico) throws BadLocationException {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setIcon(sas, ico);
    insertString(pos, " ", sas);
  }
  public boolean isItalic(int pos) {
    Element element = getCharacterElement(pos);
    return StyleConstants.isItalic(element.getAttributes());
  }
  public boolean isBold(int pos) {
    Element element = getCharacterElement(pos);
    return StyleConstants.isBold(element.getAttributes());
  }
  public boolean isUnderline(int pos) {
    Element element = getCharacterElement(pos);
    return StyleConstants.isUnderline(element.getAttributes());
  }
  public void setItalic(int start, int end, boolean active) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setItalic(sas, active);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setBold(int start, int end, boolean active) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setBold(sas, active);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setUnderline(int start, int end, boolean active) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setUnderline(sas, active);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setFont(int start, int end, String font) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setFontFamily(sas, font);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setFontSize(int start, int end, int size) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setFontSize(sas, size);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setForeground(int start, int end, Color col) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, col);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public void setBackground(int start, int end, Color col) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setBackground(sas, col);
    setCharacterAttributes(start, end - start, sas, false);
  }
  public EditorDocument() {
    super();
  }
  public EditorDocument(Content arg0, StyleContext arg1) {
    super(arg0, arg1);
  }
  public EditorDocument(StyleContext arg0) {
    super(arg0);
  }
}
Was muss ich ändern?
 

Neue Themen


Zurück
Oben