I'm trying to make a simple GUI with radio buttons that has a list of fonts and when a button is selected is displays text with the font name and in the font style.
When I try to compile I get several errors about "cannot find symbol ... Font.PLAIN" Is there something wrong with the way I'm using the fonts?
Also in the FontListener Class, I need to pass in the button group, should i pass in the button group though a parameter in the constructor?
Lastly, does it seem like I'm using the isSelected(), getSelection().getActionCommand methods correctly? FontFrame Class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class FontFrame extends JFrame {
Font HelveticaFont = new Font("Helvetica", Font.PLAIN, 14);
Font TimesRomanFont = new Font("TimesRoman",Font.PLAIN, 14);
Font CourierFont = new Font("Courier", Font.PLAIN,14);
public FontFrame(String title){
super(title);
}
public void init(){
Container panel = this.getContentPane();
panel.setLayout(new FlowLayout());
JRadioButton Helvetica = new JRadioButton("Helvetica", true);
JRadioButton TimesRoman = new JRadioButton("Times Roman", false);
JRadioButton Courier = new JRadioButton("Courier", false);
JTextField tf = new JTextField("Select One");
panel.add(Helvetica);
panel.add(TimesRoman);
panel.add(Courier);
panel.add(tf);
ButtonGroup group = new ButtonGroup();
group.add(Helvetica);
group.add(TimesRoman);
group.add(Courier);
Helvetica.addItemListener(new FontListener(HelveticaFont, tf));
TimesRoman.addItemListener(new FontListener(TimesRomanFont, tf));
Courier.addItemListener(new FontListener(CourierFont, tf));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
this.setSize(300,200);
this.setVisible(true);
}
}
FontListener Class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class FontListener implements ItemListener {
Font font;
JTextField tf;
public FontListener(Font f, JTextField tf){
this.font = f;
this.tf = tf;
}
public void itemStateChanged(ItemEvent event){
if(Helvetica.isSelected()) {
tf.setFont(font);
tf.setText(group.getActionCommand());
}
else if(TimesRoman.isSelected()) {
tf.setFont(font);
tf.setText(group.getActionCommand());
}
else if(Courier.isSelected()) {
tf.setFont(font);
tf.setText(group.getActionCommand());
}
}
}
Main Class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Font{
public static void main(String[] args){
FontFrame window = new FontFrame("Fonts");
window.init();
}
}