Trying to save an image in mysql database using netbeans program - mysql

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);

Related

MVC+ SWING and a ListSelectionListener

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();
…
}

Null Pointer Exception when trying to filter JTable with RowSorter

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);

Java Swing Game TT [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am trying to have this quiz like game where user have 3 buttons to choose from. If they chose the wrong answer, an image bomb wil appear and immediately it wil automatically change to the next question and if they chose the corect one, it will also change to the next question. However, my problem here is that i do not know if i wrote my if...else statements correctly. When i run my program, it doesn't change to the next question and there is no bomb image appearing too. I tried many methods to solve this but i stil could'nt. I really need help.
Here is my code and the if... else statements is from line 244 to 388.
public class GamesQuestionPanel extends JPanel{
private static final long serialVersionUID = 1L;
private JLabel jLabelQuestion = null;
private JLabel jLabelScore = null;
private JLabel jLabelHeart1 = null;
private JLabel jLabelHeart2 = null;
private JLabel jLabelHeart3 = null;
private JButton jButtonAnswer1;
private JButton jButtonAnswer2;
private JButton jButtonAnswer3;
private JLabel jLabelDescription1;
private JLabel jLabelDescription2;
private JLabel jLabelDescription3;
private JButton jButtonAdd = null;
private JFrame myFrame = null;
private JLabel jLabelTimer = null;
private Timer t;
private TimerModel tm;
private int qn_num = 0;
private JLabel jLabelScore1 = null;
private JLabel jLabelQn;
private JButton jButtonEdit = null;
private static int answer1;
private int answer2;
private int answer3;
private int count=0;
int Score = 0;
public void Randomise() {
ArrayList<Integer> random = new ArrayList<Integer>();
try{
DBController db = new DBController();
//passing data source name
db.setUp("CFDatabase");
String g_question =" ";
String dbQuery = "SELECT * FROM GameQuestion WHERE g_question ='" + g_question + "'";
//for retrieve SQL use readRequest method
ResultSet rs = db.readRequest(dbQuery);
if (rs.next()){
int g_questionNo =rs.getInt("g_questionNo");
random.add(g_questionNo);
System.out.println(random.get(g_questionNo));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This is the default constructor
*/
public GamesQuestionPanel() {
super();
initialize();
}
public GamesQuestionPanel(JFrame f) {
this();
myFrame = f;
}
public GamesQuestionPanel(JFrame f, String s ){
this();
myFrame = f;
jLabelTimer.setText(s);
}
/**
* This method initialises this
*
* #return void
*/
private void initialize() {
jLabelQn = new JLabel();
jLabelQn.setBounds(new Rectangle(13, 96, 55, 50));
jLabelQn.setFont(new Font("Dialog", Font.BOLD, 18));
jLabelQn.setHorizontalAlignment(SwingConstants.CENTER);
jLabelQn.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelQn.setText("");
jLabelScore1 = new JLabel();
jLabelScore1.setText("");
jLabelScore1.setSize(new Dimension(83, 29));
jLabelScore1.setLocation(new Point(119, 438));
jLabelTimer = new JLabel();
jLabelTimer.setBounds(new Rectangle(17, 23, 199, 53));
jLabelTimer.setText("00:01:00");
jLabelTimer.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelTimer.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/timerbg.png")));
jLabelTimer.setFont(new Font("Dialog", Font.BOLD, 18));
jLabelTimer.setHorizontalAlignment(SwingConstants.CENTER);
t = new Timer(1000, new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e) {
tm.timeTick();
jLabelTimer.setText(tm.getTime());
if(tm.isTimeUp()){
t.stop();
JOptionPane.showMessageDialog(null, "HighScore: " + Score, "GameOver",
JOptionPane.INFORMATION_MESSAGE);
int finalScore = Score ;
String display = Integer.toString(finalScore);
jLabelScore.setText(display);
tm.setTime("00:10:00");
JPanel panel = new ProgrammesEventsPanelEnq(myFrame);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
}
}
});
tm = new TimerModel();
tm.setTime("00:01:00");
t.start();
jLabelDescription3 = new JLabel();
jLabelDescription3.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription3.setLocation(new Point(483, 385));
jLabelDescription3.setSize(new Dimension(218, 33));
jLabelDescription3.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription3.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription3.setForeground(Color.black);
jLabelDescription2 = new JLabel();
jLabelDescription2.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription2.setLocation(new Point(244, 386));
jLabelDescription2.setSize(new Dimension(226, 33));
jLabelDescription2.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription2.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription2.setForeground(Color.black);
jLabelDescription1 = new JLabel();
jLabelDescription1.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription1.setBackground(new Color(238, 238, 238));
jLabelDescription1.setLocation(new Point(9, 386));
jLabelDescription1.setSize(new Dimension(225, 33));
jLabelDescription1.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription1.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription1.setForeground(Color.black);
jLabelHeart3 = new JLabel();
jLabelHeart3.setBounds(new Rectangle(611, 61, 45, 39));
jLabelHeart3.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart3.setText("");
jLabelHeart2 = new JLabel();
jLabelHeart2.setBounds(new Rectangle(546, 61, 43, 40));
jLabelHeart2.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart2.setText("");
jLabelHeart1 = new JLabel();
jLabelHeart1.setBounds(new Rectangle(482, 60, 44, 41));
jLabelHeart1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart1.setText("");
jLabelScore = new JLabel();
jLabelScore.setBounds(new Rectangle(25, 438, 83, 29));
jLabelScore.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
jLabelScore.setForeground(Color.black);
jLabelScore.setText(" Score:");
jLabelQuestion = new JLabel();
jLabelQuestion.setBounds(new Rectangle(71, 95, 618, 52));
jLabelQuestion.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
jLabelQuestion.setForeground(Color.black);
this.setSize(712, 500);
this.setLayout(null);
this.setBackground(Color.white);
this.add(jLabelQuestion, null);
this.add(jLabelScore, null);
this.add(jLabelHeart1, null);
this.add(jLabelHeart2, null);
this.add(jLabelHeart3, null);
this.add(getJButtonAnswer1(), null);
this.add(getJButtonAnswer2(), null);
this.add(getJButtonAnswer3(), null);
this.add(jLabelDescription1, null);
this.add(jLabelDescription2, null);
this.add(jLabelDescription3, null);
this.add(getJButtonAdd(), null);
this.add(jLabelTimer, null);
this.add(jLabelScore1, null);
this.add(jLabelQn, null);
this.add(getJButtonEdit(), null);
qn_num = 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
jLabelQn.setText("Q1.");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
/**
* This method initialises jButtonAnswer1
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer1() {
if (jButtonAnswer1 == null) {
jButtonAnswer1 = new JButton();
jButtonAnswer1.setBackground(Color.white);
jButtonAnswer1.setSize(new Dimension(228, 214));
jButtonAnswer1.setLocation(new Point(5, 164));
jButtonAnswer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer1.equals("answer1");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer1.isSelected()) && (g1.getG_correctAnswer() == answer1))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
//jButtonAnswer1.removeAll();
}
else if((jButtonAnswer1.isSelected()) && (g1.getG_correctAnswer() != answer1))
{
jButtonAnswer1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer1;
}
/**
* This method initialises jButtonAnswer2
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer2() {
if (jButtonAnswer2 == null) {
jButtonAnswer2 = new JButton();
jButtonAnswer2.setBackground(Color.white);
jButtonAnswer2.setSize(new Dimension(228, 214));
jButtonAnswer2.setLocation(new Point(240, 164));
jButtonAnswer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer2.equals("answer2");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer2.isSelected()) && (g1.getG_correctAnswer() == answer2))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
else if((jButtonAnswer2.isSelected()) && (g1.getG_correctAnswer() != answer2))
{
jButtonAnswer2.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer2;
}
/**
* This method initialises jButtonAnswer3
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer3() {
if (jButtonAnswer3 == null) {
jButtonAnswer3 = new JButton();
jButtonAnswer3.setBackground(Color.white);
jButtonAnswer3.setSize(new Dimension(228, 214));
jButtonAnswer3.setLocation(new Point(474, 163));
jButtonAnswer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer3.equals("answer3");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer3.isSelected()) && (g1.getG_correctAnswer() == answer3))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
else if((jButtonAnswer3.isSelected()) && (g1.getG_correctAnswer() != answer3))
{
jButtonAnswer1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer3;
}
/**
* This method initializes jButtonEdit
*
* #return javax.swing.JButton
*/
private JButton getJButtonAdd() {
if (jButtonAdd == null) {
jButtonAdd = new JButton();
jButtonAdd.setBounds(new Rectangle(591, 9, 90, 39));
jButtonAdd.setFont(new Font("Dialog", Font.BOLD, 16));
jButtonAdd.setText("Add");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
t.stop();
JPanel panel = new GamesCreatePanel(myFrame);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
Object admin = null;
if(getName() == admin) {
jButtonAdd.setVisible(true);
}
else {
jButtonAdd.setVisible(false);
}
}
});
}
return jButtonAdd;
}
/**
* This method initializes jButtonEdit
*
* #return javax.swing.JButton
*/
private JButton getJButtonEdit() {
if (jButtonEdit == null) {
jButtonEdit = new JButton();
jButtonEdit.setPreferredSize(new Dimension(65, 31));
jButtonEdit.setSize(new Dimension(90, 39));
jButtonEdit.setText("Edit");
jButtonEdit.setFont(new Font("Dialog", Font.BOLD, 16));
jButtonEdit.setLocation(new Point(492, 9));
jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
t.stop();
String a = jLabelQuestion.getText();
String b = jButtonAnswer1.getText();
String c = jButtonAnswer2.getText();
String d = jButtonAnswer3.getText();
String f = jLabelDescription1.getText();
String g = jLabelDescription2.getText();
String h = jLabelDescription3.getText();
GameQuestion game = new GameQuestion();
game.setG_question(a);
game.setG_image1(b);
game.setG_image2(c);
game.setG_image3(d);
game.setG_imageDescription1(f);
game.setG_imageDescription2(g);
game.setG_imageDescription3(h);
JPanel panel = new GamesEditPanel(myFrame, a, game);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
}
});
}
return jButtonEdit;
}
}
This code is way too long to go through it, but a quick look at your if statements reveals you are checking whether a JButton is selected. What you probably want is adding an ActionListener to the JButton, which will be called when the user clicks the JButton. In the ActionListener you can then check whether the correct answer was given and proceed, or show the 'bomb image'.
I suggest you take a look at the Swing button tutorial and more specifically the JButton part of the tutorial

java client side programme

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();).

JList - ListSelectionListener

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.