What I am trying to do is get the selected value from my SWING View JList to my controller class, so I can use that data in my controller.
For simplicity I manually added 2 elements to my JList("Item 1", "Item 2", (so I have something to pass)I seem to have a problem accessing it. My View has a JList with a ListSelectionListener which I pass to my controller via my main:
public class AppMain {
private AppView appView = null;
public static void main(String[] args) {
AppView appView = new AppView();
Controller controller = new Controller(appView);
}
public AppView getView() {
return appView;
}
}
My view is:
import javax.swing.event.ListSelectionListener;
public class AppView extends javax.swing.JFrame {
public AppView() {
initComponents();
this.setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
ValueList = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ValueList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", " " };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(ValueList);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JList ValueList;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
public void ListSelectionListener(ListSelectionListener selectionListener) {
ValueList.addListSelectionListener(selectionListener);
}
}
And a Controller:
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Controller implements ListSelectionListener{
AppView gui;
public Controller(AppView v)
{
gui = v;
gui.ListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
this.gui.ListSelectionListener(this);
System.out.println("FOO");
}
}
No I want TO get the selectedValue in the Controller. I can't seem to grasp it. Also This prints Foo 3 times and I also cannot find out why.
Thanks in advance
As shown in How to Write a List Selection Listener more than one ListSelectionEvent may be generated as the user selects fist one entry and then another. Try checking when the selection is stable.
if (!e.getValueIsAdjusting()) {
// examine result
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
…
}
Related
I have done all the details I have done, and I don't get an error but what I want to do doesn't work.
I tried to check on google, chatgpt, and friends. I was expected to a window with wait for input from the user, and the user writes a task and he enters "submit". Then, a window of DeadLine comes with an import calendar. So, the user chooses a DeadLine and he presses "OK". and then I created a constructor with the selected time and the task (to print the input) therefore, I called to the constructor and its doesn't call. Please help me. ):
The code:
import javax.swing.*;
import com.toedter.calendar.JCalendar;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.Date;
public class List extends JFrame {
String todo = "TO DO: ";
ImageIcon icon1;
JButton button;
public static String task;
static JLabel label,label2,label3;
static JLabel titletaskLabel,titletaskLabel2,titletaskLabel3,titletaskLabel4;
static JFrame frame;
public static JTextField text;
static Font myFont = new Font("Ink Free", Font.BOLD, 30);
static Font yourFont = new Font("Ink Free", Font.HANGING_BASELINE, 20);
static JCalendar calendar;
static Date selectedDate;
List() {
frame = new JFrame("List");
icon1 = new ImageIcon("list.png");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 900);
frame.setIconImage(icon1.getImage());
frame.setLayout(null);
label = new JLabel("To Do List: ");
label.setBounds(50, 50, 200, 20);
label2 = new JLabel("Enter a task: ");
label2.setFont(myFont);
label2.setBounds(70, 460, 200, 40);
button = new JButton("Submit");
button.setBounds(470, 500, 80, 50);
button.setBackground(Color.green);
button.addActionListener(new ActionListener1());
text = new JTextField();
text.setBounds(70, 500, 370, 50);
text.setFont(myFont);
frame.add(text);
frame.add(button);
frame.add(label);
frame.add(label2);
frame.setVisible(true);
}
static void addDeadline() {
JDialog dialog = new JDialog(frame, "Choose a Due Date", true);
dialog.setSize(400, 400);
dialog.setLocationRelativeTo(frame);
JPanel calendarPanel = new JPanel();
calendarPanel.setBounds(70, 600, 370, 200);
calendar = new JCalendar();
calendarPanel.add(calendar);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the selected date
Calendar selectedCalendar = calendar.getCalendar();
selectedDate = selectedCalendar.getTime();
task = text.getText();
System.out.println(selectedDate);
dialog.setVisible(false);
tasks(); // add the new task to the frame
}
});
calendarPanel.add(okButton);
dialog.add(calendarPanel);
dialog.setVisible(true);
}
static void tasks() {
titletaskLabel = new JLabel(task + "The DeadLine is: " + selectedDate);
titletaskLabel.setBounds(50, 70, 200, 50);
frame.add(titletaskLabel);
}
static class ActionListener1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
addDeadline();
}
}
}
public class Main extends List{
public static void main(String[] args) {
new List();
}
}
I'm using Swing, Java Messaging Service and GlassFish4.1 server to build a chat box from a Jpanel so I can add it to my Jframe application; but I seem to have a problem establishing a connection.
During runtime the program stops at the line:
TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");
I previously got this client-code to work on an Enterprise application, but now I'm attempting to add it to a regular Java project I'm rather stuck.
Really appreciate any help on this, I'm very new to JMS so please keep answers as Lamen as possible. Thanks!
import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class ChatPanel extends javax.swing.JPanel implements Runnable{
private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;
/**
* Creates new form chatFrame
* #param nickName
*/
public ChatPanel(String nickName)
{
initComponents();
DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
name = nickName;
connect();
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
// </editor-fold>
public JTextArea getTextArea()
{
return gameInfoTextArea;
}
public void setText(String textString)
{
String s = gameInfoTextArea.getText() + "\n" + textString;
gameInfoTextArea.setText(s);
}
private void connect()
{
try
{
Context ctx = new InitialContext();
TopicConnectionFactory tcf = (TopicConnectionFactory)
ctx.lookup("BJconn");
tpConnection = tcf.createTopicConnection();
tpConnection.setClientID(name);
tpSession = tpConnection.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup("BJDest");
tpPublisher = tpSession.createPublisher(topic);
tpSubscriber = tpSession.createDurableSubscriber(topic, name);
tpConnection.start();
t = new Thread(this);
t.start();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Chat cannot connect");
System.out.println(e.getMessage());
}
}
/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
tpConnection.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage() );
}
} */
private void sendMessage()
{
try
{
TextMessage tx = tpSession.createTextMessage();
tx.setText(name + ": " + this.chatField.getText());
tpPublisher.send(tx);
this.chatField.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot send message");
}
}
#Override
public void run()
{
try
{
while (true)
{
TextMessage tx = (TextMessage) tpSubscriber.receive();
if (tx != null)
{
String content = "";
content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
this.gameInfoTextArea.setText(content);
Thread.sleep(100);
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
chatField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
gameInfoTextArea = new javax.swing.JTextArea();
setBackground(new java.awt.Color(0, 102, 0));
chatField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chatFieldActionPerformed(evt);
}
});
chatField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
chatFieldKeyReleased(evt);
}
});
gameInfoTextArea.setEditable(false);
gameInfoTextArea.setColumns(20);
gameInfoTextArea.setRows(5);
jScrollPane1.setViewportView(gameInfoTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chatField)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>
private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
{
sendMessage();
}
}
// Variables declaration - do not modify
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
I've to JTables. I drag a row from the first table and drop it to the second.
The DnD operation works fine so far, but how can easily refresh the second table after
dropping operation? I've implemented a TableModelListener, but it works only when I
double click on a line of a table.
My question: which event listener do I need to solve my problem? Any solutions or examples?
btw: the DnD operation is performing with the tranferHandler
ok here's some code:
TableExample for creating the to tables
ListHandler1 for DnD operations
SearchRenderer for updating row heights after DnD or table changings
please keep in mind that i wrote quickly. ..
Thanks and regards!
TableExample:
package GUI_Examples;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
public class TableExample implements TableModelListener{
String [] title = new String [] {"Title A", "Title B"};
String [] title2 = new String [] {"Title C", "Title D"};
Object [][] data = new String [][] {{"aaaaaaaaaaaa aaaaaa aaaaaaa", "bbbbbbbb bbbb bbbbbb bbbbbb"},
{"cccccccccc cccccccc ccccccc", "ddddddd ddd dddddddd dddddd"},
{"eeeeeeeeee eeeeeeee eeeeeee", "fffffff ffff ffffff fffffff"}};
Object [][] data2 = new String [][] {{"",""}};
private JTable table;
private JTable table2;
private JFrame frame;
private DefaultTableModel model;
private DefaultTableModel model2;
private JScrollPane pane1;
private JScrollPane pane2;
private SearchRenderer1 myRenderer;
private SearchRenderer1 myRenderer2;
TableExample() {} //constructor
public JPanel createTable() {
JPanel panel = new JPanel();
//creating tables and table models
model = new DefaultTableModel(data, title);
model2 = new DefaultTableModel(data2, title2);
table = new JTable(model);
table2 = new JTable(model2);
//setting renderers
myRenderer = new SearchRenderer1();
table.setDefaultRenderer(String.class, myRenderer);
table.getColumnModel().getColumn(0).setCellRenderer(myRenderer);
table.getColumnModel().getColumn(1).setCellRenderer(myRenderer);
myRenderer2 = new SearchRenderer1();
table2.setDefaultRenderer(String.class, myRenderer2);
table2.getColumnModel().getColumn(0).setCellRenderer(myRenderer2);
table2.getColumnModel().getColumn(1).setCellRenderer(myRenderer2);
//setting sizes
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(60);
table.getColumnModel().getColumn(1).setPreferredWidth(60);
table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table2.getColumnModel().getColumn(0).setPreferredWidth(60);
table2.getColumnModel().getColumn(1).setPreferredWidth(60);
//Drag&Drop operations
table.setDragEnabled(true);
table2.setDropMode(DropMode.INSERT);
table2.setTransferHandler(new ListHandler1(model2));
pane1 = new JScrollPane(table);
pane2 = new JScrollPane(table2);
pane1.setPreferredSize(new Dimension(150,300));
pane2.setPreferredSize(new Dimension(150,300));
updateRowHeights();
updateRowHeights2();
panel.add(pane1);
panel.add(pane2);
return panel;
}
void showTable() {
//create and show frame
JPanel testPanel = createTable();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testPanel);
frame.pack();
frame.setVisible(true);
}//showTable
void updateRowHeights() {
for (int row = 0; row < table.getRowCount(); row++) {
int rowHeight = table.getRowHeight();
Component comp = table.prepareRenderer(table.getCellRenderer(row, 1), row, 1);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
table.setRowHeight(row, rowHeight);
}
}
void updateRowHeights2() {
for (int row = 0; row < table2.getRowCount(); row++) {
int rowHeight = table2.getRowHeight();
Component comp2 = table2.prepareRenderer(table2.getCellRenderer(row, 1), row, 1);
rowHeight = Math.max(rowHeight, comp2.getPreferredSize().height);
table2.setRowHeight(row, rowHeight);
}
}
public static void main(String[] args) {
TableExample example = new TableExample();
example.showTable();
}//main
#Override
public void tableChanged(TableModelEvent e) {
updateRowHeights();
updateRowHeights2();
}
}//TableExample
ListHandler
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import javax.swing.TransferHandler;
import javax.swing.table.DefaultTableModel;
public class ListHandler1 extends TransferHandler {
DefaultTableModel model = new DefaultTableModel();
ListHandler1(DefaultTableModel tableModel) {
this.model=tableModel;
} //constructor
/**
*
*/
private static final long serialVersionUID = 1L;
/* canImport: This method tests suitability of a drop operation. Here we filter out the clipboard paste operations
* and allow only String drop operations. If the method returns false, the drop operation is cancelled.(non-Javadoc)
* #see javax.swing.TransferHandler#canImport(javax.swing.TransferHandler.TransferSupport)
*/
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
/*The importData() method transfers the data from the clipboard or from the drag and drop operation to the drop location.
* (non-Javadoc)
* #see javax.swing.TransferHandler#importData(javax.swing.TransferHandler.TransferSupport)
*/
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable transferable = support.getTransferable(); //The Transferable is the class, where the data is bundled.
String line;
try {
line = (String) transferable.getTransferData(DataFlavor.stringFlavor); //We retrieve our data.
} catch (Exception e) {
return false;
}
String item [] = line.split("\t");
model.addRow(new Object[]{item[0],item[1]});
return true;
}
}
SearchRenderer:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class SearchRenderer1 extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public SearchRenderer1() {
setLineWrap(true);
setWrapStyleWord(true);
} //constructor
public Component getTableCellRendererComponent (JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column ) {
this.setText((String)value);
//for update row height
this.setSize(table.getColumnModel().getColumn(column).getWidth(),Short.MAX_VALUE);
if (isSelected) {
this.setBackground(new java.awt.Color(255, 240, 200));
}
else {
this.setBackground(new java.awt.Color(255, 255, 255));
}
return this;
}//getTableCellRendererComponent
}
I am trying to filter JTable1 by the contents in a textfield using RowSorter.
I am receiving this error message when I type text into the field:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javaapplication2.NewJFrame.newFilter(NewJFrame.java:221)
at javaapplication2.NewJFrame.access$000(NewJFrame.java:28)
at javaapplication2.NewJFrame$1.insertUpdate(NewJFrame.java:88)
Not sure as to why I am getting a NullPointerException.
Here's my code:
package javaapplication2;
import java.util.Vector;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.PropertyStateEvent;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class NewJFrame extends javax.swing.JFrame {
private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header
private Vector<Vector<String>> data2; //used for data from database
private Vector<String> header2; //used to store data header
public NewJFrame() throws Exception {
DbWork newDatabase = new DbWork();
//get data from database
data = newDatabase.getEmployee();
//create header for employee table
header = new Vector<String>();
header.add("EmployeeID");
header.add("FirstName");
header.add("LastName");
header.add("MI");
header.add("HomeAddress");
header.add("State");
header.add("Zip");
header.add("DateOfBirth");
header.add("HireDate");
header.add("TerminationDate");
header.add("LicenseDate");
header.add("Active");
header.add("ManagerID");
header.add("ModifiedID");
data2 = newDatabase.getTrucks();
//create header for truck table
header2 = new Vector<String>();
header2.add("TruckID");
header2.add("VinNumber");
header2.add("Make");
header2.add("Model");
header2.add("TruckYear");
header2.add("PriceAcquired");
header2.add("LicenseNumber");
header2.add("ModifiedID");
header2.add("DriverFirstName");
header2.add("DriverLastName");
header2.add("DriverMI");
initComponents();
new TableRowSorter<TableModel>(model1);
jTable1.setRowSorter(sorter);
txtFilter.getDocument().addDocumentListener(
new DocumentListener(){
public void changedUpdate(DocumentEvent e){
newFilter();
}
public void insertUpdate(DocumentEvent e){
newFilter();
}
public void removeUpdate(DocumentEvent e){
newFilter();
}
}
);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable(model1);
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
txtFilter = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Tracking System - Prototype");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
data, header
));
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jTable1);
jTabbedPane1.addTab("Employees", jScrollPane1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
data2, header2
));
jTable2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable2);
jTabbedPane1.addTab("Trucks", jScrollPane2);
jButton1.setText("Modify Record");
jButton2.setText("New Record");
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(307, 307, 307))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTabbedPane1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(104, 104, 104)
.addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 351, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(62, 62, 62))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
new NewJFrame().setVisible(true);
}catch(Exception e){e.printStackTrace();}
}
});
}
private void newFilter() {
RowFilter<TableModel, Object> rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(txtFilter.getText(),0);
} catch (Exception e) {
return;
}
sorter.setRowFilter(rf);
}
TableModel model1 = new DefaultTableModel();
TableRowSorter<TableModel>sorter;
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField txtFilter;
// End of variables declaration
}
The problem is that sorter is ... null :-) That's because you never set the field:
// creates a sorter which is nowhere used
new TableRowSorter<TableModel>(model1);
// declares a field that's not initialized
TableRowSorter<TableModel> sorter;
// you have to combine both to initialize the sorter field
sorter = new TableRowSorter<TableModel>(model1);
jTable1.setRowSorter(sorter);
Anyway, it's not necessary to manually install a rowSorter, let the table manage it for you and grab the auto-created sorter when needed:
// configure the table to create a rowSorter as needed
jTable1.setAutoCreateRowSorter(true);
// access the auto-created sorter in newFilter
TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
sorter.setRowFilter(rf);
i want to add listener to a jlist. but items are added dynamically to jlist.
so i cant register listener.
and event doesnt fire.
can any1 help me???
plzz contact me if u have any example.
my email id gvjoshi25#gmail.com
here is my code :
DefaultListModel f=new DefaultListModel();
DefaultListModel sf=new DefaultListModel();
public Jlistdemo() {
initComponents();
System.out.println("hi");
for(int i=0;i<10;i++)
{
f.addElement("hello"+i);
//System.out.println("helloo"+i);
}
fields=new JList(f);
jScrollPane1.setViewportView(fields);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
fields = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
sel_fields = new javax.swing.JList();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fields.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(fields);
sel_fields.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
sel_fields.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
sel_fieldsValueChanged(evt);
}
});
jScrollPane2.setViewportView(sel_fields);
jButton1.setText(">");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("<");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(91, 91, 91))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))))
.addContainerGap(68, Short.MAX_VALUE))
);
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(fields.getSelectedValue()!=null)
{
int i=fields.getSelectedIndex();
sf.addElement(fields.getSelectedValue());
f.removeElement(fields.getSelectedValue());
sel_fields=new JList(sf);
sel_fields.setSelectionMode(ListSelectionModel.SINGLE_SELECTION );
jScrollPane2.setViewportView(sel_fields);
fields.setSelectedIndex(i);
jScrollPane2.revalidate();
jScrollPane2.repaint();
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(sel_fields.getSelectedValue()!=null)
{
int i=sel_fields.getSelectedIndex();
f.addElement(sel_fields.getSelectedValue());
sf.removeElementAt(sel_fields.getSelectedIndex());
sel_fields.setSelectedIndex(i);
}
}
private void sel_fieldsValueChanged(javax.swing.event.ListSelectionEvent evt) {
System.out.println("fired");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Jlistdemo().setVisible(true);
}
});
}
private javax.swing.JList fields;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JList sel_fields;
The error is the following line in your constructor:
fields = new JList(f)
with that, you replace the list that is created in initComponents
you're separating the creation of the list from adding the data.
and you don't need to keep track of selected fields, the list will do that for you.
plus, better names will help make the code clearer.