How to do right click table row on netbeans? - java

into something like this when I right click the row.after I clicked view profile it will popup and new jFrame and display his profile. i am using GUI builder. sorry for being noob. i'm still beginner.it's hard to find on google how to do right click thing.
UPDATE2
I created the menu now but how to get the Student ID cell only... this is my code
JMenuItem item = new JMenuItem("View Profile");
JMenuItem item2 = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(studentList.this, "Testing");
}
});
jPopupMenu1.add(item);
jPopupMenu1.add(item2);
and on my MouseReleased
private void tableMouseReleased(java.awt.event.MouseEvent evt) {
int r = table.rowAtPoint(evt.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
int rowindex = table.getSelectedRow();
if (rowindex < 0) {
return;
}
if (evt.isPopupTrigger() && evt.getComponent() instanceof JTable ) {
jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
}
}

The easiest way would be to use JComponent#setComponentPopupMenu
You will also want to take a look at How to use menus

Related

can't access addActionListener method inside the createCell method in the table model

i have created a table and in one of the rows there's an evaluate button and an image button once u click on one of them an Action should happen but the problem is once i created an Action Listener inside the createCell method it doesn't seem to function once i click
Object[][] rows = new Object[articles.size()][];
for (int iter = 0; iter < rows.length; iter++) {
rows[iter] = new Object[]{
articles.get(iter).getName(),
0,
articles.get(iter).getDescription(),
articles.get(iter).getLabel(),
articles.get(iter).getQuantity(),
articles.get(iter).getRating(), 0
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "Image", "label", "quantity", "rating", "rate"}, rows);
Table table = new Table(model) {
#Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Button eval = new Button("Evaluate");
Button img = new Button("See image");
if (row > -1 && column == 2) {
System.out.println("Value="+value.toString());
return img;
}
if (row > -1 && column == 6) {
return eval;
}
eval.addActionListener((ActionListener) (ActionEvent evt) -> {
System.out.println("click on eval");
});
img.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("click on img");
}
});
return super.createCell(value, row, column, editable);
}
};
add(table);
You have this:
if (row > -1 && column == 6) {
return eval;
}
Before the code that adds the action listener so that code isn't reached.
I suggest running in the debugger and placing breakpoint, this helps track issues such as this quickly.

Disable Buttons on JAVA but leave unique button alone

According to my previous question here:
Remove a Button with same text when clicked
I need that the only buttons that appearing more then one will disappearing while clicking on them
Problem is when clicking on the "Unique" ones ( see picture ), they will disappear also.
My code:
private String namesArr[] = {"Yakir","Yarden","Igor","Maoz","Moshe","Israel","Tal","Haim","Nati","Mor","Daniel","Idan"};
private Button buttonArr[] = new Button[namesArr.length];
private Font font;
public StudentsGUI(String caption) {
super(caption);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
this.setLayout(new GridLayout(3,3));
font = new Font("Ariel",Font.BOLD,35);
for(int i=0;i<namesArr.length;i++) {
buttonArr[i] = new Button(" "+namesArr[(int)(Math.random()*namesArr.length)]);
buttonArr[i].setFont(font);
buttonArr[i].addActionListener(this);
this.add(buttonArr[i]);
}
setLocation(800,500);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) {
this.remove(buttonArr[i]);
pack();
}
}
}
}
The picture to help you understand:
So if clicking on "Idan", witch is a unique name nothing will happen as it only have one instance, but if clicking on "Maoz" all the buttons with "Maoz" title will disappear ( this already happening )
using collections as per #Freddy's answer should be better. However if you're to stick with arrays, something like below should do it (haven't tested it though)
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
int counter = 0;
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) counter++;
if (count > 1) {
for(int j=0; j<buttonArr.length; j++) {
if (buttonArr[j].getLabel().equals(btnText))
this.remove(buttonArr[j]);
}
}
}
pack();
}
}
You mean something like this (code may have syntax errors)?
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
List<Button> btnList = new ArrayList<Button>();
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) {
btnList.add(buttonArr[i]);
//this.remove(buttonArr[i]);
//pack();
}
}
if (btnList.size() > 1) {
for (Iterator<Button> it = btnList.iterator(); it.hasNext()) {
this.remove(it.next());
}
pack();
}
}
}

Deselect a TableItem after clicking in an empty slot in the table

I have a table with many TableItems (Not a tableViewer), when I click on one of the table Items it get selected . The only way to deselect it is by selecting another TableItem. I want to implement a way to deselect The Table selection when The user click on the table Where there is no TableItems, or when ReSelecting the same TableItem.
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if(e.item != ItemSelectioner ) {
ItemSelectioner = (TableItem)e.item;
// Blabla
}else {
ItemSelectioner = null;
table.deselectAll();
//blabla
}
}
});
As you can see, am using a selectionEvent which I think is the probleme, and using:
e.doit = false;
didn't work also.
Selection events are not generated for the empty parts of the table so you can't use a selection listener to do this.
You can use a mouse down listener and check if there is a table item at the mouse location:
table.addListener(SWT.MouseDown, event -> {
TableItem item = table.getItem(new Point(event.x, event.y));
if (item == null) { // No table item at the click location?
table.deselectAll();
}
});
To clear the selection the second time an item is clicked use something like this:
table.addListener(SWT.Selection, new Listener()
{
private int lastSelected = -1;
#Override
public void handleEvent(final Event event)
{
final int selectedIndex = table.getSelectionIndex();
if (selectedIndex < 0) {
lastSelected = -1;
return;
}
if (selectedIndex == lastSelected) {
table.deselect(selectedIndex);
lastSelected = -1;
}
else {
lastSelected = selectedIndex;
}
}
});

How to check if any button in JPanel is clicked by a user

I've been making a bus booking project and I've made a booking page.
The JPanel named PanelSeat and it contains buttons (about 36 buttons) inside.
I want to check if any button inside JPanel is clicked, then disable the button and finally if a user clicks util 3 buttons, it will be stopped or a user can't click it anymore.
This is the code I've written so far:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I check if button has been clicked?
Since you want to count how many times a button was pressed, and then disable it with counts involved I would suggest that you wrap the Jbutton class in order to make performing those tasks easier, this solution is generally better
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
and this solution is based on your code
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
Add ActionListener to JButton, check example here.

How to disable a specific cell with JPopupmenu's JMenuItem?

I have created a simple JTable and wish to be able to disable a cell after right clicking it and selecting the option in the JPopupMenu with a JMenuItem that will disable the selected cell, here's my MouseAdapter:
private JPopupMenu popup;
private JMenuItem one;
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int r = table.rowAtPoint(e.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
int rowindex = table.getSelectedRow();
if (rowindex < 0)
return;
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
int rowIndex = table.rowAtPoint(e.getPoint());
int colIndex = table.columnAtPoint(e.getPoint());
one = new JMenuItem("Disable this cell");
popup = new JPopupMenu();
popup.add(one);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
Now, I know you can disable particular cell(s) by doing:
DefaultTableModel tab = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
but this is disabling the cell on creation of JTable but I need to disable the cell after creation. Any ideas/leads on how this can be done?
You'll need to modify your TableModel to add storage for the desired editable state of each cell, e.g. List<Boolean>. Your model can return the stored state from isCellEditable(), and your mouse handler can set the desired state in your TableModel. You may need the model/view conversion methods mentioned here.

Categories