hi friends I am creating a software in java swing where i want to exit a java software on client machine from server.i have this code bt its not working.when client runs the programme it does not opens but when i close the programme from server and client runs it agin it opens properly but its not exited from ser ver.
import java.net.*;
import java.io.*;
public class cl extends javax.swing.JFrame {
/** Creates new form cl */
public cl() {
initComponents();
}
/** 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() {
jPanel1 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 204, 204));
jPanel1.setBackground(new java.awt.Color(255, 204, 204));
jLabel5.setIcon(new javax.swing.ImageIcon("C:\\Users\\Administrator\\Desktop\\new-1.jpg")); // NOI18N
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("Welcome to our cafe");
jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel2.setText("Contact Administrator to start your session");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel2)))
.addContainerGap(872, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)))
.addContainerGap(597, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try
{
String s1,s2;
Socket s=new Socket("192.168.1.2",1024);
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
s1=dis.readUTF();
if (s1.equals("5"))
{
System.exit(0);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Your socket is staying open.
You should probably put an s.close(); before your System.exit(0);
Also dis.close(); and dos.close(); (before s.close();).
Related
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();
…
}
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 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'm building a food menu program and in that the user will insert the category code, category name, and browse for a suitable image which will be stored in the database as BLOB and click save. But I get an exception in my program such as this.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?)' at line 1
This is my code:
package Frames;
import Methods.DB_Con;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Random;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* #author ASHAN
*/
public class AddCategory extends javax.swing.JFrame {
String filename = null;
int s = 0;
byte[] cat_image = null;
/** Creates new form AddMenu */
public AddCategory() {
initComponents();
}
/** 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() {
jLabel12 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
codetext = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
cat_name = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();
jTextField2 = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jDesktopPane1 = new javax.swing.JDesktopPane();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 36));
jLabel12.setForeground(new java.awt.Color(255, 0, 0));
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel12.setText("Add Category");
jLabel12.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(0, 153, 255), null, null));
jButton1.setText("Browse for Image");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Generate Code");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Category Name");
jButton3.setText("Save");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Back");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel2.setBounds(0, 0, 150, 130);
jDesktopPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);
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(216, 216, 216)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(229, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addGap(138, 138, 138)
.addComponent(codetext, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addGap(138, 138, 138)
.addComponent(cat_name, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)))
.addGap(299, 299, 299))
.addGroup(layout.createSequentialGroup()
.addGap(194, 194, 194)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(271, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addGap(138, 138, 138)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
.addGap(76, 76, 76)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(76, 76, 76))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(58, 58, 58)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(codetext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cat_name, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton4))
.addGap(42, 42, 42))
.addGroup(layout.createSequentialGroup()
.addGap(251, 251, 251)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(107, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename = f.getAbsolutePath();
jTextField2.setText(filename);
try {
File image = new File(filename);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
cat_image = bos.toByteArray();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Random rand = new Random();
int n = rand.nextInt(90000) + 10000;
codetext.setText(Integer.toString(n));
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DB_Con.getConnection();
String sql = "insert into category (cat_code,cat_name,cat_image) values (?,?,?)";
PreparedStatement st = (PreparedStatement) con.prepareStatement(sql);
//int code=Integer.parseInt(codetext.getText());
// st.setInt(1, code);
st.setString(1, codetext.getText());
st.setString(2, cat_name.getText());
st.setBytes(3, cat_image);
st.execute(sql);
st.close();
JOptionPane.showMessageDialog(null, "Details Successfully Added");
} catch (Exception e) {
// JOptionPane.showMessageDialog(null, e);
System.out.println(e);
}
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
AddMenuMain am = new AddMenuMain();
am.setVisible(true);
this.setVisible(false);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddCategory().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField cat_name;
private javax.swing.JTextField codetext;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}
Does anyone have any suggestions on what I might be doing wrong?
st.setString(1, "\'"+codetext.getText()+"\'");
st.setString(2,"\'"+ cat_name.getText()+"\'");
st.setBytes(3, "\'"+cat_image+"\'");
Try this one st.execute(); in place of st.execute(sql);
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.