I have a JList and each item of the JList has a distinct display text and tooltip text. I would like to use 'DefaultListModel' for the JList. My question is that is it possible to somehow save the tooltip text when added an item to the DefaultListModel.
Thanks.
You can override the getToolTipText(...) method to provide your custom tool tip.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListToolTip extends JFrame
{
public ListToolTip()
{
DefaultListModel model = new DefaultListModel();
model.addElement("one");
model.addElement("two");
model.addElement("three");
model.addElement("four");
model.addElement("five");
model.addElement("six");
model.addElement("seven");
model.addElement("eight");
model.addElement("nine");
model.addElement("ten");
JList list = new JList( model )
{
public String getToolTipText( MouseEvent e )
{
int row = locationToIndex( e.getPoint() );
Object o = getModel().getElementAt(row);
return o.toString();
}
public Point getToolTipLocation(MouseEvent e)
{
int row = locationToIndex( e.getPoint() );
Rectangle r = getCellBounds(row, row);
return new Point(r.width, r.y);
}
};
JScrollPane scrollPane = new JScrollPane( list );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
ListToolTip frame = new ListToolTip();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(400, 100);
frame.setVisible( true );
}
}
Overriding getToolTipLocation(...) is not necessary.
Edit:
I want to save the custom text in the model
Then you would need to save a custom object in the model that contains the value displayed in the list and the text for the tooltip.
Check out ComboBox With Hidden Data for an example of creating an object using this approach.
Related
I have a code which displays Table in applets & consists of two columns:-
image icon
description
Here's my code:
import javax.swing.table.*;
public class TableIcon extends JFrame
{
public TableIcon()
{
ImageIcon aboutIcon = new ImageIcon("about16.gif");
ImageIcon addIcon = new ImageIcon("add16.gif");
ImageIcon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
Now what i want to know is how can I implement selection listener or mouse listener event on my table , such that it should select a particular image from my table and display on text area or text field(my table contains path of image file)?
Can I add text field on table & table on frame? Please feel free to ask queries if required.
In my code I have a table where I set single selection mode; in my case, listener described in How to Write a List Selection Listener (with a for loop from getMinSelectionIndex to getMaxSelectionIndex) is not useful because releasing mouse button I'm sure I have just one row selected.
So I've solved as follows:
....
int iSelectedIndex =-1;
....
JTable jtable = new JTable(tableModel); // tableModel defined elsewhere
jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel selectionModel = jtable.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
handleSelectionEvent(e);
}
});
....
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
// e.getSource() returns an object like this
// javax.swing.DefaultListSelectionModel 1052752867 ={11}
// where 11 is the index of selected element when mouse button is released
String strSource= e.getSource().toString();
int start = strSource.indexOf("{")+1,
stop = strSource.length()-1;
iSelectedIndex = Integer.parseInt(strSource.substring(start, stop));
}
I think this solution, that does not require a for loop between start and stop to check which element is selectes, is more suitable when table is in single selection mode
How about this?
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
final DefaultListSelectionModel target = (DefaultListSelectionModel)e.getSource();
iSelectedIndex = target.getAnchorSelectionIndex();
}
Read the section from the Swing tutorial on How to Write a List Selection Listener.
You can't add a text field to the table, but you can add a textfield and a table to the same frame.
I have a JTable which is created using a TableModel JTable t = new JTable(tableModel) I want to add a title to it. I was hoping for something like t.setTitle(graphTitle); but i cant find anything on that lines. I dont mind if the title is on top or below the table.
I was using JLabels but it just looks messy.
Can anyone help?
Cheers in advance
Another option you could consider is enclosing the JTable in a JPanel and setting a TitledBorder to that JPanel.
Like this:
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class TableTitle
{
public TableTitle ()
{
JFrame frame = new JFrame ();
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel ();
panel.setBorder (BorderFactory.createTitledBorder (BorderFactory.createEtchedBorder (),
"Table Title",
TitledBorder.CENTER,
TitledBorder.TOP));
JTable table = new JTable (3, 3);
panel.add (table);
frame.add (panel);
frame.setLocationRelativeTo (null);
frame.pack ();
frame.setVisible (true);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
#Override public void run ()
{
TableTitle t = new TableTitle ();
}
});
}
}
It looks like this:
You would have to add it when you instantiate your DefaultTableModel:
String data[][] = {{"Vinod","MCA","Computer"},
{"Deepak","PGDCA","History"},
{"Ranjan","M.SC.","Biology"},
{"Radha","BCA","Computer"}};
String col[] = {"Name","Course","Subject"};
DefaultTableModel model = new DefaultTableModel(data,col);
table = new JTable(model);
If it already exists, you can do something like this:
ChangeName(table,0,"Stu_name");
ChangeName(table,2,"Paper");
public void ChangeName(JTable table, int col_index, String col_name){
table.getColumnModel().getColumn(col_index).setHeaderValue(col_name);
}
Courtesy of RoseIndia.net
Hope that helps.
You can also add your title the JScrollPane which inscribes jtable in it.
Code:
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createTitledBorder ("Table Title"));
I don't think you have much options here. JTable has no functionality to add a titlebar.
So using JLabel or other components is your only option.
Try putting the JTable in a JTabbedPane.
I need some help to be able to add element to a JList and how to select element whith event.
This is my JList:
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
This is part of my actionlistener that handle different buttons. It's here I want to use model.add("Name"); bot I get a red underline in Eclipse!?
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number);
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement(name);
}
}
}
Then I would preciate some help how I should select the element inside the JList? Should I use implements ActionListener to the class or a FrameHandler object? Thanks!
EDIT: My main problem that I can't solve is that the JList is inside the construcor and when I use model.add("name"); inside the constructor it works, but it's not working when I want to add something outside the constructor? I have read the tutorial several times, but can't find any help for this.
EDIT 2: The completet code. Probably some out of scope problem?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI4EX extends JFrame implements ActionListener{
private JButton buttonNewCustomer, buttonTerminate, buttonAddNewName, buttonAddNewSavingsAccount, buttonAddNewCreditAccount;
private JLabel textLabelName, textLabelPersonalNumber, textLabelNewName;
private JTextField textInputName, textInputPersonalNumber, textInputNewName;
private JPanel panelNewCustomer, panelQuit, panelNewAccount, panelChangeName, panelSelectCustomer;
private boolean statusButtonNewCustomer = true;
private boolean statusButton2 = true;
private boolean statusButtonAddNewName = true;
private String title = "Bank ";
// Create a customHandler object
CustomHandler customHandler = new CustomHandler();
// Main method to start program
public static void main(String[] args){
GUI4EX frame = new GUI4EX();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
// Cunstructor
public GUI4EX(){
// Create window
setTitle(title);
setSize(450,500);
setLocation(400,100);
setResizable(false);
// Set layout to boxlayout
Container container = getContentPane( );
setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
// Create jpanels
panelNewCustomer = new JPanel();
panelQuit = new JPanel();
panelNewAccount = new JPanel();
panelChangeName = new JPanel();
panelSelectCustomer = new JPanel();
// Create and add components - buttons
buttonNewCustomer = new JButton("OK");
buttonTerminate = new JButton("Avsluta");
buttonAddNewName = new JButton("OK");
buttonAddNewSavingsAccount = new JButton("Sparkonto");
buttonAddNewCreditAccount = new JButton("Kreditkonto");
// Create and add components - labels
textLabelName = new JLabel("Namn");
textLabelPersonalNumber = new JLabel("Personnummer");
textLabelNewName = new JLabel("Nytt namn");
//add(textLabel1);
// Create and add components - textfields
textInputName = new JTextField("");
textInputPersonalNumber = new JTextField("");
textInputName.setColumns(10);
textInputPersonalNumber.setColumns(10);
textInputNewName = new JTextField();
textInputNewName.setColumns(20);
// Add components to panel new customer
panelNewCustomer.add(textLabelName);
panelNewCustomer.add(textInputName);
panelNewCustomer.add(textLabelPersonalNumber);
panelNewCustomer.add(textInputPersonalNumber);
panelNewCustomer.add(buttonNewCustomer);
// Add components to panel to select customer
panelSelectCustomer.add(listScroller);
// Add components to panel new name
panelChangeName.add(textLabelNewName);
panelChangeName.add(textInputNewName);
panelChangeName.add(buttonAddNewName);
// Add components to panel new accounts
panelNewAccount.add(buttonAddNewSavingsAccount);
panelNewAccount.add(buttonAddNewCreditAccount);
// Add components to panel quit
panelQuit.add(buttonTerminate);
// Set borders to jpanels
panelNewCustomer.setBorder(BorderFactory.createTitledBorder("Skapa ny kund"));
panelChangeName.setBorder(BorderFactory.createTitledBorder("Ändra namn"));
panelNewAccount.setBorder(BorderFactory.createTitledBorder("Skapa nytt konto"));
panelQuit.setBorder(BorderFactory.createTitledBorder("Avsluta programmet"));
panelSelectCustomer.setBorder(BorderFactory.createTitledBorder("Välj kund"));
// Add panels to window
add(panelNewCustomer);
add(panelSelectCustomer);
add(panelChangeName);
add(panelNewAccount);
add(panelQuit);
// Listener
// FrameHandler handler = new FrameHandler();
// Add listener to components
//button1.addActionListener(handler);
buttonNewCustomer.addActionListener(this);
buttonAddNewName.addActionListener(this);
buttonAddNewSavingsAccount.addActionListener(this);
buttonAddNewCreditAccount.addActionListener(this);
buttonTerminate.addActionListener(this);
}
//private class FrameHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number); // Check if customer exist
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement("name");
}
}
// Change name
if(event.getSource() == buttonAddNewName && statusButtonAddNewName)
{
String newName = textInputNewName.getText();
customHandler.changeName(newName); // call method to change name
setTitle(title + "Kund: " + newName);
}
// Create new savings account
if(event.getSource() == buttonAddNewSavingsAccount)
{
customHandler.CreateNewSavingsAccount();
}
// Create new credit account
if(event.getSource() == buttonAddNewCreditAccount)
{
customHandler.CreateNewCreditAccount();
}
// Terminate program
if(event.getSource()==buttonTerminate && statusButton2)
{
System.exit(3);
}
}
//}
}
You are lucky I am in a good mood. Here a very basic example, matching the code you provided. Type something in the textfield, hit the enter button and watch the list get populated.
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddToJListDemo {
private static JFrame createGUI(){
JFrame frame = new JFrame( );
final DefaultListModel model = new DefaultListModel();
JList list = new JList( model );
final JTextField input = new JTextField( 10 );
input.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent aActionEvent ) {
String text = input.getText();
if ( text.length() > 0 ) {
model.addElement( text );
input.setText( "" );
}
}
} );
frame.add( list, BorderLayout.CENTER );
frame.add( input, BorderLayout.SOUTH );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
return frame;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
public void run() {
JFrame frame = createGUI();
frame.setSize( 200,200 );
frame.setVisible( true );
}
} );
}
}
Edit
Based on your full code, you must make the list a field in your GUI4EX class, similar to for example the buttonNewCustomer field
public class GUI4EX extends JFrame implements ActionListener{
//... all other field
DefaultListModel model;
//constructor
public GUI4EX(){
//all other code
//DefaultListModel model = new DefaultListModel(); instantiate the field instead
model = new DefaultListModel();
JList list = new JList(model);
//rest of your code
}
}
This will make sure you can access the model in the actionPerformed method. But if you cannot figure out something this basic, you should not be creating GUIs but reading up on basic Java syntax and OO principles
i want to highlight an item inside popup list.
I say "highlight" becouse i don't want to select it (for example by calling setSelectedItem) but only make it selected inside the jcombobox popup.
How can i do?
The following sort of works in that an item other than the first is selected. However, if you use the keyboard to change selection, it always starts from the first because that is the one that is selected.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
public class ComboBoxSelect extends JFrame
{
public ComboBoxSelect()
{
String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
JComboBox comboBox = new JComboBox( items );
add( comboBox );
comboBox.addPopupMenuListener(new PopupMenuListener()
{
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
JComboBox comboBox = (JComboBox)e.getSource();
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.setSelectedIndex(2);
}
public void popupMenuCanceled(PopupMenuEvent e) {}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
});
}
public static void main(String[] args)
{
ComboBoxSelect frame = new ComboBoxSelect();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
This write-up provides guidance on how you could modify JComboBox:
http://www.orbital-computer.de/JComboBox/
Although it's written for auto-complete functionality, a custom mechanism to highlight without selecting would be very similar (and probably easier).
I am making an address book GUI with Java and I have a JList that displays all the names of the people in my ArrayList (this is populated by the updateinfo method mentioned below). I want it so when I click an item on the JList, the TextFields are then updated with that persons details. Before I have only used buttons and therefore actionListeners. I think I understand that a JList must use ListSelectionListener but I cannot seem to implement this. I have added a snippet of my code below. Can somebody please help?? For continuity with my actionlisteners I would like to have it as an inner class but this is not vital
JList jl;
DefaultListModel list;
list = new DefaultListModel();
this.jl = new JList(this.list);
//add ListSelectionListener????
updateList();
this.add(this.jl, layout);
You can add the listener and then just query the currently selected index.
I did a sample for you, I hope you find it useful.
This is the relevant section:
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
Bear in mind that's not the only way to go, this is just an starting point for you.
Here's the complete working sample:
import java.util.Vector;
import java.util.Arrays;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class JListSample {
private Vector<String> data = new Vector<String>(
Arrays.asList( new String [] {
"one", "two", "three"
})
);
private JTextField nameTextField;
public static void main( String [] args) {
JListSample s = new JListSample();
s.run();
}
public void run() {
JFrame frame = new JFrame("Selection test");
frame.add( list(), BorderLayout.WEST );
frame.add( editPanel() );
frame.pack();
frame.setVisible( true );
}
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
private JComponent editPanel() {
JPanel panel = new JPanel();
panel.add( new JLabel("Name:") );
nameTextField = new JTextField(10);
panel.add( nameTextField );
return panel;
}
}
This is what is displayed:
sample http://img177.imageshack.us/img177/6294/capturadepantalla200911k.png
You just add the selection listener to the list, like that:
jl.addSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// evaluate e if necessary and call a method
// in your class to write the text in the textfield
int selectedRow = e.getFirstIndex(); // more complicate for multiselects
updateTextFieldWithName(selectedRow); // to be implemented
}
});
Using an anonymous class like here is the quickest way. It's a bit hard to read but a typical pattern.
(just read you preferred an inner class, but I can't code that here on the fly with no IDE at hand...)
Yes you will want to use a ListSelectionListener for this, you will also probably want to set the list to single selection(ListSelectionModel.SINGLE_SELECTION). This will allow the user to only select one item in the list. You can then add you listSelectionListener, and in the valueChanged of the event do something like the following(not exact syntax).
valueChanged(ListSelectionEvent e){
int idx = e.getFirstIndex();
int idx2 = e.getLastIndex(); //idx and idx2 should be the same if you set SingleSel
if(idx==idx2){
//here you can get the person detail however you have them stored. You can get them from the model like so,
Object personObj = MYLIST.getModel().getElementAt(int index);
}
}
I think I understand that a JList must
use ListSelectionListener but I cannot
seem to implement this
Well, then start by reading the JList API. You will find a link to the Swing tutorial on "How to Use Lists", which contains a working example.
Also in the tutorial you will find a section on "How to Write a List Selection Listener" which contains a second example.
Start with the tutorial for your basic questions.