Generate list of int to populate ComboBox in JavaFX - java

I'm trying to avoid hardcoding a whole bunch of numbers into my JavaFX ComboBox, but I don't know any other way to do it. Currently I'm doing this:
length_comboBox.getItems().addAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
However my aim is to make a call to a method that will generate a list of numbers to some specified upper limit (say 50). I've tried the following but it just adds one last i, instead of all 50:
length_comboBox.getItems().addAll(generator(50));
public static int generator(int limit) {
int i;
for (i = 1; i < limit; i++)
System.out.println(i);
return i;
}

ComboBox cBox = new ComboBox();
cBox.getItems().addAll(generator());
... example ...
private Integer[] generator() {
int size = (int) (Math.random() * 100);
Integer[] result = new Integer[size];
for (int i = 0; i < result.length; i++) {
result[i] = (int) (Math.random() * 50);
}
return result;
}

You can use the one-liner
IntStream.rangeClosed(1,50).boxed().forEach(length_comboBox.getItems()::add);
or, if you want to fire fewer change events to the combo box (in practice it will make very little difference):
length_comboBox.getItems().setAll(
IntStream.rangeClosed(1,50).boxed().collect(Collectors.toList())
);

Related

Keep JTable Stationary in JScrollPane When Resizing Columns

I have a JTable inside a JScrollPane. The user scrolls to the right. I then enlarge by x pixels a column to the left of where the user is looking. This causes the table to appear to scroll left. How do I adjust the JScrollPane, JScrollBar or JViewport to keep the table stationary? In other words, how do I keep the same visible portion of the table on the screen?
I tried adjusting the horizontal JScrollBar's value by x. I also tried adjusting the JViewport's view position by x. The problem is that the table ends up scrolling to the right.
Here is the code that shows the problem without any of my attempts to keep the table stationary.
package oracle.psr.ndr.guiclient.util.table;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public final class StableColumnResizing extends JFrame
{
private static final long serialVersionUID = 738732002168497075L;
private final TableColumnModel m_model;
private final JScrollBar m_bar;
private int m_colIndex;
public static void main(String args[])
{
SwingUtilities.invokeLater(StableColumnResizing::create);
}
private static void create()
{
StableColumnResizing frame;
Timer timer;
frame = new StableColumnResizing();
frame.setVisible(true);
SwingUtilities.invokeLater(frame::moveRight);
timer = new Timer(1000, frame::adjust);
timer.start();
}
private StableColumnResizing()
{
JScrollPane pane;
JTable table;
Object rowData[][], columnNames[];
columnNames = new Object[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
rowData = new Object[][]{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29}};
table = new JTable(rowData, columnNames);
m_model = table.getColumnModel();
pane = new JScrollPane();
m_bar = pane.getHorizontalScrollBar();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
pane.setViewportView(table);
add(pane, BorderLayout.CENTER);
setSize(1024, 768);
setLocationByPlatform(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void moveRight()
{
m_bar.setValue(m_bar.getMaximum() / 3);
}
private void adjust(#SuppressWarnings("unused") ActionEvent event)
{
TableColumn column;
int count;
count = m_model.getColumnCount();
if (m_colIndex >= count)
return;
column = m_model.getColumn(m_colIndex);
column.setPreferredWidth(200);
m_colIndex++;
}
}
At the request of others, I created some simple code to show the problem. With that simple code, it became easy to create the solution.
The solution adds a new method getX() and adds more code to adjust(). getX() computes the left-most position of the column before making any column size changes. This value is stored in the local variable x.
The solution also captures the JScrollBar.getValue() before making any column size changes. This value is stored in the local variable value.
After the column size is changed, then compare x < value. This is true if the left-most position of the column is off the left side of the view. If true, then add the difference in column width to value and call JScrollBar.setValue(). Thus, columns off the left side of the view will cause the scroll bar to be shifted enough to keep the visible columns in view. Columns to the right will simply be adjusted.
Becareful of TableColumn.getMaxWidth(). The width of the column will honor this when setting the width of the column. The code to handle getMaxWidth() is below even though it has no impact to the UI since the original post does nothing not call TableColumn.setMaxWidth().
private void adjust(#SuppressWarnings("unused") ActionEvent event)
{
TableColumn column;
int count, old, next, value, x, max;
count = m_model.getColumnCount();
if (m_colIndex >= count)
return;
x = getX(m_colIndex);
value = m_bar.getValue();
column = m_model.getColumn(m_colIndex);
old = column.getPreferredWidth();
max = column.getMaxWidth();
next = 200;
column.setPreferredWidth(next);
m_colIndex++;
if (x < value)
m_bar.setValue(value + Math.min(next, max) - old);
}
private int getX(int colIndex)
{
TableColumn column;
int result;
result = 0;
while (--colIndex >= 0)
{
column = m_model.getColumn(colIndex);
result += column.getPreferredWidth();
}
return(result);
}

How do I access a specific element of an object of an array in Java?

This program is a work in progress. In it, I created an array of ten objects with five pieces of different data types for each object. I need to find the highest score for q1 which I hoped to accomplish by creating a loop that would compare the variable highScore with each q1 data(8, 3, 10, 8, 9, 7.5, 8.5, 6, 7.5, 7) as the loop went through its cycles, however, I am getting an error message that says "The operator < is undefined for the argument type(s) double, ClassGrade" at the line that is second from the bottom. I don't understand why I am getting this error message, but i suspect that the reason i am getting it is that I am not correctly specifying the specific element that i am trying to access from each object. Any help on the matter would be greatly appreciated.
public class ClassGrade {
public String studentID;
public double q1;
public double q2;
public int mid;
public int finalExam;
public ClassGrade(String studentID, double q1, double q2, int mid, int finalExam)
{
// TODO Auto-generated constructor stub with a few modifications
}
public static void main(String[] args) {
System.out.println("this program works");
double highScore;
highScore = 0;
ClassGrade [] student = new ClassGrade[10];
student[0] = new ClassGrade ("A1", 8, 8.5, 84, 82);
student[1] = new ClassGrade ("B2", 3, 7, 0, 99);
student[2] = new ClassGrade ("C3", 10, 9.5, 92, 84);
student[3] = new ClassGrade ("D4", 8, 8, 89, 86);
student[4] = new ClassGrade ("E5", 9, 10, 83, 91);
student[5] = new ClassGrade ("F6", 7.5, 8.5, 88, 69);
student[6] = new ClassGrade ("G7", 8.5, 0, 81, 52);
student[7] = new ClassGrade ("H8", 6, 8.5, 79, 68);
student[8] = new ClassGrade ("I9", 7.5, 6, 72, 91);
student[9] = new ClassGrade ("J10", 7, 6.5, 58, 77);
for(int i=0; i<10; i++){
if (highScore < student[i])
highScore = student[i];
}
}
}
First, you need to assign your instance variables in you constructor.
You are comparing a double (highscore) with a ClassGrade (student[i]).
You need to create public methods in ClassGrade to return your desired properties.
Accessing an object's properties from an array is just the same way as from a single object. You fetch the object from the array and use '.' to access its public properties or methods. E.g:
array[i].method()
You are comparing the highscore with the actual object in the array, you are comparing a student with grade, so just make some small change - declare a method in your ClassGrade class like getQ1() and then access the q1 from the loop
This should work:
ClassGrade classGrade = (ClassGrade) student[i];
classGrade.method();
Each member of the array is still a ClassGrade, so all you need to do is check its q1 member like you would any other ClassGrade's q1.
for(int i=0; i<10; i++){
if (highScore < student[i].q1)
highScore = student[i].q1;
}
Just think about it as if the array index is part of the name, and it'll make more sense.
// Consider this:
studentZero = new ClassGrade("A1", 8, 8.5, 84, 82);
if (highScore < studentZero)
highScore = studentZero;
// studentZero is not a double. Therefore...
if (highScore < studentZero.q1)
highScore = studentZero.q1;
Alternatively, you can add a getter for q1, and use it.
int score = student[i].getQ1()
if (highScore < score)
highScore = score;
See here for an example of how to access a member of an object in an array:

Make an ArrayList of BufferedImages, Keeps Crashing

SOLVED
I am making an java game. I'm trying to get text converted in BufferedImages that are mine tiles. But every time i get an error and i don't know what is wrong.
I hope you can help me.
package my.tdl.main;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import my.project.gop.main.SpriteSheet;
import my.project.gop.main.loadImageFrom;
public class Font {
private static String chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ.,?!:'1234567890 ";
public ArrayList<BufferedImage> msg_img = new ArrayList<BufferedImage>();
public static SpriteSheet text = new SpriteSheet();
public Font(String msg, Color colour) {
text.setSpriteSheet(loadImageFrom.LoadImageFrom(Main.class, "textSheet.png"));
msg.toUpperCase();
System.out.println(msg);
System.out.println(msg.length());
for (int i = 0; i <= msg.length() + 1; i++) {
System.out.println(i);
int charIndex = chars.indexOf(msg.charAt(i));
System.out.println(chars.charAt(charIndex));
if (charIndex > 0) {
System.out.println(charIndex * 16 + ", 0, 16, 16");
BufferedImage image = text.getTile(charIndex * 16, 0, 16, 16);
Graphics2D g = image.createGraphics();
g.setColor(colour);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
msg_img.add(image);
}
}
}
public ArrayList<BufferedImage> getMsg_img() {
return msg_img;
}
}
this is the output:
STARTGAME
9
0
S
304, 0, 16, 16
1
T
320, 0, 16, 16
2
A
16, 0, 16, 16
3
R
288, 0, 16, 16
4
T
320, 0, 16, 16
5
G
112, 0, 16, 16
6
A
16, 0, 16, 16
7
M
208, 0, 16, 16
8
E
80, 0, 16, 16
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 9, Size: 9
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at my.tdl.gamestate.GameStateButton.render(GameStateButton.java:87)
at my.tdl.gamestates.MenuState.render(MenuState.java:38)
at my.tdl.gamestate.GameStateManager.render(GameStateManager.java:22)
at my.tdl.gameloop.Gameloop.render(Gameloop.java:37)
at my.project.gop.main.GameLoop.run(GameLoop.java:73)
at java.lang.Thread.run(Unknown Source)
I'm trying to convert the string="STARTGAME"
Sorry for the bad enlish.
if you need more of the code send me a message and i will send you it.
I solved it myself. I did a stupid thing and putted =< in the GameStateButton class.
greetings, bjkalk
The line
for (int i = 0; i <= msg.length() + 1; i++) {
Should read
for (int i = 0; i < msg.length(); i++) {
Otherwise you will always read the 10th element (element nine) in a 9 element message. Remember the 9 elements are numbered 0 to 8. In fact with the +1 you will be looking for the 11th element.
By the way I also noticed that you are doing the following call and throwing away the result.
msg.toUpperCase();
perhaps you intended
msg = msg.toUpperCase();

NumberFormatException trying to parse " 66" to an integer

So i have this slice of code that reads text from a csv file where nums[] goes throughout the file and stores the number of a said student, and grades[][] goes through and stores each of their grades:
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] stuff = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
stuff[i] = line.split.(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(stuff[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<11; y++){
grades[x][y] = Integer.parseInt(stuff[x][y]);
}
}
The problem is that numbs works wonderfully, but grades cant store any value that is past the first column of data. If I set grades [x][y] = stuff[any number] [0] it will run, but if I try to go past 0 in the rows, I error terminate.
Part of data file:
1, 66, 82, 85, 87, 65, 80, 97, 75, 68, 72
2, 70, 63, 75, 62, 84, 65, 67, 95, 81, 96
3, 100, 98, 73, 78, 69, 75, 97, 66, 61, 90
4, 75, 62, 79, 78, 87, 73, 74, 76, 63, 84
5, 81, 90, 80, 66, 75, 96, 73, 77, 66, 87
Stack Trace:
java.lang.NumberFormatException: For input string: " 66"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
Fixed Code ( I apologize, I did not copy the code verbatim and included a few extra errors in it)
public static void main(String[] args)throws FileNotFoundException
{
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] values = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
values[i] = line.split(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(values[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<10; y++){
grades[x][y] = Integer.parseInt(values[x][y+1].trim());
}
}
You aren't getting rid of the whitespace between tokens.
Make sure to clear it, preferably with String#trim()
Integer.parseInt(stuff[x][0].trim());
For the record, I'd also look to use better names than stuff.
Also, you're going to get an index out of bounds when you fix those other errors:
for( int y = 0; y < 11; y++ )
grades[x][y] = Integer.parseInt( stuff[x][y] );
All your array indexes go to 10, which in Java means 0 through 9. y here will go to 10, so boom out of bounds.
Considering the syntax errors pointed out in the comments, please in the future copy and paste the EXACT code you are using. It'll be no good if we are debugging different code than what you are actually using.

Passing parameters from method to main

I can't seem to figure out what my parameters should be for my method "public static int[][] sellSeatByPrice". I need to prompt the user for a price (of a seat), then figure out if that price is taken (if it = 0) and if not, assign it the value 0.
Below is my code, help please!
import java.util.Scanner;
/**
* Write a description of class A10_TheaterSeating here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class A10_TheaterSeating
{
public static void main(String args[])
{
System.out.println("***Welcome to the Ticket Choice App!***");
System.out.println();
int[][] theaterSeats = //set values in seating chart array
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{20, 20, 30, 30, 40, 40, 30, 30, 20, 20},
{20, 30, 30, 40, 50, 50, 40, 30, 30, 20},
{30, 40, 50, 50, 50, 50, 50, 50, 40, 30}
};
int[][] seats = theaterSeats;
printArray(seats); //print the seating chart
System.out.println();
//Defining variables
String str = "";
String input = "";
while (!input.equalsIgnoreCase("Q"))
{
System.out.print("Select 'S' to pick a seat, 'P' choose a price or 'Q' to quit: ");
Scanner in = new Scanner(System.in);
input = in.next();
if (input.equalsIgnoreCase("S"))
{
System.out.print("Enter row and seat number desired: ");
int row = in.nextInt();
int seat = in.nextInt();
System.out.println();
sellSeatByNumber(seats, row, seat);
printArray(seats);
System.out.println();
}
else if (input.equalsIgnoreCase("P"))
{
System.out.print("Enter price of seat desired: ");
int price = in.nextInt();
System.out.println();
sellSeatByPrice(seats, row, seat, price);
printArray(seats);
System.out.println();
}
}
System.out.println();
System.out.println("Thank you for choosing the ticket choice app.");
System.out.println();
}
public static void printArray(int[][] currSeat)
{
final int ROWS = 9;
final int COLUMNS = 10;
for(int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
System.out.print(currSeat[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] sellSeatByNumber(int[][] seats, int row, int seat)
{
if (row <= 0 || row > 9)
{
if (seat <= 0 || seat > 10)
{
System.out.print("Please enter a valid row and seat: ");
}
}
if (seats[row][seat] == 0)
{
System.out.print("That seat is taken. Please select another seat: ");
}
else
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
public static int[][] sellSeatByPrice(int[][] seats, int row, int seat, int price)
{
if (seats[row][seat] = price)
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
}
Your parameters seem fine - the internal logic and syntax is incorrect.
Since you're using static methods, and passing along the seat matrix, that is okay - but you have to check that the values being passed in are inside the bounds of your matrix - or you will get exceptions on them.
For instance, you don't check the bounds in sellSeatByPrice(). You really should do that, or a bogus row/seat combination could blow your program up.
It's also the case that the comparison given is incorrect:
if (seats[row][seat] = price)
should really be
if (seats[row][seat] == price)
as = is assignment, and == is primitive comparison.
Furthermore, in sellSeatByNumber(), you can still run into issues since an out of bounds row/seat combo will still blow up. You do check the bounds - kudos - but you don't return anything if they're outside of those bounds. In all reality, an IllegalArgumentException should be raised if they're stepping out of bounds, or you can return the matrix unmodified (which may be more straightforward).

Categories

Resources