popmenu item is not responding on click [duplicate] - java

This question already has an answer here:
JPopupMenu is not displayed on right click
(1 answer)
Closed 8 years ago.
I have written this code to add and delete a row in my table using popup menu, but this code neither delete nor add a row to the table when I click respective options (ADD and DELETE) on popup menu, please help.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class B extends MouseAdapter {
JFrame frame = new JFrame();
Object rows[][] = new Object[5][3];
String colums[] = {"A","B","C"};
DefaultTableModel model = new DefaultTableModel(rows,colums);
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
JPopupMenu popup = new JPopupMenu();
JMenuItem item1 = new JMenuItem("ADD");
JMenuItem item2 = new JMenuItem("DELETE");
Object[] row = {"Column 1", "Column 2", "Column 3"};
public static void main(String arg[]) {
new B();
}
B() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
table.addMouseListener(this);
item1.addMouseListener(this);
item2.addMouseListener(this);
popup.add(item1);
popup.add(item2);
table.add(popup);
frame.add(scroll);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent click) {
if(click.getSource()==table && click.getButton()==3)
popup.show(table,click.getX(),click.getY());
else if(click.getSource()==item1)
model.addRow(row);
else if(click.getSource()==item2)
model.removeRow( table.rowAtPoint(click.getPoint()) );
}
}

Instead of comparing objects using == (to compare references of two components) you should use equals method . So change the following from:
click.getSource()==table
To
click.getSource().equals(table)

Related

Questions on a Scrollbar's AdjustmentListener behavior

I modified an exist JTable with Scrollbar example and added an Adjustment Listener and JMenu item for this example.
When the example is executed and the Frame resized affecting the scrollbar or if the scrollbar is moved, the listener is executed as expected. Accessing the menu on the toolbar will fire the Adjustment Listener.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class AdjustmentListener_Example3
{
static int x = 0;
public static void main(String[] argv)
{
JFrame frame = new JFrame();
JTable table = new JTable(data, col);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener()
{
#Override
public void adjustmentValueChanged(AdjustmentEvent event)
{
x++;
System.out.println(x + " : " + event.getValue());
String type = null;
switch (event.getAdjustmentType())
{
case AdjustmentEvent.TRACK:
type = "Track";
break;
case AdjustmentEvent.BLOCK_DECREMENT:
type = "Block Decrement";
break;
case AdjustmentEvent.BLOCK_INCREMENT:
type = "Block Increment";
break;
case AdjustmentEvent.UNIT_DECREMENT:
type = "Unit Decrement";
break;
case AdjustmentEvent.UNIT_INCREMENT:
type = "Unit Increment";
break;
}
System.out.println(" Type: " + type);
}
});
frame.add(scrollPane);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem1 = new JMenuItem("Send Action To Scrollbar");
menuItem1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
AdjustmentListener[] adjustmentListeners = scrollPane.getVerticalScrollBar().getAdjustmentListeners();
adjustmentListeners[0].adjustmentValueChanged(new AdjustmentEvent(scrollPane.getVerticalScrollBar(), 0, 0, 0));
}
});
menu.add(menuItem1);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,20, 500,500);
frame.setVisible(true);
}
static String [][] data = {{"001","vinod","Bihar","India","Biology","65","First"},
{"002","Raju","ABC","Kanada","Geography","58","second"},
{"003","Aman","Delhi","India","computer","98","Dictontion"},
{"004","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"005","vinod","Bihar","India","Biology","65","First"},
{"006","Raju","ABC","Kanada","Geography","58","second"},
{"007","Aman","Delhi","India","computer","98","Dictontion"},
{"008","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"009","vinod","Bihar","India","Biology","65","First"},
{"010","Raju","ABC","Kanada","Geography","58","second"},
{"011","Aman","Delhi","India","computer","98","Dictontion"},
{"012","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"013","vinod","Bihar","India","Biology","65","First"},
{"014","Raju","ABC","Kanada","Geography","58","second"},
{"015","Aman","Delhi","India","computer","98","Dictontion"},
{"016","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"017","vinod","Bihar","India","Biology","65","First"},
{"018","Raju","ABC","Kanada","Geography","58","second"},
{"019","Aman","Delhi","India","computer","98","Dictontion"},
{"020","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"021","vinod","Bihar","India","Biology","65","First"},
{"022","Raju","ABC","Kanada","Geography","58","second"},
{"023","Aman","Delhi","India","computer","98","Dictontion"},
{"024","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"025","vinod","Bihar","India","Biology","65","First"},
{"026","Raju","ABC","Kanada","Geography","58","second"},
{"027","Aman","Delhi","India","computer","98","Dictontion"},
{"028","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"029","vinod","Bihar","India","Biology","65","First"},
{"030","Raju","ABC","Kanada","Geography","58","second"},
{"031","Aman","Delhi","India","computer","98","Dictontion"},
{"032","Ranjan","Bangloor","India","chemestry","90","Dictontion"}};
static String col[] = {"Roll","Name","State","country","Math","Marks","Grade"};
}
Questions :
Using a JButton, if no Listener is created nothing happens, but even if the AdjustmentListener was never added in this example, the scrollbars would work. This indicates the scrollbars already have a default listener to handle the functionality.
Is the Adjustment listener a means to add additional listeners to the scrollbar instead of overriding the existing one?
Is the Adjustment listener primarily to execute other non-scroll bar behavior anytime the scrollbar is moved?
Why isn't the #override annotation required along with a call to super within the custom listener?

Is there a way to create a JList in a modal dialog?

I have a JFrame already visible. The user can load a saved session.
The idea is to create a JList, so the user can load the chosen session and the frame can be updated.
The code bellow get a list of String and add them to the list.
DefaultListModel model = new DefaultListModel();
JList list=new JList(model);
JScrollPane pane = new JScrollPane(list);
try {
for (String part : Utils.getSessions()) {
model.addElement(part);
}
} catch (IOException e1) {
e1.printStackTrace();
}
The next step : display the step.
What I found : add pane to the current frame
My Hope: display the list in a modal dialog
Is there a way to create a JList in a modal dialog?
It turns out that JOptionPane already has list selection built on, no need to work with your own JList.
Here's the call to use: JOptionPane.showInputDialog
Here's a trivially simple example: Displaying a dialog with a list of choices
Here's a fully working example that lets you choose a font name (using the handy-dandy font list snippet given by Andrew in the comments).
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ListChooserDemo extends JFrame {
JTextPane textPane = new JTextPane();
String lastChoice = null;
public ListChooserDemo() {
setTitle("List Chooser Demo");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(new Dimension(500, 500));
add(new JScrollPane(textPane), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
add(buttonPanel, BorderLayout.SOUTH);
JButton b = new JButton("Choose it!");
textPane.setText("Click the button...");
b.addActionListener(this::doChooseFont);
buttonPanel.add(b);
}
public void doChooseFont(ActionEvent e) {
// a handy way to get a nontrivial list of choices for a demo
String[] choices = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
// Show a list of options with no effort on our part.
String input = (String) JOptionPane.showInputDialog(
this, // optional reference to frame/window or null
"Choose a font...", // prompt displayed over list
"Font Chooser", // title
JOptionPane.QUESTION_MESSAGE, // message style
null, // Use default icon for message style
choices, // array of choices
lastChoice); // initial choice or null
if (input == null) {
// Handle case when user canceled, didn't select anything, or hit escape
textPane.setText(textPane.getText() + "\r\nCanceled!");
} else {
// Do stuff that happens when a selection was made
textPane.setText(textPane.getText() + "\r\nSelected " + input);
lastChoice = input;
}
}
public static final void main(String[] args) {
// Run in GUI thread
SwingUtilities.invokeLater(() -> {
ListChooserDemo frame = new ListChooserDemo();
// Center in screen and show
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
frame.setVisible(true);
});
}
}
You can use JOptionPane's ability to display any component. Use
JOptionPane.showMessageDialog(frame, list);
to get a modal dialog displaying your JList. You can further customize this dialog by adding more parameters, see here for more information.
A full example:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String[] options = new String[] {"a", "b", "c"};
JList<String> list = new JList<>(options);
// Shows the dialog
JOptionPane.showMessageDialog(frame, list);
// Do whatever you want with the selection, for example
frame.add(new JLabel(list.getSelectedValue()));
frame.pack();

ActionPerformed being called when JComboBox is clicked in Jtable cell

I am using JComboBox in Jtable cell. When I click on the JComboBox and select a value from it, it calls the ActionPerformed fuction. Till here it is working fine but as soon as I click on the JComboBox again, it calls the ActionPerformed function, which it should not. What I want is, to call the ActionPerformed function when the item is selected in the JComboBox. In other words it should work as it worked for the first time when the item was selected from the JComboBox and then the ActionPerformed function was called. I cannot figure out why this problem is occurring. Here are the links that I have looked into and I did some other searches also but still could not find any relative answer to the above mentioned problem.
Adding JComboBox to a JTable cell
How to use ActionListener on a ComboBox to give a variable a value
https://coderanch.com/t/339842/java/ComboBox-ItemListener-calling
Here is the code, you can copy paste it and check it.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
public class TableExample implements ActionListener{
JFrame frame;
JComboBox skuNameComboBoxTable;
TableExample() {
frame = new JFrame();
String data[][] = {{"101", "Amit", "Choose"},
{"102", "Jai", "Choose"},
{"101", "Sachin", "Choose"}};
String column[] = {"ID", "Name", "Degree"};
JTable table = new JTable(data, column);
table.setBounds(30, 40, 200, 300);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.setSize(300, 400);
frame.setVisible(true);
String[] array = {"BS(SE)", "BS(CS)", "BS(IT)"};
skuNameComboBoxTable = new JComboBox(array);
skuNameComboBoxTable.addActionListener(this);
TableColumn col = table.getColumnModel().getColumn(2);
col.setCellEditor(new DefaultCellEditor(skuNameComboBoxTable));
}
public static void main(String[] args) {
new TableExample();
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "actionPerformed called");
}
}
Kindly tell me why this problem is occurring and how should I solve it.
Unfortunately, you can't do much when using the DefaultCellEditor - that is how it behaves. Within your code you can add a check to ensure that a change in value occured before handling the event. Something like below:
public void actionPerformed(ActionEvent e) {
if (skuNameSelected == null || skuNameComboBoxTable.getSelectedItem() != skuNameSelected)
JOptionPane.showMessageDialog(null, "actionPerformed called: ");
skuNameSelected = (String) skuNameComboBoxTable.getSelectedItem();
}
You can try using ItemListener and filter your action according to the ItemEvent.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class JComboBoxTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] items = {"One", "Two", "Three"};
JComboBox cb = new JComboBox(items);
cb.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Selected " + e.getItem());
} else {
System.out.println("Deselected " + e.getItem());
}
}
});
frame.add(cb);
frame.pack();
frame.setVisible(true);
}
}
This is happening because you are using the same JComboBox as the DefaultCellEditor for column 2.
Whenever you click a cell from column 2 the ComboBox will change to the value that is on the cell at the moment and that triggers the DESELECT (from the old value) and the SELECT (for the new value). This will only happen if the old value and the new value are not the same.
One way to avoid this is to add a CellEditorListener on the DefaultCellEditor that you are using, like below:
TableColumn col = table.getColumnModel().getColumn(2);
DefaultCellEditor cellEditor = new DefaultCellEditor(skuNameComboBoxTable);
col.setCellEditor(cellEditor);
cellEditor.addCellEditorListener(new CellEditorListener() {
#Override
public void editingStopped(ChangeEvent e) {
System.out.println("Value of combo box defined!");
}
#Override
public void editingCanceled(ChangeEvent e) {
System.out.println("Edition canceled, set the old value");
}
});
This way you will be able to only act when the value has been defined by the ComboBox.
I hope this helps.
You should not be using an ActionListener for this. The combo box uses its own ActionListener to update the TableModel when an item is selected.
So instead you should be listening for changes in the TableModel in order to do your custom code. So you should be using a TableModelListener to listen for changes in the data. However, a TableModelListener can fire an event even if just start and stop editing of the cell which might be a problem for you.
In this case you can use the Table Cell Listener. It will only generate an event when the value in the TableModel has changed.

How to color render a checked combobox component in table in Java Swing?

I have a ComboBox which contains checkbox inside it, placed in a table. Whenever I select the row, the color render is applying only to remaining cells of the table. How to render the "checkedcombobox", so that it can also get selection color matching with other cells in the row of a table.
Here is an example for you:
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxUI;
public class TableEditorExample {
private static final String[] COLS = {"Number", "Type", "Name"};
private static final Object[][] DATA = {{"1", "Book", "Brave new world"}, {"2", "Music", "Smells like a teen spirit"},
{"3", "Film", "Star Wars"}};
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// Nothing
}
JFrame frm = new JFrame("Test combo renderer");
JTable tbl = new JTable(DATA, COLS);
tbl.setRowHeight(20);
JComboBox<String> combo = new JComboBox<>(new String[] {"Book", "Music", "Film"});
combo.setUI(new BasicComboBoxUI());
combo.setBackground(tbl.getSelectionBackground());
combo.setForeground(tbl.getSelectionForeground());
tbl.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(combo));
frm.add(new JScrollPane(tbl));
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}
So, what you need to do is:
combo.setUI(new BasicComboBoxUI());
combo.setBackground(tbl.getSelectionBackground());
combo.setForeground(tbl.getSelectionForeground());
Here is the screenshot of the corresponded program (for Windows):

How to update the cells of a table from a combobox?

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.java.dev.designgridlayout.DesignGridLayout;
import java.io.*;
import net.java.dev.designgridlayout.Tag;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
class table1
{
JFrame JF;
Container C;
JPanel JP;
JLabel creditLabel;
JComboBox credit;
String[] Credit = {"Vasan Phalke", "Pansare", "Anil Kg", "Suresh"};
String[] Names = {"Name", "Qty", "Rate/ Kg", "Rate/Dzn.", "Total Amt."};
JTable table;
DefaultTableModel model;
JScrollPane scrollPane;
public table1()
{
JF = new JFrame();
JP = new JPanel();
C= JF.getContentPane();
JF.pack();
JF.setLocationRelativeTo(null);
JF.setVisible(true);
DesignGridLayout layout = new DesignGridLayout(C);
creditLabel = new JLabel("Credit");
credit = new JComboBox<String>(Credit);
model = new DefaultTableModel(Names,5);
table =new JTable(model){#Override
public boolean isCellEditable(int arg0, int arg1)
{
return true;
}
};
scrollPane= new JScrollPane(table);
layout.row().grid(creditLabel).add(credit);
layout.emptyRow();
layout.row().grid().add(table);
C.add(JP);
}
public static void main(String args[])
{
new table1();
}
}
By clicking on the value of combobox, it should appear in the name column of the table, and what changes should be made to the table for automatic calculation, ie, when i enter qty and rate, total amount should automatically be calculated.
How all these things can be done, please help.
Thanks in advance.
Read the section from the Swing tutorial on How to Use Tables
The tutorial shows you how to use a combo box as an editor for a column in a table. This is what you should be doing instead of having a separate combo box.
To calculate the amount, you need to create a custom TableModel and override the setValueAt() method. Whenever the quantity or rate changes you recalculate the amount.

Categories