I want to automatically disable a few buttons.
I wrote the code:
import javax.swing.*;
public int[] zamrozone = new int[4];
a1 = new JButton("A1");
a2 = new JButton("A2");
a3 = new JButton("A2");
a4 = new JButton("A2");
a5 = new JButton("A2");
private void zamroz()
{
zamrozone[0]=1;
zamrozone[1]=1;
zamrozone[2]=1;
zamrozone[3]=0;
zamrozone[4]=0;
for(int i=0; i<8; i++) //losuje 8 statkow
{
if(zamrozone[i]==1)
"a"+i.setEnabled(false); // here is an error
}
}
Unfortunately this is not working. Anyone know how to do this?
You can put the JButtons in an array and then use their index:
import javax.swing.*;
final int SIZE = 5;
JButton[] buttons = new JButton[SIZE]
for (int i=0; i<SIZE;i++) {
buttons[i] = new JButton("A" + i)
}
public int[] zamrozone = new int[SIZE];
private void zamroz()
{
zamrozone[0]=1;
zamrozone[1]=1;
zamrozone[2]=1;
zamrozone[3]=0;
zamrozone[4]=0;
for (int i=0; i<SIZE; i++) //losuje SIZE statkow
{
if (zamrozone[i]==1) {
buttons[i].setEnabled(false); // here is an error
}
}
:
}
Use defined SIZE rather then constant values all over your code to avoid OutOfBounds exception and make the code easier to change/maintain.
"a"+i.setEnabled(false); cannot work as variables don't work that way. What you are doing right there is trying to call setEnabled on the integer i and then adding the return value (which does not exist as setEnabled returns void) to the String literal "a".
I would suggest storing your buttons in an array as well and then simply calling buttonArray[i].setEnabled(false) inside the loop.
Related
Lets say I have a public class called GameBoard that will be a two dimensional array with 4 rows and 5 columns. The spaces in the array are filed with String values from 1 to 20. A card will be drawn that has a name (King of Spades for example) . If the user inputs 15 I will store it in a String variable called userLocation. What would be the most efficient way to create a method that takes the input location and updates the array with the name of the Card? Would a for loop be most efficient?
public GameBoard() {
square = new String[4][5];
square[0][0] = new String("1");
square[0][1] = new String("2");
square[0][2] = new String("3");
square[0][3] = new String("4");
square[0][4] = new String("5");
square[1][0] = new String("6");
square[1][1] = new String("7");
square[1][2] = new String("8");
square[1][3] = new String("9");
square[1][4] = new String("10");
square[2][1] = new String("11");
square[2][2] = new String("12");
square[2][3] = new String("13");
square[3][1] = new String("14");
square[3][2] = new String("15");
square[3][3] = new String("16");
square[2][0] = new String(17);
square[3][0] = new String(18);
square[2][4] = new String(19);
square[3][4] = new String(20);
}
My preferred method as of now would look something like this but it gives me the error code "type mismatch:cannot convert string to boolean" under userLocation = board[i][j]
public String[][] updateBoard(String userLocation, Card card, String[][] board) {
for (int i = 0; i <4; i++)
{
for (int j = 0; j < 5; j++)
{
if(userLocation = board[i][j]) {
board[i][j] = card.name;
}
}
}
return board;
}
So the reason it will not compile is your = does not return a boolean expression. == would, but it's still not what you want, since you want to check if the String contents are the same, not if they're the same object, so use .equals.
But, no, I think you don't want to depend on strings to identify locations. What if you want to replace a card? And why look through everything when you need not?
Rather if i is some number between 1 and 20, identify the corresponding spot in the array by square[(i-1)/5][(i-1)%5]
That should bypass the issue you are having with matching strings.
So for example, your constructor becomes:
public GameBoard() {
square = new String[4][5];
for (int i=1; i<=20;i++){
square[(i-1)/5][(i-1)%5]=""+i;//initialize with 1 to 20 if you like
}
and userLocation is an int.
In Java, I'm trying to identify which JComboBox within an ArrayList was just clicked on. Some of the code follows:
private ArrayList<JComboBox<String>> setTextBoxList;
// basic initialization
public void populateList() {
String str[] = {"one", "two"};
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(new JComboBox<String>(str));
jcb.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o instanceof JComboBox) {
// here's where I'd like to see which box was just changed
System.out.println("change index "
+ setTextBoxList.indexOf((JComboBox)o) );
}
}
My problem is that when I click on and change one of the comboboxes, the index shown is always -1. I'd like to get the index of which box in the arraylist was just clicked on/changed. I get the same results w/o the explicit type-cast.
The problem is in this segment of code:
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(new JComboBox<String>(str)); // <-- error!
jcb.addActionListener(this);
}
You are creating two JComboBoxes, and the one that gets the listener is not the one that is in the list. Try changing the code to:
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(jcb); // changed line
jcb.addActionListener(this);
}
public void allButtonChoice(){
Button[] multiChoice = new Button[3];
multiChoice = new Button[]{choiceButton1,choiceButton2,choiceButton3,choiceButton4};
//to output shuffled array in an randomized order.
//Random number generator.
Random generateMultiChoice = new Random();
for(int i = 0; i < multiChoice.length; i++){
int randomPosition = generateMultiChoice.nextInt(multiChoice.length);
Button temp = multiChoice[i];
multiChoice[i] = multiChoice[randomPosition];
multiChoice[randomPosition] = temp;
}
//set the positions to the buttons in order
choiceButton1.setX(10f);
choiceButton1.setY(10f);
choiceButton2.setX(10f);
choiceButton2.setY(10f);
choiceButton3.setX(10f);
choiceButton3.setY(12f);
choiceButton4.setX(10f);
choiceButton4.setY(12f);
}
How can I assign a variable to choiceButton1, choiceButton2, choiceButton3, and choiceButton4? Is it possible to have one variable that holds the four buttons with setX and setY data?
choiceButton1.setTag(value);
will be useful for you
you can retrieve data by calling getTag
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class vasilisTable extends JFrame {
Object[] split_data_l;
Object[][] split_data;
Object [][] split_data_clone;
Object [][] split_data_reverse;
Object [][] split_data_reverse_num;
String[] temp;
private JTable table;
private JPanel bottom_panel;
private JLabel average;
private JLabel max_dr;
public vasilisTable(String name, String data, int choice)
{
super(name);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //the DISPOSE_ON_CLOSE means that when we press the x button is will close only the table window and not the whole programm
//this.getAccessibleContext().setAccessibleName(name);
//System.out.println(this.getAccessibleContext().getAccessibleName());
setSize(800,600);
String[] columnNames = {"Date", "Open","High","Low","Close",
"Volume", "Adjusted" };//defines the column names
//------ Start of making the arrays that will be used as data for the table creation
split_data_l = data.split( "\n" );
int lngth = split_data_l.length;
split_data = new Object[lngth-1][7];
split_data_clone = new Object[lngth-1][7];
split_data_reverse= new Object[lngth-1][7];
split_data_reverse_num= new Object[lngth-1][7];
double sum = 0;
for(int k=1; k<split_data_l.length; k++) //initializing the three arrays with the data we got from the URLReader
{
temp = split_data_l[k].toString().split(",");
for (int l=0; l<temp.length; l++)
{
split_data[k-1][l] = temp[l];
split_data_clone[k-1][l] = temp[l];
split_data_reverse[k-1][l] = temp[l];
split_data_reverse_num[k-1][l] = temp[l];
}
}
for(int k=split_data_l.length-2; k>=1; k--) // making of the clone array that contains all the last column with colours
{
Double temp = Double.parseDouble(split_data[k][6].toString());
Double temp1 = Double.parseDouble(split_data[k-1][6].toString());
double check =temp-temp1;
if (check>0)
{
String color_temp = "<html><span style = 'color:red'>" + split_data_clone[k-1][6] +"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
else
{
String color_temp = "<html><span style = 'color:green'>" +split_data_clone[k-1][6]+"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
}
int l = split_data_clone.length;
int m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse[i][j]=split_data_clone[m][j];
}
m--;
}
m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse_num[i][j]=split_data[m][j];
}
m--;
}
//------ End of making the arrays that will be used as data for the table creation
//------ Start of calculating the average
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data[i][6].toString());
sum = sum+temp;
//System.out.println("turn "+i+" = "+split_data[i][6]);
}
float avg = (float) (sum/(lngth-1));
avg = Round((float) avg,2);
String avg_str;
avg_str = "<html>Average: <b>"+avg+"</b></html>";
//"<html><b>Average: </b></html>"
//------ End of calculating the average
//------ Start of Calculating the Maximal Drawdown
double high=0;
double low=100000000;
double drawdown=0;
double max_drawdown=0;
int last_high=0;
int last_low=0;
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data_reverse_num[i][6].toString());
//Double temp1 = Double.parseDouble(split_data[i+1][6].toString());
if (temp>high)
{
high = temp;
last_high = i;
//System.out.println("max high = "+temp);
}
else
{
low = temp;
last_low = i;
//System.out.println("max low = "+temp);
}
if (last_low>last_high)
{
drawdown = high-low;
//System.out.println("drawdown = "+drawdown);
}
if (drawdown>max_drawdown)
{
max_drawdown = drawdown;
}
}
//System.out.println("max dr = "+max_drawdown);
String max_dr_str = "<html>Maximal Drawdown: <b>"+max_drawdown+"</b></html>";
//------ End of Calculating the Maximal Drawdown
average = new JLabel(avg_str);
max_dr = new JLabel(max_dr_str);
bottom_panel = new JPanel();
String space = " ";
JLabel space_lbl = new JLabel(space);
bottom_panel.add(average);
bottom_panel.add(space_lbl);
bottom_panel.add(max_dr);
//-------- Start of table creation ---------
if(choice==1)
{
table = new JTable(split_data_clone, columnNames);//creates an instance of the table with chronological order
}else
{
table = new JTable(split_data_reverse, columnNames);//creates an instance of the table with reverse chronological order
}
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0) {
column.setPreferredWidth(100); //third column is bigger
} else if (i == 5) {
column.setPreferredWidth(85); //third column is bigger
}
else if (i == 6) {
column.setPreferredWidth(70); //third column is bigger
}
else {
column.setPreferredWidth(50);
}
}
table.setShowGrid(true);
table.setGridColor(Color.black);
//-------- End of table creation ---------
JPanel table_panel = new JPanel (new BorderLayout());
JScrollPane table_container = new JScrollPane(table); // create a container where we will put the table
//table.setFillsViewportHeight(true); // if the information are not enough it still fill the rest of the screen with cells
table_panel.add(table_container, BorderLayout.CENTER);
table_panel.add(bottom_panel, BorderLayout.SOUTH);
//table_panel.add();
setContentPane (table_panel);
pack(); // here i pack the final result to decrease its dimensions
}
public float Round(float Rval, int Rpl) // this functions rounds the number to 2 decimal points
{
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}
I am making an application which creates various instances of a class. These instances are actually some windows. After having create multiple of these windows, how can I access one of them and bring it in front? I know the .tofront() method, but how can I specify the window that I want to bring in front?
Above is the code that creates every window. My main problem is that after I have create e.g 5 windows, how can I access one of them?
ps
code that creates each window:
if (sData != null) {
//System.out.println("Success, waiting response");
vasilisTable ftable = new vasilisTable(name, sData, choice);
hashMap.put(name, ftable);
ftable.setVisible(true);
//choice=2;
}
My main problem is that after I have create e.g 5 windows, how can I access one of them?
You have to keep a reference to the relevant objects in variables or an array or a collection or something. The "bring it to the front" function needs to:
figure out what domain object needs to be brought to the front,
lookup its corresponding JFrame, and
call toFront() on it.
Java provides no built-in mechanisms for finding previously created instances of objects.
When you create your various instances of the above JFrame, you can keep track of the created instances, may be store them within a HashMap, then you can pick the right JFrame instance basing on its designated name and bring it to the front. Have a look at the below code for more illustration:
HashMap<String, VasilisTable> hashMap = new HashMap<String, VasilisTable>();
JFrame firstWindow = new VasilisTable("firstWindow",data, choice);
hashMap.put("firstWindow", firstWindow);
JFrame secondWindow = new VasilisTable("secondWindow",data, choice);
hashMap.put("secondWindow", secondWindow);
JFrame thirdWindow = new VasilisTable("thirdWindow",data, choice);
hashMap.put("thirdWindow", thirdWindow);
// To bring a certain window to the front
JFrame window = hashMap.get("firstWindow");
window.setVisible(true);
window.toFront();
Are these JFrame or JWindow objects? If they are you can call -
jframe.setVisible(true);
jframe.toFront();
This is something interesting I found at the API doc.
Places this Window at the top of the stacking order and shows it in
front of any other Windows in this VM. No action will take place if
this Window is not visible. Some platforms do not allow Windows which
own other Windows to appear on top of those owned Windows. Some
platforms may not permit this VM to place its Windows above windows of
native applications, or Windows of other VMs. This permission may
depend on whether a Window in this VM is already focused. Every
attempt will be made to move this Window as high as possible in the
stacking order; however, developers should not assume that this method
will move this Window above all other windows in every situation.
I would recommend you to check out these answers as well.
Java Swing: JWindow appears behind all other process windows, and will not disappear
Java: How can I bring a JFrame to the front?
//edit: I changed my ArrayList conversion, but I am unable to load the second spinner
What am I doing wrong. I would like to fill a second spinner with an array of w depending on the row selected in the first spinner, but am getting this warning when trying to convert from array list.
***I have this marked in code
Null Pointer Exception
11-06 19:03:34.050: WARN/System.err(5342): at RetrievingAmazonXMLDataActivity.onCreate(RetrievingAmazonXMLDataActivity.java:88)
// edited code
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
w = (String[][])allProducts.toArray(new String[allProducts.size()][]);
Spinner spinnerProducts = (Spinner) findViewById(R.id.spinner2);
spinnerProducts.setOnItemSelectedListener(this);
// ** error line below
ArrayAdapter<String> productsArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, productArrayToShow);
productsArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProducts.setAdapter(productsArrayAdapter);
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
try {
selected = parent.getItemAtPosition(position).toString();
productArrayToShow = w[position];
} catch (Exception e) {}
}
// original code
ArrayList<String[]>allProducts = new ArrayList<String[]>();
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
String[][] w; = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = (String[])allProducts.toArray(new String[allProducts.size()]);
}
Why not just
String[][] w = allProducts.toArray(new String[][] {});
It looks like you changed your mind about how you were going to do the conversion half way through. Your code is a bit of this:
String[][] w = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = allProducts.get(a);
}
and a bit of that:
String[][] w = allProducts.toArray(new String[allProducts.size()][]);
Either will work, though the latter is shorter, and possibly more efficient.
I think you can get by with just this:
String[][] w = allProducts.toArray(new String[allProducts.size()]);
Make them of the same datatype an "ArrayList" and a "Array of Strings" they are not of the same datatype, so they wont be compartable with each other. And please comment where the problem is.