My text does not change. I don't understand why - java

I don't understand why this Java code isn't working. It's a GUI project I'm working on and I'm trying to get the JLabel to change to bold, italic, etc. via some check boxes:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class FontViewer {
static JCheckBox checkBoxBold;
static JCheckBox checkBoxItalic;
static JCheckBox checkBoxCenter;
static JPanel textPanel;
static JLabel textLabel;
static JComboBox fontName;
static JComboBox fontSize;
static ActionListener listener;
public static void main(String[] args) {
final int FRAME_SIZE_X = 250;
final int FRAME_SIZE_Y = 400;
JFrame frame = new JFrame();
frame.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
JPanel face = new JPanel();
face.setLayout(new GridLayout(2, 1));
JPanel bottomFace = new JPanel();
bottomFace.setLayout(new GridLayout(3, 1));
textPanel = createTextPanel();
JPanel checkBoxPanel = createCheckBoxPanel();
JPanel comboPanel = createComboPanel();
JPanel radioButtonsPanel = createButtonsPanel();
face.add(textPanel);
bottomFace.add(checkBoxPanel);
bottomFace.add(comboPanel);
bottomFace.add(radioButtonsPanel);
face.add(bottomFace);
frame.add(face);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
class FontListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
int fontStyle = 0;
if (checkBoxBold.isSelected())
fontStyle = fontStyle + Font.BOLD;
if (checkBoxItalic.isSelected())
fontStyle = fontStyle + Font.ITALIC;
if (checkBoxCenter.isSelected())
textPanel.add(textLabel, BorderLayout.CENTER);
String textFont = (String) fontName.getSelectedItem();
int textSize = Integer.parseInt((String) fontSize
.getSelectedItem());
textLabel.setFont(new Font(textFont, fontStyle, textSize));
textLabel.repaint();
}
}
listener = new FontListener();
}
private static JPanel createTextPanel() {
textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
textLabel = new JLabel("Java Text");
textPanel.add(textLabel, BorderLayout.WEST);
return textPanel;
}
private static JPanel createCheckBoxPanel() {
JPanel checkBoxPanel = new JPanel();
checkBoxBold = new JCheckBox("Bold");
checkBoxItalic = new JCheckBox("Italic");
checkBoxCenter = new JCheckBox("Center");
checkBoxBold.addActionListener(listener);
checkBoxItalic.addActionListener(listener);
checkBoxCenter.addActionListener(listener);
checkBoxPanel.add(checkBoxBold);
checkBoxPanel.add(checkBoxItalic);
checkBoxPanel.add(checkBoxCenter);
return checkBoxPanel;
}
private static JPanel createComboPanel() {
JPanel comboPanel = new JPanel();
fontName = new JComboBox();
fontName.addItem("Serif");
fontName.addItem("Courier");
fontSize = new JComboBox();
fontSize.addItem("12");
fontSize.addItem("24");
fontSize.addItem("36");
comboPanel.add(fontName);
comboPanel.add(fontSize);
return comboPanel;
}
private static JPanel createButtonsPanel() {
JPanel radioButtonsPanel = new JPanel();
JRadioButton redButton = new JRadioButton("Red");
JRadioButton whiteButton = new JRadioButton("White");
JRadioButton blueButton = new JRadioButton("Blue");
ButtonGroup colors = new ButtonGroup();
colors.add(redButton);
colors.add(whiteButton);
colors.add(blueButton);
radioButtonsPanel.add(redButton);
radioButtonsPanel.add(whiteButton);
radioButtonsPanel.add(blueButton);
return radioButtonsPanel;
}
}
When I press any of the check boxes, the JLabel object does not change. Any help is greatly appreciated and thank you so much in advance.
Note: As of now, I only wish to know why the check boxes are not working. This code is incomplete, I'm aware of this. Thank you once again.

At the time you added the listener to the check boxes, the value of listener was null. listener is not initialized until the very end of the main method.

Try to initialize the listeners before creating JFrame. It worked for me. Of course the definition of the FontListener class has to be put before listener declaration accordingly.
//...
listener = new FontListener();
JFrame frame = new JFrame();
//...

Related

How can I draw multiple JLabels in different places? (icons don't show up)

I am trying to draw multiple icons in many different locations using for loop. For some reason they just don't show up. I don't know what I'm missing – only clue I found was about setting layout to null, but IntelliJ overwrites it.
Icons should show up in "mapa" panel. I tried adding them manually, but nothing changed.
My code:
package okna;
import logistyka.Walker;
import logistyka.errand.Errand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class WalkerGUI extends JFrame{
private JPanel mainPanel;
private JLabel walkerName;
private JTextField walkerNameField;
private JLabel walkerAddress;
private JTextField walkerAddressField;
private JButton searchErrandsButton;
private JComboBox errandsComboBox;
private JLabel errandsList;
private JTextField walletValue;
private JLabel Wallet;
private JRadioButton archivalErrandsRadioButton;
private JRadioButton currentErrandsRadioButton;
private JButton payOutButton;
private JButton seeProfileButton;
private JPanel mapa;
ArrayList<Errand> masterErrandList = new ArrayList<>();
public WalkerGUI(Walker w, ArrayList<Errand> masterErrandList) {
setContentPane(mainPanel);
ArrayList<JLabel> errandsLabels = new ArrayList<>();
ImageIcon x = new ImageIcon(System.getProperty("user.dir") + "\\src\\x.png");
this.masterErrandList = masterErrandList;
for (Errand errand: masterErrandList) {
JLabel label = new JLabel("whtvr");
label.setIcon(x);
label.setLocation((int)errand.getAddress().getX(),(int)errand.getAddress().getY());
label.setMinimumSize(new Dimension(20,20));
label.setPreferredSize(new Dimension(20,20));
label.setVisible(true);
errandsLabels.add(label);
}
walkerNameField.setText(w.getDescription().getName());
walkerAddressField.setText(w.getDescription().getHomeRegion().getCurrentAddress().toString());
walletValue.setText(String.valueOf(w.getWalletSatus()));
seeProfileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new ProfileGUI(w);
frame.pack();
frame.setVisible(true);
}
});
payOutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
w.setWalletSatus(0);
walletValue.setText(String.valueOf(w.getWalletSatus()));
}
});
}
}
You can use SpringLayout (rather than null layout). Method Errand.getAddress().getX() will return the distance of the left edge of the JLabel from the left edge of its container while Errand.getAddress().getY() will return the distance of the top edge of the JLabel from the top edge of its container.
The code in your question is not a minimal, reproducible example so the below code should be considered as a proof of concept.
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class SprinGui {
private void createAndDisplayGui() {
JFrame frame = new JFrame("Spring");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
Point[] points = new Point[]{new Point(5, 5),
new Point(5, 100),
new Point(225, 150),
new Point(250, 210)};
Class<?> meClass = getClass();
Icon[] icons = new Icon[4];
icons[0] = new ImageIcon(meClass.getResource("coffee.png"));
icons[1] = new ImageIcon(meClass.getResource("dollar.png"));
icons[2] = new ImageIcon(meClass.getResource("dynamite.png"));
icons[3] = new ImageIcon(meClass.getResource("soccer-player.png"));
for (int i = 0; i < 4; i++) {
JLabel label = new JLabel(icons[i]);
contentPane.add(label);
layout.putConstraint(SpringLayout.WEST,
label,
points[i].x,
SpringLayout.WEST,
contentPane);
layout.putConstraint(SpringLayout.NORTH,
label,
points[i].y,
SpringLayout.NORTH,
contentPane);
}
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SprinGui instance = new SprinGui();
EventQueue.invokeLater(() -> instance.createAndDisplayGui());
}
}
This is how the GUI looks.
Note that How to Use Icons may also be helpful.

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

Nesting FlowLayout Panels

I'm trying to create a GUI using JAVA for a BMR calculator.
I'm having some problems with getting the GUI right so I have been experimenting with different layout managers/nesting Jpanels.
My current code has an age and gender label, both contained in separate JPanels in a flow layout, but the problem is that they appear next to eachother rather than on seperate lines as I want them to.
How can I acheive this with my code? My current laoyut is as below, I want Gender to be below age, and have been playing with this for some time but can't get it to work.
Cheers.
package v2;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.FlowLayout;
public class BmrCalcv2 extends JFrame {
static JFrame mainFrame;
static JPanel mainPanel;
static JMenuBar menuBar;
static JMenu fileMenu, editMenu;
static JPanel agePanel;
private JLabel ageLabel;
private JTextField ageTextField;
static JPanel genderPanel;
private JLabel genderLabel;
public BmrCalcv2() {
// Main JFrame
mainFrame = new JFrame("BMR/TDEE Calculator");
mainPanel = new JPanel();
// All JPanel declarations
menuBar = new JMenuBar();
agePanel = new JPanel();
genderPanel = new JPanel();
// JPanel layout managers
agePanel.setLayout(new FlowLayout(10));
genderPanel.setLayout(new FlowLayout(10));
// Menu JPanel
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
// Age JPanel
ageLabel = new JLabel("Age:");
ageTextField = new JTextField(5);
agePanel.add(ageLabel);
agePanel.add(ageTextField);
// Gender JPanel
genderLabel = new JLabel("Gender:");
genderPanel.add(genderLabel);
// Adding sub JPanels to main JPanel
mainPanel.add(agePanel);
mainPanel.add(genderPanel);
// Adding main JPanel/menubar to JFrame
mainFrame.setJMenuBar(menuBar);
mainFrame.add(mainPanel);
}
public static void main(String[] args) {
BmrCalcv2 frame = new BmrCalcv2();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setSize(330, 300);;
mainFrame.setResizable(false);
}
}
If you don't care about alignment:
mainFrame.getContentPane().setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.X_AXIS));
// quick pseudocode incoming
for(int x = 0; x < components.size(); x++) {
JPanel j = new JPanel();
j.setLayout(new FlowLayout(FlowLayout.CENTER)); // I think CENTER is the default anyhow
j.add(getLabel(x));
j.add(getField(x));
mainFrame.add(j);
}
If you care about alignment, swap the FlowLayout for a BoxLayout along the Y_AXIS and put some horizontal glue between the label and the input field(s).
Something like this should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class GridBagLayoutExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("BMI Calculator");
// create the gui elements
JLabel ageLabel = new JLabel("Age:");
JTextField ageTxt = new JTextField(20);
JLabel genderLabel = new JLabel("Gender:");
JTextField genderTxt = new JTextField(20);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.HORIZONTAL;
// age label
cons.gridx = 0;
cons.gridy = 0;
pan.add(ageLabel, cons);
// age text
cons.gridx = 1;
cons.gridy = 0;
pan.add(ageTxt, cons);
// gender label
cons.gridx = 0;
cons.gridy = 1;
pan.add(genderLabel, cons);
// gender text
cons.gridx = 1;
cons.gridy = 1;
pan.add(genderTxt, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 200);
jframe.setVisible(true);
}
}
Looks like this:

changing color for the square textfield

I'm trying to create a layout that would take 3 RGB colors and change the background of the textfield but I'm not able to do so.
package Quizzes_practice;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class quiz3 extends JFrame{
private JPanel up;
private JPanel down;
private JPanel left; // as mother container
private JPanel right;
private JLabel font_size;
private JLabel color_val;
private JLabel r;
private JLabel g;
private JLabel b;
private JTextField font_text;
private JTextField r_text;
private JTextField g_text;
private JTextField b_text;
private JLabel color_text;
private JTextField red; // the big square
private JCheckBox bold;
private JCheckBox italic;
private JRadioButton fg;
private JRadioButton bg;
private JRadioButton reset;
private ButtonGroup gorup;
//private JPanel container; // this will sit in the left corner
private JPanel panel1; // for each row one of these
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel center;
public quiz3(){
JFrame myframe = new JFrame();
setLayout(new BorderLayout()); // general layout
JPanel up = new JPanel();
JPanel down = new JPanel();
JPanel left = new JPanel();
JPanel right = new JPanel();
// adding components
// adding the main 4 panels to the their positions
// panel left will be the container
JLabel font_size = new JLabel("Font Size ");
JLabel r = new JLabel("R");
JLabel g = new JLabel("G");
JLabel b = new JLabel("B");
myhandler handler = new myhandler();
JTextField font_text = new JTextField(10);
JTextField r_text = new JTextField(4);
r_text.addActionListener(handler);
JTextField g_text = new JTextField(4);
g_text.addActionListener(handler);
JTextField b_text = new JTextField(4);
b_text.addActionListener(handler);
JCheckBox bold = new JCheckBox("Bold");
JCheckBox italic = new JCheckBox("Italic");
JRadioButton fg = new JRadioButton("Foreground");
JRadioButton bg = new JRadioButton("Background");
JRadioButton reset = new JRadioButton("Reset");
ButtonGroup group = new ButtonGroup();
//JPanel center = new JPanel();
red = new JTextField(); // text field that I want to change its color
//center.setLayout(new FlowLayout());
//center.add(red);
///red.setBackground(Color.RED);
add(up, BorderLayout.NORTH);
add(down, BorderLayout.SOUTH);
add(left, BorderLayout.WEST);
add(red, BorderLayout.CENTER);
JPanel panel1 = new JPanel ();
JPanel panel2 = new JPanel ();
JPanel panel3 = new JPanel ();
JPanel panel4 = new JPanel ();
// adding compnents to the frame
up.setLayout(new FlowLayout());
up.add(font_size);
up.add(font_text);
up.add(bold);
up.add(italic);
down.setLayout(new FlowLayout());
//down.add(group);
group.add(fg);
group.add(bg);
group.add(reset);
down.add(fg);
down.add(bg);
down.add(reset);
JLabel color_text = new JLabel("Font size");
panel1.add(color_text);
panel2.setLayout(new FlowLayout());
panel2.add(r);
panel2.add(r_text);
panel3.setLayout(new FlowLayout());
panel3.add(g);
panel3.add(g_text);
panel4.setLayout(new FlowLayout());
panel4.add(b);
panel4.add(b_text);
left.setLayout(new GridLayout(5,0));
left.add(panel1);
left.add(panel2);
left.add(panel3);
left.add(panel4);
}
private class myhandler implements ActionListener{
int red1;
int blue1;
int green1;
public void actionPerformed (ActionEvent event){
if(event.getSource()== r_text){
String a = event.getActionCommand();
int a2 = Integer.parseInt(a);
Color mycolor = new Color(a2);
red.setBackground(mycolor);
}
if(event.getSource()== b_text){
String a = event.getActionCommand();
int a2 = Integer.parseInt(a);
Color mycolor = new Color(a2);
red.setBackground(mycolor);
}
if(event.getSource()== g_text){
String a = event.getActionCommand();
int a2 = Integer.parseInt(a);
Color mycolor = new Color(a2);
red.setBackground(mycolor);
}
else {System.out.println("error!");}
}
}
}
I'm not getting an error, it's just not happening, the condition I believe is incorrect
You're shadowing your JTextField variables. Replace
JTextField r_text = new JTextField(4);
with
r_text = new JTextField(4);
The same applys to the other color components.
Aside: Consider using JColorChooser. Read How to Use Color Choosers

centering JLabel in a panel

For some reason, the "Java Text" JLabel does not center. I've looked up how to do it and seen various examples, the most promising being http://www.java2s.com/Code/Java/Swing-JFC/AsimpledemonstrationoftextalignmentinJLabels.htm but it's not working. Here's the whole code if you wish to run it yourself with a few in-code comments so you don't have to bother searching through its entirety:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
public class FontViewer
{
static JCheckBox checkBoxBold;
static JCheckBox checkBoxItalic;
static JCheckBox checkBoxCenter;
static JPanel textPanel;
static JLabel textLabel;
static JComboBox fontName;
static JComboBox fontSize;
static JRadioButton redButton;
static JRadioButton whiteButton;
static JRadioButton blueButton;
static ActionListener listener;
public static void main(String[] args)
{
final int FRAME_SIZE_X = 250;
final int FRAME_SIZE_Y = 400;
JFrame frame = new JFrame();
frame.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
JPanel face = new JPanel();
face.setLayout(new GridLayout(2, 1));
// listener inner class
class FontListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int fontStyle = 0;
if (checkBoxBold.isSelected())
fontStyle = fontStyle + Font.BOLD;
if (checkBoxItalic.isSelected())
fontStyle = fontStyle + Font.ITALIC;
// this if statement does not work
if (checkBoxCenter.isSelected())
textLabel.setHorizontalAlignment(SwingConstants.CENTER);
String textFont = (String) fontName.getSelectedItem();
int textSize = Integer.parseInt((String) fontSize.getSelectedItem());
textLabel.setFont(new Font(textFont, fontStyle, textSize));
if (redButton.isSelected())
textLabel.setForeground(Color.RED);
else if (whiteButton.isSelected())
textLabel.setForeground(Color.WHITE);
else if (blueButton.isSelected())
textLabel.setForeground(Color.BLUE);
textLabel.repaint();
}
}
listener = new FontListener();
JPanel bottomFace = new JPanel();
bottomFace.setLayout(new GridLayout(3, 1));
textPanel = createTextPanel();
JPanel checkBoxPanel = createCheckBoxPanel();
JPanel comboPanel = createComboPanel();
JPanel radioButtonsPanel = createButtonsPanel();
face.add(textPanel);
bottomFace.add(checkBoxPanel);
bottomFace.add(comboPanel);
bottomFace.add(radioButtonsPanel);
face.add(bottomFace);
frame.add(face);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static JPanel createTextPanel()
{
final int DEFAULT_FONT_SIZE = 12;
textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
textLabel = new JLabel("Java Text");
textLabel.setFont(new Font("Times", 0, DEFAULT_FONT_SIZE));
textPanel.add(textLabel, BorderLayout.WEST);
return textPanel;
}
// check boxes created and programmed here
private static JPanel createCheckBoxPanel()
{
JPanel checkBoxPanel = new JPanel();
checkBoxBold = new JCheckBox("Bold");
checkBoxItalic = new JCheckBox("Italic");
checkBoxCenter = new JCheckBox("Center");
checkBoxBold.addActionListener(listener);
checkBoxItalic.addActionListener(listener);
checkBoxCenter.addActionListener(listener);
checkBoxPanel.add(checkBoxBold);
checkBoxPanel.add(checkBoxItalic);
checkBoxPanel.add(checkBoxCenter);
return checkBoxPanel;
}
private static JPanel createComboPanel()
{
JPanel comboPanel = new JPanel();
fontName = new JComboBox();
fontName.addItem("Times");
fontName.addItem("Serif");
fontName.addItem("Courier");
fontSize = new JComboBox();
fontSize.addItem("12");
fontSize.addItem("24");
fontSize.addItem("36");
comboPanel.add(fontName);
comboPanel.add(fontSize);
fontName.addActionListener(listener);
fontSize.addActionListener(listener);
return comboPanel;
}
private static JPanel createButtonsPanel()
{
JPanel radioButtonsPanel = new JPanel();
redButton = new JRadioButton("Red");
whiteButton = new JRadioButton("White");
blueButton = new JRadioButton("Blue");
redButton.addActionListener(listener);
whiteButton.addActionListener(listener);
blueButton.addActionListener(listener);
ButtonGroup colors = new ButtonGroup();
colors.add(redButton);
colors.add(whiteButton);
colors.add(blueButton);
radioButtonsPanel.add(redButton);
radioButtonsPanel.add(whiteButton);
radioButtonsPanel.add(blueButton);
return radioButtonsPanel;
}
}
I'm completely puzzled by this anomaly and any help or advice is greatly appreciated! Thank you so much in advance.
The textLabel is anchored to the BorderLayout.WEST position of your textPanel. Move it to the center:
textPanel.add(textLabel, BorderLayout.CENTER);

Categories

Resources