Update new position for Jlabel - java

I'm new to Java and I am having some trouble with my assignment.
I have a Panel containing 100 JLabels:
for(int i=0;i<100;i++)
{
num[i] = new JLabel(""+i, JLabel.CENTER);
mainPanel.add(num[i]);
}
And a button to set image icon for the label when clicked
public void actionPerformed(ActionEvent ae)
{
int a = ran.nextInt(6) +1;//random number
int b +=a;
if(b>=100)
{
b=99;
num[b].setIcon(icon);
}
else
{
num[b].setIcon(icon);
}
}
How can i remove the icon from the last position and update it to a new position?

You can try to remember the index of the array of the label, for which you tried to set the icon.
For example-
int b = 0; // make b an instance variable
public void actionPerformed(ActionEvent ae)
{
int a = ran.nextInt(6) +1;//random number
num[b].setIcon(null); //remove the icon from from previously set label
b=a; //since b already has some value, b+=a might create unexpected result, hence just assigned a
if(b>=100)
{
b=99;
num[b].setIcon(icon);
}
else
{
num[b].setIcon(icon);
}
}

Related

How to know on which Label I clicked [Java]

I tried .equals() and ==, but nothing help. All labels I storage in ArrayList of my own class, which have JLabel.
How can I get the index of the label in ArrayList or something else?
Can my problem in using ArrayList?
MouseListener
private static MouseListener clicklvl1=new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
for (int i=0;i<shahtars.size();i+=1){
if (e.getSource()==shahtars.get(i).uiShahtar){
IDofClickedObject=i;
}
}
if (IDofClickedObject!=-1){
if (counter == 0) {
shahtars.get(IDofClickedObject).uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1(Clicked).png"));
counter = 1;
} else if (counter == 1) {
// uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
shahtars.get(IDofClickedObject).uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
counter = 0;
}
}
System.out.print("x "+shahtars.get(IDofClickedObject).uiShahtar.getX()+" y "+shahtars.get(IDofClickedObject).uiShahtar.getY());
}
My class
class FillShahtar implements Cloneable {
static JLabel uiShahtar;
static int energy;
static double power;
static double speed;
String name;
And the last
FillShahtar(int chose) {
switch (chose){
case 1:{
plankaDown = 1;
plankaUp = 11;
int xRand = (int) ( 0+Math.random()*1000);
int yRand =(int) (0+Math.random()*600);
int counter=0;
/////////////////////////debug/////////////////
System.out.print(xRand+" "+yRand+"\n");
//////////////////////////////////////////////
energy = (int) (plankaDown + Math.random() * plankaUp );
power = (int) (plankaDown + Math.random() * plankaUp );
speed = (int) (plankaDown + Math.random() * plankaUp );
uiShahtar = new JLabel();
uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
uiShahtar.setLayout(new FlowLayout());
uiShahtar.setSize(50,50);
uiShahtar.setLocation(xRand,yRand);
uiShahtar.setVisible(true);
uiShahtar.addMouseListener(clicklvl1);
// mainPanel.add(shahtars.get(counter).uiShahtar);
counter+=1;
break;
}
Clicked image must change the image, but change only last Label.
Since JLabel inherits from swing's Component class, you can add a MouseListener (or MouseAdapter) to each of your clickable labels. Using this EventListener you can find the clicked label like this:
JLabel l = new JLabel();
l.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
JLabel clickedLabel = (JLabel) e.getComponent();
}
});
In order to get the index of the clicked label within the ArrayList, use the indexOf(Object) method provided by the ArrayList:
int index = list.indexOf(clickedLabel);

How to set properties of a JButton ArrayList?

I have a JButton ArrayList. The code below does not work. How can I access a specific button from the array list and set the size, location and other properties and also add it to the applet?
ArrayList<String> cdTitles = new ArrayList<String>();
ArrayList<JButton> btnCDS = new ArrayList<JButton>();
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Initialize")) {
cdTitles.add("Original Order");
cdTitles.add("Metric - Fantasies");
cdTitles.add("Beatles - Abby Road");
cdTitles.add("Pearl Jam - Ten");
cdTitles.add("Doors - Alive");
cdTitles.add("The Rolling Stones - Gimme Shelter");
for(int i = 0; i < cdTitles.size(); i++) {
String buttonName = "btn" + i;
System.out.println(buttonName);
btnCDS.add(new JButton(buttonName));
break;
}
btnCDS.get(0).setText(cdTitles.get(0));
btnCDS.get(0).setLocation(100, 145);
btnCDS.get(0).setSize(520, 25);
add(btnCDS.get(0));
}
}
provided that this is executing in a Applet sub-class,
this works for me:
#Override
public void init()
{
// all your code between:
// cdTitles.add("Original Order");
// AND
// add(btnCDS.get(0));
// Watch out for dead code in the for loop.
}

Trying to add item listener to a JCheckBox object

I am trying add an item listener to a checkbox to see if its been checked, and if it is, to be added to a list of SQL table names to be selected. Inversely, if it is not selected then remove it from the list. I cannot add a listener though to any checkbox because "they are not effitively final". What can I do/is there a better way to attack it?
My method:
public JPanel drawChecks(){
ArrayList<String> list = MainFrame.grabSQLTableNames();
int index = list.size();
int rows = 1;
while(index > 1){
rows++;
index = index - 3;
}
GridLayout c = new GridLayout(rows, 3);
JPanel panel = new JPanel(c);
JCheckBox check[] = new JCheckBox[list.size()];
for(int x = 0; x < list.size(); x++){
check[x] = new JCheckBox(list.get(x));
check[x].setVisible(true);
check[x].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (check[x].getState == true){
//do something
}
}
});
panel.add(check[x]);
}
Get the source of the event using the getSource method of the ItemEvent
public void itemStateChanged(ItemEvent e) {
JCheckBox checkBox = (JCheckBox)e.getSource();
if ( checkBox.isSelected() ){
//do something
}
}
For future reference, please read the following for tips on posting code examples for asking questions on stack overflow: https://stackoverflow.com/help/mcve

Making a notepad in java with a on screen keyboard, cant link it to the text area properly

First of all, thank you for taking your time to read this.
this is what am trying to make:
A Text editor with multiple options.
a button for a virtual keyboard. I've managed to create the buttons, also successfully added all the buttons, however I am having difficulties linking each button to my text area and making each button press work.
Not looking for anything complex also all other aspects of the app works, as you will see from the screenshot provided.
this is the bits of code in relation to my keyboard.
class KbListener implements ActionListener //kb function.
{
public void actionPerformed(ActionEvent e) //checking events.
{
keyboard = new JFrame("VK");
keyboard.setSize(400,300);//setting initial size of app.
keyboard.setVisible(true);//making sure its active.
keyboard.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);//closes when the x is pressed.
JButton[] letter = new JButton[27];
keyboard.setLayout(new GridLayout(3,9));
for (int i = 0;i<27;i++)
{
letter[i] = new JButton(""+(char)('A'+ i));
keyboard.add(letter[i]);
//up until this point all is fine.
letter[i].addActionListener = (new ActionListener());
if(e.getSource() ==letter[A])
textArea.append("A");
}
}
}
You need to create a String that is used in the button and used in its listener both, something like,
for (int i = 0; i < 27; i++) {
final String buttonText = String.valueOf((char) ('A' + i));
letter[i] = new JButton(buttonText);
keyboard.add(letter[i]);
letter[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(buttonText);
}
});
}
Note that buttonText must be final so that it is accessible within the anonymous inner ActionListener class.
Also, consider avoiding magic numbers. For instance, you could do
for (int i = 0; i <= (int)('Z' - 'A'); i++) {
or
int i = 0;
for (char myChar = 'A'; myChar <= 'Z'; myChar++) {
final String btnText = String.valueOf(myChar);
letter[i] = new JButton(btnText);
keyboard.add(letter[i]);
letter[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(btnText);
}
});
i++;
}
Edit
Another and perhaps better way to do this is to use Actions rather than ActionListeners. For instance,...
//....
int i = 0;
for (char myChar = 'A'; myChar <= 'Z'; myChar++) {
final String btnText = String.valueOf(myChar);
MyKeyBoardAction action = new MyKeyBoardAction(btnText);
letter[i] = new JButton(action);
i++;
}
}
private class MyKeyBoardAction extends AbstractAction {
public MyKeyBoardAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(getValue(NAME).toString());
}
}
You also ask about the space character,
do u know how to add a space to the code as well?
That would not work with your for loop but can be added on its own.
Also,
but why avoid the numbers?
Because it's easy to make hard to fix bugs if you use "magic" numbers that don't intrinsically make sense. Also, by using constants, variables rather than hard-coded numbers, your variables make your code self-commenting.
Why don't create direct the action listener?
letter[i].addActionListener = (new ActionListener() {
public void onClick(View view) {
textArea.append(""+(char)('A'+ i));
}
);

Could someone tell me why my actionListener for-loop is not working?

I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn. I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed. Anyone want to take a peek?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
First investigation:
while (colorCollection.size() < 10)
shall be replaced with
if (colorCollection.size() < 10)
Second observation:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc.
Third:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button.
Finally:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. I cannot look to your file but I think that this will be the problem.
Map Solution:
Initialization
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}

Categories