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);
Related
I would like to layout my components as shown in this picture.
In short:
aTextField must have a fixed size of 250px;
bButton has a fixed size that dependes on the text label;
bTextField should grow so that it's width plus bButton width reach
250px.
This is my code:
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutIdReference extends JFrame {
private final MigLayout migLayout = new MigLayout("debug", "", "");
private final JLabel aLabel = new JLabel("Label A");
private final JTextField aTextField = new JTextField();
private final JLabel bLabel = new JLabel("Label B");
private final JTextField bTextField = new JTextField();
private final JButton bButton = new JButton("B Button");
public MigLayoutIdReference() {
Container container = getContentPane();
container.setLayout(migLayout);
add(aLabel, "");
add(aTextField, "id aTextField, w 250!, wrap");
add(bLabel, "");
add(bTextField, "width aTextField.w-bButton.w");
add(bButton, "id bButton, wrap");
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MigLayoutIdReference();
}
}
Unfortunately it seems that MigLayout does not allow to calculate width based on other components that you recall by id.
When running my code I get:
Caused by: java.lang.IllegalArgumentException: Size may not contain links
Am I missing something? Apart from referencing components by id, how could I achieve the desired result?
I changed the MigLayout constructor invocation and added row constraints and column constraints.
I made aTextField span two columns.
I gave bTextField the growx constraint.
Now the width of bTextField will adjust so that together with the width of bButton it will match the width of aTextField.
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutIdReference extends JFrame {
private final MigLayout migLayout = new MigLayout("debug", "[][grow][]", "[][]");
private final JLabel aLabel = new JLabel("Label A");
private final JTextField aTextField = new JTextField();
private final JLabel bLabel = new JLabel("Label B");
private final JTextField bTextField = new JTextField();
private final JButton bButton = new JButton("B Button");
public MigLayoutIdReference() {
Container container = getContentPane();
container.setLayout(migLayout);
add(aLabel, "");
add(aTextField, "id aTextField, w 250!, wrap, span 2");
add(bLabel, "");
add(bTextField, "growx");
add(bButton, "id bButton,wrap");
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MigLayoutIdReference();
}
}
Here is a screen capture:
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.
I am trying to add the buttons to the centerPanel that I created, then add that panel to the main center borderlayout. for some reason though my tab will not repaint anymore. It worked fine a while ago when I had the DrawFieldsListener class in the same class file as the MagicSquare, but nothing in the code has changed from my splitting them into two class files. So i really don't know what is going on. When it did repaint before, it would also take a long time. Any help? thanks!
All source for the project is on GitHub if it is easier to read and understand there: https://github.com/andrefecto/Academic-Convivium-Project
MagicSquare Class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MagicSquare extends JPanel {
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
static JButton calculate;
static JButton reset;
static JTextField squareSize;
static JTextField field;
public static ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
public static ArrayList<Integer> inputs = new ArrayList<Integer>();
public static ArrayList<Integer> totals = new ArrayList<Integer>();
public static int squared = 0;
public static int square = 0;
public static JPanel centerPanel = new JPanel();
public static JPanel bottomPanel = new JPanel();
public MagicSquare (){
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JTextField();
squareSize.setColumns(6);
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
}
}
my DrawFieldsListener class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawFieldsListener extends JPanel implements ActionListener {
int square = MagicSquare.square;
int squared = MagicSquare.squared;
JPanel centerPanel = MagicSquare.centerPanel;
JTextField squareSize = MagicSquare.squareSize;
JTextField field = MagicSquare.field;
ArrayList<JTextField> inputFields = MagicSquare.inputFields;
JButton calculate = MagicSquare.calculate;
JButton reset = MagicSquare.reset;
JPanel bottomPanel = MagicSquare.bottomPanel;
public void actionPerformed(ActionEvent e){
square = Integer.parseInt(squareSize.getText());
squared = square*square;
centerPanel.setLayout(new GridLayout(square, square));
for(int i = 0; i < squared; i++){
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons(){
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
calculate.addActionListener(new CalculateListener());
reset.addActionListener(new ResetListener());
}
}
Mistake #1
public static JPanel centerPanel = new JPanel();
Followed by...
class DrawFieldsListener extends JPanel implements ActionListener {
//...
JPanel centerPanel = MagicSquare.centerPanel;
static is not a cross object communication mechanism...and now I have no idea who is suppose to be responsible for managing the centerPanel...
Remember, static is not your friend, beware of how it is used
Mistake #2
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
You are creating two instances of DrawFieldsListener (which is a panel), one is acting as the ActionListener and one is acting as the view, but which one is actually housing MagicSquare.centerPanel as a component can only have one parent...
Mistake #3
Not revalidating the container after you have changed it...
public void actionPerformed(ActionEvent e) {
square = Integer.parseInt(squareSize.getText());
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
Swing is lazy when it comes to container management, it assumes that you will want to do a number of adds or removes, so it won't update the container hierarchy layout until you ask it to, as the operation can be expensive
A better solution...
Isolate responsibility and provide information to your objects in a de-coupled manner.
For example, the DrawFieldsListener shouldn't care about MagicSquare, but should provide a means by which "some body" can tell it how many squares it should create.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MagicSquare extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MagicSquare());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
private JSpinner squareSize;
JTextField field;
public MagicSquare() {
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JSpinner();
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
DrawFieldsListener dfl = new DrawFieldsListener();
setSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int gridSize = (int) squareSize.getValue();
dfl.makeGrid(gridSize);
}
});
add(subPanel, BorderLayout.NORTH);
add(dfl, BorderLayout.CENTER);
}
class DrawFieldsListener extends JPanel {
private JButton calculate;
private JButton reset;
private ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
private ArrayList<Integer> inputs = new ArrayList<Integer>();
private ArrayList<Integer> totals = new ArrayList<Integer>();
private int squared = 0;
private int square = 0;
private JPanel centerPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
public void makeGrid(int gridSize) {
square = gridSize;
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons() {
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
// calculate.addActionListener(new CalculateListener());
// reset.addActionListener(new ResetListener());
}
}
}
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
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();
//...