Wednesday, September 21, 2011

JAVA: Using JButton to Change font of JLabel?

How do you change the font of a JLabel in a Java Applet when the user clicks the JButton?



import javax.swing.*;

import java.awt.*;

public class JChangeFont extends JApplet {

Container con = getContentPane();

JLabel greeting = new JLabel(';Hello. Who are you?';);

Font headlineFont = new Font(';Helvetica';, Font.BOLD, 36);

JButton pressMe = new JButton(';Press to change font';);

public void init()

{



con.add(greeting);

con.add(pressMe);

pressMe = greeting.setFont(headlineFont);

con.setLayout(new FlowLayout());

}

}



It's not workingJAVA: Using JButton to Change font of JLabel?
Why are you setting a button to the (probably void) results of a setFont function?



pressme.addActionListener(this);



And then have a function:

void actionPerformed(ActionEvent e)

{

greeting.setFont(headlineFont);

}



and add: , implements ActionListener



before the first '{' after the class keyword. You should really read the Java tutorial by Sun (I've linked it below).JAVA: Using JButton to Change font of JLabel?
The previous answerer is right.. you need to add an action listener, like he said.



The other thing wrong is you don't use 'getContentPane()' with a JApplet.. that is for JFrames only. Instead create a new JPanel and add your stuff onto that. Finally use 'add(your_JPanel)' to include it in the JApplet.



Good luck!
  • software alternative to excel
  • score a triumph
  • No comments:

    Post a Comment