Cannot set JLabel to Multiple Text Values - java

My JLabel isn't being set to all of these text values.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MultipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
lbl.setText("First Text");
Thread.sleep(1000);
lbl.setText("Second Text");
Thread.sleep(1000);
lbl.setText("Third Text");
}catch (Exception e) {
//Don't really care if the program dies
}
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
The output would waits two seconds, then set the value of the JLabel to "Text Three" instead of displaying the three values one after another. I don't see what I'm doing wrong here.

From the question, It is not clear what is the problem you are facing. Please add an example of the code that others can run and test.
If you are trying to see the value of the variables a, b or 'c' in the JLabel , you will need code like
GUIWindow.text.setText(a.toString());
What you are doing now is setting the text "a" and not the value of variable a.
I am not sure what is the data type of the variables a, b or 'c'. If they do have a proper toString() implementation (they probably do as the System.out.println() is giving you the desired output), the above code should work. Else you might need to call the right method on these variables that will give you the desired text.

I was able to fix this issue by creating and running a swing timer. Here is the code, with the fix inside it.
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MulttipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
static Timer t;
static int i;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
t = new Timer (1000,new ActionListener() {
public void actionPerformed(ActionEvent e2) {
;
lbl.setText("First Text");
switch (i) {
case 1:
lbl.setText("Second Text");
i++;
break;
case 2:
lbl.setText("Third Text");
i++;
break;
default:
i++;
}
if (i == 3) {
t.stop();
i = 0;
}
}
});
t.start();
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
I don't have a compiler on me, but I am sure this code should work for what you need.

Related

java swing get or set unique id for new JButton while create thim on for loop

i have java swing Class that create JButton
it is working but what i need is when i pressed a JButton lets seed that it is number 1 the code in the ActionEvent is to change the Background of the JButton but what i need is if i pressed another JButton the first one i need it to go back to red Color :
Example :
package Classes;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class testbtn {
public JFrame frame = new JFrame();
public int copcounter = 5;
public testbtn() {
JPanel jdb = new JPanel();
jdb.setLayout(new FlowLayout());
for (int x = 1; x <= copcounter; x++) {
JButton btn = new JButton();
btn.setText(String.valueOf(x));
if (x == 1) {
btn.setBackground(Color.yellow);
} else {
btn.setBackground(Color.red);
}
btn.putClientProperty("id", x);
btn.addActionListener((ActionEvent e) -> {
btn.setBackground(Color.yellow);
System.out.println(e.getID());
});
jdb.add(btn);
}
frame.add(jdb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new testbtn();
}
});
}
}
this code will show form like this :
when i press JButton 4 the output become like this :
but i need it to be like this so the other button will become red color but what i pressed i need it to become yellow ! :
i know that i can use id but how to get the id for them ! or if there is better way ?
No need for an id, simply put all the JButtons into a List<JButton>, say called buttonList, and then iterate through the list in the button's ActionListener, turning backgrounds red for all the buttons in the list, and then turn the current button's background yellow.
And then in the code that uses it:
public void actionPerformed(ActionEvent e) {
// iterate through the list
for (JButton button : buttonList) {
button.setBackground(Color.RED);
}
// then set *this* button's color yellow:
((JButton) e.getSource).setBackground(Color.YELLOW);
}
That's it
or for your code...
public class TestBtn {
public JFrame frame = new JFrame();
public int copcounter = 5;
private List<JButton> buttonList = new ArrayList<>();
public TestBtn() {
JPanel jdb = new JPanel();
jdb.setLayout(new FlowLayout());
for (int x = 1; x <= copcounter; x++) {
JButton btn = new JButton();
// add this
buttonList.add(btn);
btn.setText(String.valueOf(x));
if (x == 1) {
btn.setBackground(Color.yellow);
} else {
btn.setBackground(Color.red);
}
// btn.putClientProperty("id", x);
btn.addActionListener((ActionEvent e) -> {
// iterate through the list
for (JButton button : buttonList) {
button.setBackground(Color.RED);
}
// then set *this* button's color yellow:
((JButton) e.getSource).setBackground(Color.YELLOW);
// show button text
System.out.println(e.getActionCommand());
});
jdb.add(btn);
}
frame.add(jdb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new testbtn();
}
});
}
}
Also, the ActionEvent's actionCommand String should match the button's text (with some exceptions).

I'm trying to make a button to count characters in a text field

I'm trying to use the JButton count to count the number of characters entered into the JTextField t. I'm new to Java and GUIs but here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
I'm also trying to enter the value in another uneditable JTextField x. Any help is appreciated.
Add this to your code
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
OR
You can use lambda expression like this
count.addActionListener(e -> a = t.getText().length());
For More
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You need to add a listener
TextField t = new TextField();
Button b = new Button("Count");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
}
});
You can read more about here
http://www.tutorialspoint.com/awt/awt_button.htm
First of all, I recommend you not to use AWT elements, since it brings tons of problems and it has little to no support, instead you can try using Swing components which are a replacement/fix for AWT. You can read more about here. You might also want to read AWT vs Swing (Pros and Cons).
Now going into your problem:
You should avoid extending from JFrame, I might recommend you to create a new JFrame object instead. Here's the reason to why. That being said, you can also remove all your this.t and other calls with this.
I'm glad you're using a Layout Manager!
And now to count the number of characters on your JTextField and set text to your other JTextField you should use this code:
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
Also I fixed your code, I changed AWT elements to Swing ones and added number of cols to your second JTextField so it would appear.
So, here's a running example that I made from your code (And removed Choice choice line since you didn't posted that code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 {
JTextField t;
JButton count;
int a;
JFrame frame;
public GUI1(){
frame = new JFrame();
t = new JTextField("", 15);
count = new JButton("count");
JTextField x = new JTextField("", 15);
x.setEditable(false);
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
frame.setTitle("Character count");
frame.setLayout(new FlowLayout());
frame.add(x);
frame.add(t);
frame.add(count);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
new GUI1();
}
}
When you click on a button you should
String str = t.getText(); // get string from jtextfield
To save the text from the texfield. Then you can use something like:
a = str..length(); // get length of string
x.setText(str + " " + a); //set it to the field
To set it to the JTextField.

Why won't my .isSelected() method work?

Well what i'm trying to do is change the text of the JRadioButton's when they're selected, i got them to change the color. I know I can do it by putting the code to change the text inside the dedicated event handling method specific to each button, but how do I do it so that I use A DIFFERENT event handling method that just changes the buttons? I already created one but it doesn't work, here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LessonTwenty extends JFrame implements ActionListener{
JRadioButton b1,b2;
JTextArea t1;
JScrollPane s1;
JPanel jp = new JPanel();
public LessonTwenty()
{
b1= new JRadioButton("green");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.GREEN);
}
});
b2= new JRadioButton("red");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.RED);
}
});
//Method to change the text of the JRadion Buttons, what i'm trying to make work
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
jp.add(b1);
jp.add(b2);
this.add(jp);
setTitle("Card");
setSize(700,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String [ ] args){
new LessonTwenty();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
if i understand you right, you want do do something like this:
//Method to change the text of the JRadion Buttons, what i'm trying to make work
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
b1= new JRadioButton("green");
b1.addActionListener(al);
b2= new JRadioButton("red");
b2.addActionListener(al);
ie. you define one ActionListener which you use in all your objects.
The anonymous object you define in your original code does absolutely nothing, it just creates an ActionListener which nobody can ever access, since it is not assigned to any Button.
Maybe this could help
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1){
b1.setText("Welcome");
} else if(e.getSource() == b2){
b2.setText("Hello");
}
}
};

Implementing a way to change a JLabel from another class in my game Part 3?

I am currently having trouble with being able to change the choiceDeclaration JLabel. My mindset behind the choiceDeclaration JLabel is to simply display text based on which JButton is clicked.
Here is my current code for the project:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.event.*;
public class prompt {
public static void main(String []args) {
/* Setting up the JPanel and its necessities for this program */
JFrame choicePrompt = new JFrame("Rock, Paper, Scissors Game");
JPanel choicePanel = new JPanel();
JButton rockButton = new JButton("ROCK");
JButton scissorsButton = new JButton("SCISSORS");
JButton paperButton = new JButton("PAPER");
JLabel choiceDeclaration = new JLabel();
choicePrompt.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
choicePrompt.setResizable(false);
choicePrompt.setSize(300, 300);
choicePrompt.setVisible(true);
choiceDeclaration.setVisible(true);
choicePrompt.add(choicePanel);
choicePanel.add(choiceDeclaration);
choicePanel.add(rockButton);
choicePanel.add(scissorsButton);
choicePanel.add(paperButton);
choiceDeclaration.setVerticalTextPosition(JLabel.TOP);
choiceDeclaration.setHorizontalTextPosition(JLabel.CENTER);
/* ActionListeners for the JButtons */
rockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
scissorsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
paperButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
}
}
I cannot use a setText method in my ActionListeners as shown below because it conflicts with my main class method a line below the declaration of my class. They are both using String in their parameters.
public static void main(String []args) {
rockButton.addActionListener(new ActionListener() {
setText(String text) {
}
}
}
My concluding thought was to make another class that could use the setText method to change the JLabel on that frame. However, since JLabels cannot be called from one class to another like variables or methods, I am having trouble trying to implement this idea.
Have a separate method for it...
public static void settext() {
setText(String text)
}
then call it in your action listener...
rockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
settext();
}
});
I hope this is what you meant! :)

JComboBox getSelectedIndex() method

I was making a simple text editor where you can set font style,font size, clear all etc. To set font size I added JComboBox and implemented ItemListener. Here is my MainWindow class:
import javax.swing.*;
public class MainWindow extends JFrame{
Editor e = new Editor();
public MainWindow(){
super(".:My Text Editor:.");
getContentPane().add(e);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new MainWindow();
}
});
}
}
Here is my Editor class:
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Editor extends JPanel{
JPanel optionPanel = new JPanel();
JTextArea editArea = new JTextArea();
JButton boldBtn = new JButton("Bold");
JButton italicBtn = new JButton("Italic");
JButton plainBtn = new JButton("Plain");
JButton clearBtn = new JButton("Clear all");
String [] fontSizes = {"10","11","12","13","14","15","16","17","18","19","20"};
int fontSize;
JComboBox combo = new JComboBox(fontSizes);
public Editor(){
createUI();
addEvents();
}
public void createUI(){
optionPanel.add(boldBtn);
optionPanel.add(italicBtn);
optionPanel.add(plainBtn);
optionPanel.add(combo);
optionPanel.add(clearBtn);
setLayout(new BorderLayout());
add(optionPanel,BorderLayout.NORTH);
add(new JScrollPane(editArea),BorderLayout.CENTER);
setPreferredSize(new Dimension(640,480));
}
public void addEvents(){
boldBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.BOLD,fontSize));
}
});
italicBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.ITALIC,fontSize));
}
});
plainBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
}
});
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
int ind = combo.getSelectedIndex();
System.out.println(ind);
fontSize = Integer.parseInt(fontSizes[ind]);
editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
}
});
clearBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setText("");
}
});
}
}
Now, weird thing what happened is when I put System.out.println(ind); line just to see what index the getSelectedIndex() method returns me. Depending on which item I click, it returns me this:
1
1
0
0
2
2
3
3
Why is this happening? Shouldn't return me just 1 0 2 3? Thanks in advance.
JCombobox fire itemStateChanged twice for SELECTED and DESELECTED that you differentiate with ItemEvent.getStateChanged(). So wrap your code in an if like this:
public void itemStateChanged( ItemEvent event ) {
if( event.getStateChanged() == ItemEvent.SELECTED ) {
// code here
}
}
Whenever you change the selection in a JComboBox, the itemStateChanged event is triggered twice, once for DESELECT of the old selected item and once for SELECT for the new selected item.
If you only want your code to be executed once, just do:
if (e.getStateChange() == ItemEvent.SELECTED) {
...
}
Seems that itemStateChanged is triggered twice. I think that the ItemEvent parameter is not the same each time. Perhaps you should check the event type before doing something.
Sorry I can't check now, but I will do it later if you still need help.

Categories

Resources