JButton zum ändern Der Schriftart/Schriftgröße

JO2simpl

Mitglied
Hallo, Ich bin im Internet über einen Quelltext für einen SpeedReader gestolpert und wollte nun probieren noch jeweils einen Button zum ändern der Schriftgröße/Schriftart einzufügen was mir jedoch nach mehreren Anläufen nicht gelungen ist. Nun bin ich hier gelandet und bitte um Hilfe das Problem zu lösen :D

Bin noch recht unerfahren mit Java und bin daher auch für Verbesserungsvorschläge als auch Tipps offen ^^

Code:
package reader;

import javax.swing.*;   //used for user interface
import javax.swing.text.SimpleAttributeSet; //used for changing fonts
import javax.swing.text.StyleConstants; //text styles
import javax.swing.text.StyledDocument; //text styles
import java.awt.*;
import java.awt.event.ActionListener;   //listens for mouse clicks on buttons
import java.awt.event.ActionEvent;  //handles button press events
import java.io.FileNotFoundException;   //handles file exceptions
import java.io.FileReader;  //file reader for file input
import java.util.Scanner;   //scanner for input
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JFrame;


public class Reader {

    JFrame guiFrame;    //initiate main window frame
    JPanel optPanel;    //initiate option panel
    JFileChooser fileDialog;    //initiate fileDialog
    JTextPane textPane;     //initiate textPane

    int pause = 265;    //set initial reading speed to 200wpm
    int f = 1;      //tracks the colour scheme
    String filePath;    //holds location of the selected file


    public static void main(String[] args) {
         //Use the event dispatch thread for Swing components
         EventQueue.invokeLater(new Runnable()
         {
            @Override
             public void run()
             {
                 new Reader();
             }
         });
    }

    public Reader() //Create JFrame and all components
    {
        guiFrame = new JFrame();    //create new instance of the main window
        guiFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);   //program will exit if window closed
        guiFrame.setTitle("Reader Window");     //title of main window
        guiFrame.setSize(500,200);      //set the size of the main window
        guiFrame.setLocationRelativeTo(null);   //put the window in the middle of the screen
        guiFrame.setLayout(new BorderLayout()); //initiate layout of guiframe

        fileDialog = new JFileChooser();//"C:\\Documents and Settings\\Owner\\My Documents" used to select file to read

        textPane = new JTextPane();     //create new instance of the textpane
        textPane.setEditable(false);    //user cannot edit text in textpane
        Font font = new Font("Serif", Font.BOLD, 22);   //set font and size
        textPane.setFont(font); //set font of textpane
        StyledDocument doc = textPane.getStyledDocument();  //styled document allows allignment options
        SimpleAttributeSet center = new SimpleAttributeSet();       //attribute set to control center alignment
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);   //Align text to the center
        doc.setParagraphAttributes(0, doc.getLength(), center, false);  //set formatting options
        textPane.setText("Choose a speed, open a file and start reading");  //initial contents of textpane
        textPane.setVisible(true);      //set textpane to visible
        guiFrame.add(textPane, BorderLayout.CENTER);    //add textpane with word output in center to guiframe

        optPanel = new JPanel();        //add an instance of optPanel
        optPanel.setLayout(new GridLayout(1,3));   //set layout of buttons 1 high by 3 wide
        guiFrame.add(optPanel,BorderLayout.NORTH);  //Put the buttons at the bottom of the window

        JButton openButton = new JButton("Open File");  //Create new button
        openButton.setActionCommand("Open File");
        openButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {   //event happens if file button pressed
                try {
                    openFile();     //call open file method to display file selection window
                } catch (Exception e) {     //catch exception
                    e.printStackTrace();    //used to identify problems
                }
            }
        });
        optPanel.add(openButton);   //add open file button to option panel

        JButton speedButton = new JButton("Select WPM");  //Create new button
        speedButton.setActionCommand("Select WPM");
        speedButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {   //event happens if user clicks button
                try {
                    setSpeed();     //call set speed method to display speed window
                } catch (Exception e) { //catch exception
                    e.printStackTrace();    //used to identify problems
                }
            }
        });
        optPanel.add(speedButton);  //Add speed selection button to option panel

        JButton changeColours = new JButton("change color");  //Add button to invert colour scheme
        changeColours.setActionCommand("change color");
        changeColours.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {    //event happens when user clicks button---
                try {
                    if (f == 1) {       //check the current color settings. Currently black on white
                          
                        textPane.setForeground(Color.blue);    //set text colour to white
                        f = 0;          //tracks colour settings
                    } else {                //check the current color settings. currently white on black
                        
                        textPane.setForeground(Color.green);
                        f = 1;          //tracks colour settings
                    }
                } catch (Exception e) {   //catch exception
                    e.printStackTrace();    //used to identify problems
                }
            }
        });
        optPanel.add(changeColours);    //add the colour button to option panel
        
        guiFrame.setVisible(true);
    }

    //Show a open file dialog box
    private void openFile() throws Exception {  //exception needed to handle files
        int openChoice = fileDialog.showOpenDialog(guiFrame);   //display file chooser window
        if (openChoice == JFileChooser.APPROVE_OPTION){     //user selects a file from file chooser window
            filePath = fileDialog.getSelectedFile().getPath();  //set filepath as the path of the file selected in the filedialog window
            (new Thread(new displayText())).start();    //Start displayText method in separate thread to avoid gui freeze
        }
    }
    private void setSpeed(){        //Method called if speed button pressed
        String[] speeds = { "200", "300", "500", "800" };   //String holds values for drop down box
        JFrame frame = new JFrame("Input required speed in words per minute");  //new frame to select speed
        String speedChoice = (String) JOptionPane.showInputDialog(frame,    //option pane used for easy speed selection
                "What speed would you like?",   //display question to user
                "WPM",          //window title
                JOptionPane.QUESTION_MESSAGE,   //standard for option pane
                null,
                speeds, //add the string of speeds as options
                speeds[0]); //default is 200
        if(speedChoice.equals("200"))
            pause = 265;                    //187 words in 59.877s that's 187.38414wpm (without natural reading pauses)
        else if(speedChoice.equals("300"))
            pause = 160;                    //187 words in 38.522s that's 291.26215wpm (without natural reading pauses)
        else if(speedChoice.equals("500"))
            pause = 75;                     //187 words in 22.451s that's 499.75504wpm (without natural reading pauses)
        else if(speedChoice.equals("800"))
            pause = 28;                     //187 words in 14.006s that's 801.08527wpm (without natural reading pauses)
    }

    public class displayText implements Runnable {  //Run all the display text method within its own thread. Prevents the GUI from becoming unresponsive
        public void run(){
            Scanner in = null;     //Scanner to read the file at chosen location
            try {
                in = new Scanner(new FileReader(filePath));
            } catch (FileNotFoundException e) {   //ignore exception
                e.printStackTrace();    //used to identify problems
            }
            int i =0;       //Number of words in document
            while(in.hasNextLine()){        //read every line of file
                in.next();      //move to next word
                i++;            //increment word counter
            }
            in.close();     //Close Scanner after words have been counted

            try {
                in = new Scanner(new FileReader(filePath));     //New Scanner to start at top of file
            } catch (FileNotFoundException e) {   //ignore exception
                e.printStackTrace();    //used to identify problems
            }
            String[] word = new String[i];      //Array stores each word

            int n = 0;
            long start =0, end; //used to calculate words per minute
            float time;     //will hold time taken to finish article
            float wPM;         //will hold number of words per minute

            for(int k=0; k<i; k++){ //loop cycles through every word in file
                //FROM HERE
                if(k==0){       //check if at start of loop
                    start = System.currentTimeMillis();    //Start time used to calculate words per minute
                }
                else if(k==(i-1)){      //check if at end of loop
                    end = System.currentTimeMillis();   //end time used to calculate words per minute
                    time = (end-start);     //time taken = end time - start time
                    wPM = (60/(time/1000))*i;     //words per minute = time in minutes * words read
                    System.out.println(i + " words in " + (time/1000) + "s" + " that's " + wPM + "wpm");    //print results in system dialog
                }
                //TO HERE is just used to show how many words were read. Used to calculate how much pause to set.

                word[k] = in.next();        //get next word from file
                //Natural reading speeds and pauses attempt (needs research)
                if(word[k].length()>=5 && word[k].length()<=8) n = 100;     //short pause for words with 5-8 characters
                else if(word[k].length()>=9 && word[k].length()<=12) n = 150;   //medium pause for words with 9-12 characters
                else if(word[k].length()>12) n = 200;       //long pause for words over 12 characters
                for(int j=0; j<word[k].length(); j++){      //loop cycles through length of word
                    if(word[k].charAt(word[k].length()-1) == '.')   //Add pause after a full stop
                        n += 50;
                    if(word[k].charAt(word[k].length()-1) == ',')   //Add slight pause after a comma
                        n += 30;
                }
                textPane.setText(word[k]);  //Set the word in the text pane to the word read from file
                sleep(pause+n);     //call sleep method to add a pause after the word. n adds custom pause
                n=0;            //n set back to 0 after each word
            }
        }
    }

    private void sleep(int i) {     //Adds a pause between words. i changes length of pause
        try {
            Thread.sleep(i);        //sleep thread for pause+n milliseconds
        } catch(InterruptedException e) {   //exception needed for sleep
            //do nothing
        }
        
        
    }

  




}
 

mihe7

Top Contributor
Für z. B. am Ende Deines Reader-Konstruktors vor guiFrame.setVisible(true) ein:
Java:
        JSpinner changeFontSize = new JSpinner(
                new SpinnerNumberModel(22, 10, 78, 2));

        changeFontSize.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                textPane.setFont(textPane.getFont().deriveFont(
                    ((Number)changeFontSize.getValue()).floatValue()));
            }
        });
        optPanel.add(changeFontSize);
 

JO2simpl

Mitglied
Für z. B. am Ende Deines Reader-Konstruktors vor guiFrame.setVisible(true) ein:
Java:
        JSpinner changeFontSize = new JSpinner(
                new SpinnerNumberModel(22, 10, 78, 2));

        changeFontSize.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                textPane.setFont(textPane.getFont().deriveFont(
                    ((Number)changeFontSize.getValue()).floatValue()));
            }
        });
        optPanel.add(changeFontSize);
Super vielen Dank ^^
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
K (GUI) JButton Farbe bei druck ändern AWT, Swing, JavaFX & SWT 3
H Swing JButton größe ändern AWT, Swing, JavaFX & SWT 5
E Breite eines JButton dynamisch ändern AWT, Swing, JavaFX & SWT 3
S Farbe von JButton ändern AWT, Swing, JavaFX & SWT 5
S Die größe eines JButton ändern AWT, Swing, JavaFX & SWT 7
T Jbutton Click farbe ändern AWT, Swing, JavaFX & SWT 4
S Jtree-Icon per Klick auf JBUTTON ändern AWT, Swing, JavaFX & SWT 3
J Beschriftung vom JButton per UIManager ändern AWT, Swing, JavaFX & SWT 2
X JButton in MetalButtonUI Farbe ändern lassen? AWT, Swing, JavaFX & SWT 7
L Die Farbe von JButton beim Klicken ändern? AWT, Swing, JavaFX & SWT 4
S Cursor über JButton ändern AWT, Swing, JavaFX & SWT 4
H Die Form eines JButton ändern AWT, Swing, JavaFX & SWT 4
G JButton mit importFiles-Funktion auf JDrawPane AWT, Swing, JavaFX & SWT 5
B JButton Search AWT, Swing, JavaFX & SWT 8
B Swing JButton mit KeyListener AWT, Swing, JavaFX & SWT 3
L JButton durch Mausklick auslösen und Enter-Taste AWT, Swing, JavaFX & SWT 2
N Erlennen ob JButton gedrückt ist AWT, Swing, JavaFX & SWT 6
D JButton Form verändern AWT, Swing, JavaFX & SWT 4
R Grafik per JButton laden und austauschen lassen AWT, Swing, JavaFX & SWT 14
SvenPittelkow Programm soll auf JButton warten bis der geklickt wurde AWT, Swing, JavaFX & SWT 1
Badebay Problem mit JButton AWT, Swing, JavaFX & SWT 2
Z Swing Drag and Drop mit einem JButton AWT, Swing, JavaFX & SWT 1
Z Swing Kann man auf JButton zeichenen AWT, Swing, JavaFX & SWT 3
J JButton Icon hinzufügen AWT, Swing, JavaFX & SWT 5
U Swing JButton mit Icon AWT, Swing, JavaFX & SWT 7
ms_cikar Jbutton erzeugt neue Buttons AWT, Swing, JavaFX & SWT 2
Drachenbauer Swing Wie ändere ich die Farbe der Konturen von jButton und jCombobox? AWT, Swing, JavaFX & SWT 18
Drachenbauer Swing Wie ändere ich die helle geklickt-Farbe von einem JButton? AWT, Swing, JavaFX & SWT 4
A Swing JButton mit Pfeiltasten bewegen AWT, Swing, JavaFX & SWT 6
F Swing Scrollbare Liste von JButton AWT, Swing, JavaFX & SWT 4
Hatsi09 JButton text layout AWT, Swing, JavaFX & SWT 9
A Swing JButton aussehen AWT, Swing, JavaFX & SWT 12
J jButton soll nach klicken eine Variable um 1 erhöhen AWT, Swing, JavaFX & SWT 2
Legi Swing JButton Icon verschiebt sich AWT, Swing, JavaFX & SWT 2
T Swing Änderung des ActionListener Events nach Klick auf JButton AWT, Swing, JavaFX & SWT 2
S Swing JButton verschwindet nach Compilieren AWT, Swing, JavaFX & SWT 8
B Swing Posistion von JButton auslesen gibt immer 0 aus AWT, Swing, JavaFX & SWT 1
J Thread kennt JButton nicht. AWT, Swing, JavaFX & SWT 11
G Swing JButton ändert (unerwünscht) Größe bei Ausführung AWT, Swing, JavaFX & SWT 4
MR._FIRE_Flower Variable setzten mit JButton AWT, Swing, JavaFX & SWT 5
S Mit JButton neues Fester öffnen und das alte schließen AWT, Swing, JavaFX & SWT 3
T JButton wird beim vergrößern des Fensters erst sichtbar AWT, Swing, JavaFX & SWT 4
R Swing Verändern der Ausrichtung JButton und neu anzeigen AWT, Swing, JavaFX & SWT 2
G Swing JButton - Keine Klickanimation AWT, Swing, JavaFX & SWT 4
Joker4632 JButton nicht sichtbar, aber funktionsfähig AWT, Swing, JavaFX & SWT 8
B Swing JButton deaktivieren, wenn nicht alle JTextFields ausgefüllt sind. AWT, Swing, JavaFX & SWT 2
D JButton per Tastenkombi auswählen AWT, Swing, JavaFX & SWT 2
K JButton nicht sichtbar machen für User 2 AWT, Swing, JavaFX & SWT 4
L Swing JButton soll link öffnen AWT, Swing, JavaFX & SWT 1
K JButton auf anderer Klasse AWT, Swing, JavaFX & SWT 6
A JButton soll durch anklicken die Farbe wechseln AWT, Swing, JavaFX & SWT 8
T KeyListener funktioniert nicht wenn ich ein JButton hinzufüge AWT, Swing, JavaFX & SWT 1
R Swing ActionListener bei JButton AWT, Swing, JavaFX & SWT 9
B JButton -> Rahmen wegbekommen AWT, Swing, JavaFX & SWT 7
N JButton über benutzerdefinierte paintComponent setzen AWT, Swing, JavaFX & SWT 3
T JButton überlagern sich und werden erst beim Mausscrollen sichtbar AWT, Swing, JavaFX & SWT 2
B JButton erscheint in JFrame, obwohl er diesem nicht zugeordnet wurde! AWT, Swing, JavaFX & SWT 1
M JButton Probleme AWT, Swing, JavaFX & SWT 14
T Klasse über JButton schließen AWT, Swing, JavaFX & SWT 4
M Textfarbe JButton verändern AWT, Swing, JavaFX & SWT 2
N JButton ausblenden AWT, Swing, JavaFX & SWT 2
M Swing jButton Text verschwindet AWT, Swing, JavaFX & SWT 2
C Swing JButton wird nicht angezeigt AWT, Swing, JavaFX & SWT 2
stylegangsta JLabel durch Klick auf JButton einblenden AWT, Swing, JavaFX & SWT 16
stylegangsta Eigene Klasse für JButton aus dem JFrame abrufen AWT, Swing, JavaFX & SWT 29
stylegangsta MouseEvents aus JButton aufrufen AWT, Swing, JavaFX & SWT 3
stylegangsta JButton Transparent anzeigen AWT, Swing, JavaFX & SWT 9
stylegangsta JButton Fehelr javax.swing.ImageIcon.<init>(Unknown Source) AWT, Swing, JavaFX & SWT 24
X Swing JButton's zum JScrollPane hinzufügen geht nicht. Bitte um Hilfe. AWT, Swing, JavaFX & SWT 9
D JButton - Nur Icon anzeigen / transparenter Hintergrund AWT, Swing, JavaFX & SWT 2
S JButton-Label vergrößern AWT, Swing, JavaFX & SWT 2
J Swing Basics - JButton funktioniert nicht. AWT, Swing, JavaFX & SWT 1
L JButton mit ImageIcon/Fehlermeldung AWT, Swing, JavaFX & SWT 1
D jButton Problem, ein Rieser Button bedeckt das ganze frame AWT, Swing, JavaFX & SWT 1
L Array mit JButton, wie rausfinden auf welche JButton geklickt wurde + index des JButtons ausgeben AWT, Swing, JavaFX & SWT 4
L JButton mit Image AWT, Swing, JavaFX & SWT 5
fLooojava JButton [Focus) AWT, Swing, JavaFX & SWT 4
M JButton - Listener AWT, Swing, JavaFX & SWT 1
D jButton auf von jFrame erzeugtem jDialog AWT, Swing, JavaFX & SWT 16
L JButton flackern - Programm hängt sich auf AWT, Swing, JavaFX & SWT 3
L JButton - Größe anders als erwartet AWT, Swing, JavaFX & SWT 2
1 JButton nach Klick ausblenden AWT, Swing, JavaFX & SWT 6
X Swing 1 JButton bedeckt meine ganze Frame aber Warum? AWT, Swing, JavaFX & SWT 2
S Größe und Farbe vom JButton festlegen AWT, Swing, JavaFX & SWT 2
H Swing JList/JTable mit JButton, JTextField, Image, JComboBox und JLable AWT, Swing, JavaFX & SWT 2
J JButton neu zeichnen lassen AWT, Swing, JavaFX & SWT 9
S JButton u. Label auf paint-Methode AWT, Swing, JavaFX & SWT 1
HoloYoitsu Swing JButton in verschiedenen Winkeln drehen AWT, Swing, JavaFX & SWT 0
J vocab1 = new JButton(""+voc1.get(nr).toString()+""); AWT, Swing, JavaFX & SWT 16
A JButton wird bei ActionListener nicht "angenommen" AWT, Swing, JavaFX & SWT 7
BRoll JButton Text nicht ausblenden ("...") AWT, Swing, JavaFX & SWT 2
I JFrame mit JButton schließen? AWT, Swing, JavaFX & SWT 0
D JList&JButton erst nach Resize des JFRame sichtbar AWT, Swing, JavaFX & SWT 2
J Swing JFrame slideout, wenn JButton gedrückt wurde AWT, Swing, JavaFX & SWT 0
S Swing Rückmeldung für JButton AWT, Swing, JavaFX & SWT 4
R AWT JLabel oder JButton aktualisieren AWT, Swing, JavaFX & SWT 1
L JButton im Frame fest verankern AWT, Swing, JavaFX & SWT 0
M Swing Mix JComboBox - JButton? AWT, Swing, JavaFX & SWT 6
U Event Handling JButton Actionevent: starte Spiel AWT, Swing, JavaFX & SWT 4
E JButton füllt ganzes JPanel auf AWT, Swing, JavaFX & SWT 6

Ähnliche Java Themen

Neue Themen


Oben