How to hide Selection in JList - java

I create several JLists by using DefaultListmModel, so I can add, edit and delete items in those JLists.
How can I hide the selection the user made?
So like the user clicks in JList 1 to edit the value with index 2 by double clicking on the item. So now the item with index value 2 is selected in the UI and it's blue.
My Question is: How can I hide this, so after editing/adding items in the JList, what do I have to do that the item which was selected isn't blue, so that you can't see what you selected before.
clearSelection() isn't working.
My code is the following (I shortened the JOptionPane stuff and the if else part):
for (int i=0; i < StringArray.length; i++) {
DefaultListModel<String> model = new DefaultListModel<String>();
for (int j=0; j < StringArray[i].length; j++) {
model.addElement(StringArray[i][j]);
if((StringArray[i].length -1)== j) {
listbox = new JList<String>(model);
Panel.add(listbox);
listbox.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = listbox.locationToIndex(e.getPoint());
Object[] options = {"Add", "Edit", "Delete"};
//.... JOptionPane
if (ADDING) {
String tmpAddValue = JOptionPane...
model.addElement(tmpAddValue);
}
else if (EDITING) {
String tmpValue = JOptionPane...
model.setElementAt(tmpValue, index);
}
else if (DELETING) {
model.removeElementAt(index);
}
else {
System.out.println("No Button pushed");
}
listbox.clearSelection();
}
}
});
}
}
Thanks

Related

How can I dynamically change the number of items in a JComboBox

private void dropDownMenu(JPanel jp1, String prodId){
int len = storeManager.getInv().getStockAmount(prodId);
int[] nums = new int[len];
String[] numPossible = new String[len];
for (int i=0; i<len; i++){
nums[i] = i+1;
}
for (int i=0; i<len; i++){
numPossible[i] = String.valueOf(nums[i]);
}
JComboBox<String> cb = new JComboBox<String>(numPossible);
JButton okButton = new JButton("Add To Cart");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product p1 = storeManager.getInv().getProd(prodId);
String quan = (String) cb.getSelectedItem();
int quantity = Integer.parseInt(quan);
if (quantity > storeManager.getInv().getStockAmount(prodId)) {
System.out.println("Not Enough Stock.");
} else {
storeManager.getCart().addToCart(p1, quantity);
storeManager.getInv().removeStockAmount(prodId, quantity);
//update the dropdown menu here
}
}
});
jp1.add(cb);
jp1.add(okButton);
}
Essentially what i am looking for is that whenever i select a number from the drop down menu, i want the number of items in the menu to be reduced by the amount that was added to cart. for example if i add 5 to cart then i want the dropdown menu to go from allowing me to choose 10 to 5 only.
Image of GUI
As a thought...Instead of doing all these conversions from integer to string and string to back to integer in order to fill your combo box, why not just have a combo box of Integer? You're dealing initially with integer quantity values anyways:
JComboBox<Integer> cb = new JComboBox<>();
int len = storeManager.getInv().getStockAmount(prodId);
for (int i = 1; i <= len; i++) {
cb.addItem(i);
}
cb.setSelectedIndex(0);
Your action listener might look something like this now:
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product p1 = storeManager.getInv().getProd(prodId);
int quantity = (int) cb.getSelectedItem();
/* This 'if' statement below would be moot if the Combo-Box
is properly updated unless editing is allowed in the combo
which in this case...disable that feature. */
if (quantity > storeManager.getInv().getStockAmount(prodId)) {
System.out.println("Not Enough Stock.");
} else {
storeManager.getCart().addToCart(p1, quantity);
len = storeManager.getInv().removeStockAmount(prodId, quantity);
cb.removeAllItems();
for (int i = 1; i <= len; i++) { cb.addItem(i); }
cb.setSelectedIndex(0);
}
}
});
Possibly better yet would be to utilize the JSpinner component instead of a Combo Box. A drop-down list in this use case always seems a bit obtrusive in my opinion.

Changing a String array for a JComboBox depending on another value in another ComboBox

I'm trying to create a Combobox, where, when a value is changed in the first Combobox, in this case which is "FlightNumber", to change the String array in another Combobox in the same window, which is "Baggage" depending on which value is selected in the FlightNumber Combobox.
Every time I try to do this, the program hangs after selecting a Flight number from the drop down menu.
private void jComboBox_flightNumberActionPerformed(java.awt.event.ActionEvent evt) {
int number = Integer.parseInt((String)jComboBox_flightNumber.getSelectedItem());
boolean found = false;
int baggageSize = 0;
int counter;
System.out.println(this.flightList.size());
System.out.println(number);
for(counter = 0; counter < this.flightList.size() || !found; counter++){
Flight flight = this.flightList.get(counter);
if(flight.getFlightID() == number) {
found = true;
baggageSize = flight.getBaggage();
System.out.println(baggageSize);
}else{
found = false;
}
}
String [] baggageLength = new String[baggageSize];
for(int x = 0;counter < baggageLength.length; x++) {
baggageLength[counter] = Integer.toString((x+1));
}
this.baggageSize = baggageLength;
jComboBox_baggage.setModel(new javax.swing.DefaultComboBoxModel<>(this.baggageSize));
jComboBox_baggage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_baggageActionPerformed(evt);
}
});
}

Why are all my ActionListener's added to JButtons in a loop identical?

Ok so I am trying to make a chess game in swing. I have a program that creates a 2d array of JButton's 8x8. I then create them all in a loop doing stuff like going back and forth between white/black and adding an action event. The problem i am having is that each button has the same action event and it is the event that is created last I.E. button on Row 8 column H is the action listener for all of the buttons in the array. Here is a snippet of code that is where I am creating the buttons and adding them.
I also have an Enum Columns that just goes from int to character 1 to H for example. selectPosition and targetPosition are objects that have two members columns and rows.
public void initializeGui(boolean isWhite) {
boolean shouldBeWhite = true;
for(int i = 0; i< 8; i++){
for(int j = 0; j < 8; j++){
column = i+1;
row = j+1;
JButton square = new JButton();
square.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final int thisRow = row;
final int thisColumn = column;
selectPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
selectPosition.setRow(thisRow);
if(isSelecting){
System.out.print("Selecting square to move. Row: " + thisRow + " Column: " + Columns.getColumnsFromInt(thisColumn));
selectPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
selectPosition.setRow(thisRow);
} else{
System.out.print("Targeting square to move to. Row: " + thisRow + " Column: " + Columns.getColumnsFromInt(thisColumn) + "\n");
targetPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
targetPosition.setRow(thisRow);
}
System.out.println("");
isSelecting = !isSelecting;
}
});
if(shouldBeWhite){
square.setBackground(Color.WHITE);
shouldBeWhite = false;
}else{
square.setBackground(Color.BLACK);
shouldBeWhite = true;
}
if (j == 7){
shouldBeWhite = !shouldBeWhite;
}
chessBoardSquares[i][j] = square;
gui.add(chessBoardSquares[i][j]);
}
}
if(isWhite){
setInitialPiecesWhiteStart();
}else{
setInitialPiecesBlackStart();
}
}
Further up as a member of this class are the following:
int column = 0, row = 0;
When I click on any of these buttons i see printed
Selecting square to move. Row: 8 Column: H
Targeting square to move to. Row: 8 Column: H
Selecting square to move. Row: 8 Column: H
Targeting square to move to. Row: 8 Column: H
and so on. My question is why are these buttons all given the same action event? My logic walk through would be something like create the first button set column = i+1 and row = j+1 then add an action listener with an action event that sets the current row/column values to the inner final variables and then prints out the thisRow and thisColumn associated with that action event. Am i overriding the values at the end or do i have the scope wrong? Basically how am i creating these buttons actions listeners incorrectly?
You could...
Use the actionCommand API to pass information between the button and the ActionListener...
JButton btn = new JButton();
btn.setActionCommand(row + "x" + column);
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
//...
}
});
The problem here is you're relying on String parsing to extract the values, which can get messy quickly
You could...
Create a custom ActionListener which takes the values you want to use...
public class SquareActionListener implements ActionListener {
private int column;
private int row;
public SquareActionListener(int row, int column) {
this.row = row;
this.column = column;
}
#Override
public void actionPerformed(ActionEvent e) {
//...
}
}
This de-couples the ActionListener from the rest of the code and provides you the information you need, although, you may need to pass additional information (such as the model) as well for it to work
You could...
Make use of the Action API which is designed to be provide self contained units of work, it's generally a more re-usable solution, but might be a little beyond what you need right now
public class SquareAction extends AbstractAction {
private int column;
private int row;
public SquareAction(int row, int column) {
this.row = row;
this.column = column;
}
#Override
public void actionPerformed(ActionEvent e) {
//...
}
}
This looks alot like the last suggestion, but instead of adding it as the button's ActionListener, you actually apply it to the button directly...
JButton btn = new JButton(new SquareAction(row, column));
The button then uses other properties (which I've not set) to set itself up
I had the same issue when making a tic-tac-toe game. I used each button's hashcode to trace back which button was actually pushed. This is what my button setup looked like:
hashcodes= new ArrayList<Integer>();
for (int i=1;i<=9;i++) {
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setHash(button.hashCode());
testWinner();
testDraw();
}
});
hashcodes.add(button.hashCode());
panel.add(button);
}
}
private void setHash(int hashcode) {
for (int h:hashcodes) {
if (h==hashcode) {
//do stuff
}
}
}
This is my Test class, and it works perfectly.
public class Test extends javax.swing.JFrame {
private javax.swing.JButton[][] buttons;
private final int ROW = 8;
private final int COLUMN = 8;
public Test() {
initComponents();
}
private void initComponents() {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
this.buttons = new javax.swing.JButton[ROW][COLUMN];
this.setLayout(new java.awt.GridLayout(ROW, COLUMN));
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
final int row = i;
final int column = j;
buttons[i][j] = new javax.swing.JButton(
String.format("Button %d-%d", i, j));
buttons[i][j].addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// System.out.println(
// String.format("You have just pressed the button at row %d and column %d", row, column));
javax.swing.JOptionPane.showMessageDialog(
Test.this, String.format("You have just pressed the button at row %d and column %d", row, column));
}
});
this.add(buttons[i][j]);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Test().setVisible(true);
}
}

Add selectListener to table in SWT

In SWT I want to show a Table with 4 columns: 1st a number, 2nd a String, 3rd a checkBox and 4th a radio button.
Once all rows are set, I want to add another row for 3rd column (check all/none), and 4th column (clean radio selected).
This is the code (It compiles, but I haven't tested, yet):
//Create table
Table table = new Table(layoutComposite, SWT.BORDER);
table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
String[] tableItems = new String[] {"", "Player", "Show", "Highlight"};
int[] tableSizes = new int[] {30, 150, 20, 20};
// Header Columns and sizes for table
for (int i = 0; i < tableItems.length; i++) {
TableColumn tableColumn = new TableColumn(table, SWT.NONE);
tableColumn.setText(tableItems[i]);
tableColumn.setWidth(tableSizes[i]);
}
table.setHeaderVisible(true);
table.setLinesVisible(false);
// Create items (void)
for (int i = 0; i < positions.size(); i++) {
new TableItem(table, SWT.NONE);
}
TableItem[] items = table.getItems();
// Check and Radio Buttons
Button[] checks = new Button[items.length + 1];
Button[] radios = new Button[items.length + 1];
// Add elements
for (int i = 0; i < items.length + 1; i++) {
// Pos and Player only in first items.length rows
if (i < items.length) {
items[i].setText(0, String.valueOf(positions.get(i).getPos()));
items[i].setText(1, positions.get(i).getPlayer().getPlayerName());
}
TableEditor editorCheck = new TableEditor(table);
checks[i] = new Button(table, SWT.CHECK);
checks[i].pack();
checks[i].setSelection(true);
editorCheck.minimumWidth = checks[i].getSize().x;
editorCheck.setEditor(checks[i], items[i], 2);
TableEditor radioCheck = new TableEditor(table);
radios[i] = new Button(table, SWT.RADIO);
radios[i].pack();
radios[i].setSelection(false);
radioCheck.minimumWidth = radios[i].getSize().x;
radioCheck.setEditor(radios[i], items[i], 3);
}
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if (e.detail == SWT.CHECK) {
if (e.item instanceof Button) {
// TODO:
// Get checked item selected
// If last row (ie: == checks[items.length]), select or unselect all check related buttons
//
//((Button)e.item).get // Problem here!!!!
}
}
else if (e.detail == SWT.RADIO) {
// TODO:
// Get radio selected
// If last row (ie: radios[items.length]), clean selected item (if any)
}
// TODO Auto-generated method stub
super.widgetSelected(e);
}
});
Now I need to add a Listener over check and radio buttons. My question is: How do I know which check or radio button is selected?
should I do something like this?
for (int i = 0; i < checks.length; i++) {
if (e.item == checks[i]) { // found selected
if (i == checks.length -1 ) { // last one
// Select or unselect all
}
// doStuff () ;
}
}
If this is correct, Is there an easy way to know which is selected? If not, how can I do it?
Any other hint will be very welcome.
you can add a selection listener to each checkbox and radio button after you create them:
checks[i].addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent event) {
// your code here...
// get the current checkbox/radio button from the event:
Widget src = event.widget;
// ...
}
});
do the same with radio buttons:
radios[i].addSelectionListener(...);
i hope this helps you. enjoy.

How to identify ID of Labels in Java

I have created 9 JLabels by array. And it has common Event Listener with method of mouseClicked(MouseEvent src){... }, here i am finding problem is, how can I identify which JLabel is clicked?
Say, if label[0] is clicked then I want to show "Label-0 is clicked",
if label[1] is clicked then I want to show "Label-1 is clicked"
Can I perform this? if yes then How?
NOTE :- I found some answer stating that add Custom 'id' Property, I would but first, I prefer if there is any default method exist.
Add Label
JPanel pnl = new JPanel(new FlowLayout());
dd.add(pnl);
addlistener();
for (int i = 0; i < 10; i++) {
pnl.add(lbl[i] = new JLabel("" + i));
lbl[i].addMouseListener(listern);
}
Listener
public void mouseEnter(MouseEvent me) {
System.err.println("Hi");
me.getComponent();
if(me.getSource() instanceof JLabel){
System.out.println("lable"+ ((JLabel)me.getSource()).getText());
}
}
You could loop the array comparing the source of the event to each element in the array...
for (int index = 0; index < myLabelArray.length; index++) {
if (myLabelArray[index].equals(src.getSource())) {
System.out.println("Label-" + index + " was clicked");
break;
}
}
Or you could "name" each label...
JLabel[] myLabelArray = new JLabel[9];
for (int index = 0; index < 9; index++) {
JLabel label = new JLabel("...");
label.setName(Integer.toString(index));
label.addMouseListener(commonMouseListener);
myLabelArray[index] = label;
}
Then in your mouse listener...
public void mouseClicked(MouseEvent evt) {
System.out.println("Label-" + ((JLabel)evt.getSource()).getName() + " was clicked");
}
Or you could use a Map instead of an array or a List...

Categories

Resources