Results 1 to 6 of 6
  1. #1
    X75TIGER75X is offline Member
    Join Date
    Apr 2012
    Posts
    19
    Rep Power
    0

    Question Need help with clickable JButton in JTable that invokes method in the main GUI class

    Hi Java Forums!

    I am almost finished with my project and I ran into a problem. I need your help to get around it. I am building a GUI software with a table that contains Strings and Buttons that are clickable and has ActionListener in them. I followed this tutorial, JButtons in a JTable. It works pretty well except that the tutorial did not tell me how to invoke a method from the main GUI class. I have written a compilable example code that illustrates my problem. You can try them out yourself.

    [Java] mainGUI.java - Pastebin.com

    [Java] customTable.java - Pastebin.com

    [Java] JTableButtonMouseListener.java - Pastebin.com

    [Java] JTableButtonRenderer.java - Pastebin.com

    mainGUI.java is the main class. To use it, simply run it without command-line arguments. If you want to see example of my desired result, type something in command-line argument like java mainGUI example.

    If you toy around with it enough, you should be able to see the problem. I want an actionlistener from customTable.java to invoke action method in mainGUI.java. How can I achieve that?

    Thanks in advance!

    P.S. I'm sorry if this topic is not suitable for Advanced Java section in this forum.

    EDIT: Some of you seem to not want to copy-paste or download my example code from website. I'll just post here.

    mainGUI.java
    Java Code:
     import java.awt.BorderLayout;
    import javax.swing.border.EmptyBorder;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.UIManager;
    
    public class mainGUI extends JFrame{
    	JPanel panel;
    	JTable table;
    	Object[][] list;
    	
    	public mainGUI(boolean example){
    		
    		try{
    			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    		}catch(Exception e){
    			//Do nothing
    		}
    		
    		panel = new JPanel(new BorderLayout());
    		update();
    		panel.add(new JScrollPane(table));
    		panel.setBorder(new EmptyBorder(2, 2, 2, 2));
    		
    		this.add(panel, BorderLayout.CENTER);
    		
    		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		this.setTitle("Example");
    		this.setSize(200,300);
    		this.setVisible(true);
    		
    		if(example){ action(2); } //Example
    		
    	}//End of constructor
    	
    	private JTable buildTable(){
    		String[] columns = {"Name", "Number", "Action"};
    		list = new Object[5][3]; //Assume there is 5 values on the list
    		list[0][0] = "Fred";
    		list[1][0] = "Allison";
    		list[2][0] = "John";
    		list[3][0] = "Kelly";
    		list[4][0] = "Jamie";
    		for(int i = 0; i < 5; i++){
    			list[i][1] = Integer.toString((int)(Math.random() * 100 + 1));
    			if(i % 2 == 0){
    				list[i][2] = new JButton("Activate Me");
    			}else{
    				list[i][2] = new JButton("Activate!");
    			}
    		}//End of for loop
    		
    		//JTable
    		JTable table = new JTable(new customTable(list, columns));
    		
    		//Column Buttons
    		TableCellRenderer buttonRenderer = new JTableButtonRenderer();
    		table.getColumn("Action").setCellRenderer(buttonRenderer);
    		table.addMouseListener(new JTableButtonMouseListener(table));
    		
    		//Misc
    		table.setFillsViewportHeight(true); 
    		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    		
    		//Return
    		return table;
    	}//End of buildTable method
    	
    	private void update(){
    		table = buildTable();
    		panel.removeAll();
    		panel.updateUI();
    		panel.add(new JScrollPane(table));
    	} //End of update method
    	
    	public void action(int selection){
    		String message = list[selection][0] + " has number of " + list[selection][1];
    		JOptionPane.showMessageDialog(this, message);
    		update();
    	}//end of action method
    	
    	public static void main(String[] args){
    		boolean example = false;
    		if(args.length != 0){
    			example = true;
    		}
    		new mainGUI(example);
    	}//End of main method
    } //End of class
    customTable.java
    Java Code:
     import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.table.DefaultTableModel;
    
    public class customTable extends DefaultTableModel{
    	Object[][] data;
    	
    	public customTable(Object[][] data, String[] column){
    		super(data, column);
    		this.data = data;
    	}//End of constructor
    	
    	public boolean isCellEditable(int row, int cols){
    		return false;
    	}//End of isCellEditable method
    	
    	public Object getValueAt(final int rowIndex, final int columnIndex){
    		switch(columnIndex){
    			case 0: return (String)data[rowIndex][columnIndex];
    			case 1: return (String)data[rowIndex][columnIndex];
    			case 2: final JButton button = new JButton(((JButton)data[rowIndex][columnIndex]).getText());
    					button.setBorder(null);
    					button.addActionListener(new ActionListener(){
    						public void actionPerformed(ActionEvent ae){
    							System.out.println("Clicked at row " + rowIndex + " and column " + columnIndex);
    							/*  I want this table to invoke action method and gives the row index number */
    							//mainGUI.action(rowindex); //Calls the action method in mainGUI class
    						}//End of actionPerformed method
    					}); //End of anonymous class
    					data[rowIndex][columnIndex] = button;
    				return button;
    			default: return "Error";
    		}//End of switch statement
    	}//End of getValueAt method
    }//End of class
    JTableButtonMouseListener.java
    Java Code:
     import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JTable;
    
    public class JTableButtonMouseListener extends MouseAdapter{
    	private final JTable table;
    	public JTableButtonMouseListener(JTable table){
    		this.table = table;
    	}//End of constructor
    	@Override
    	public void mouseClicked(MouseEvent e){
    		int column = table.getColumnModel().getColumnIndexAtX(e.getX());
    		int row = e.getY()/table.getRowHeight();
    		if(row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0){
    			Object value = table.getValueAt(row, column);
    			if(value instanceof JButton){
    				((JButton)value).doClick();
    			}
    		}
    	}//End of mouseClicked method
    }//End of class
    JTableButtonRenderer.java
    Java Code:
     import java.awt.Component;
    import javax.swing.JButton;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.UIManager;
    
    public class JTableButtonRenderer implements TableCellRenderer{
    	@Override
    	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
    		JButton button = (JButton)value;
    		if(isSelected){
    			button.setForeground(table.getSelectionForeground());
    			button.setBackground(table.getSelectionBackground());
    		}else{
    			button.setForeground(UIManager.getColor("Button.foreground"));
    			button.setBackground(UIManager.getColor("Button.background"));
    		}
    		return button;
    	}//End of getTableCellRendererComponent method
    }//End of class
    Last edited by X75TIGER75X; 08-29-2013 at 01:21 PM.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: Need help with clickable JButton in JTable that invokes method in the main GUI cl

    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem. Don't forget to use the code tags.

    Moving to New to Java.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    X75TIGER75X is offline Member
    Join Date
    Apr 2012
    Posts
    19
    Rep Power
    0

    Default Re: Need help with clickable JButton in JTable that invokes method in the main GUI cl

    Quote Originally Posted by DarrylBurke View Post
    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem. Don't forget to use the code tags.
    I thought I just did that. I had already posted four compilable pastebin snippets on my first post where you could copy or download into your computer and compile and run it. The link you just posted said I should use one of suggested hosting websites for SSCCE, pastebin is one of them...

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: Need help with clickable JButton in JTable that invokes method in the main GUI cl

    I'm not going to download your code from another site, and many members who might be inclined to help are blocked by a corporate firewall from accessing file sharing sites. If the code is too long to post on a forum, it's too much code to ask for help with; click the SSCCE link and read the page to understand better.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #5
    X75TIGER75X is offline Member
    Join Date
    Apr 2012
    Posts
    19
    Rep Power
    0

    Default Re: Need help with clickable JButton in JTable that invokes method in the main GUI cl

    Fine, I edited the thread to include the whole code using code tags so people would not need to go to another website to copy-paste or download code. I hope that helps!

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: Need help with clickable JButton in JTable that invokes method in the main GUI cl

    You shouldn't be storing JButtons or indeed any visual component in a TableModel. To learn a better approach, take a look at camickr's Table Button Column « Java Tips Weblog

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 25
    Last Post: 08-24-2013, 11:08 AM
  2. JButton Running Another Main Class (help me)
    By cyentw in forum New To Java
    Replies: 2
    Last Post: 01-28-2013, 07:05 AM
  3. JButton not clickable
    By StevenTNorris in forum AWT / Swing
    Replies: 5
    Last Post: 11-09-2012, 08:59 PM
  4. setting JButton setEnabled() outside of main class
    By danborgir in forum New To Java
    Replies: 11
    Last Post: 05-07-2011, 04:03 PM
  5. Running main method class from another main class
    By tlrocketman in forum New To Java
    Replies: 3
    Last Post: 12-06-2010, 08:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •