Hi I was doing a list of online users names using JLabel inside the JTextPane.
I used JLabel because I want the names to be clickable I was able to allign them horizontally using the styleddocument now my problem is
How can I delete the JLabel that was recently inserted ? I tried the remove method of JTextPane but it didnt work. I need to delete the JLabel when a user go offline.
My code:
public static void getUsernames()
{
try{
String query = "SELECT username FROM members WHERE status = 'offline'";
ps3 = con.prepareStatement(query);
rs2 = ps3.executeQuery();
}catch(Exception ex){ex.printStackTrace();}
}
public static void resultGetUsername(JTextPane jtp,StyledDocument sd)
{
try {
while (rs2.next())
{
final JLabel jl = new JLabel(rs2.getString("username"));
final String username = rs2.getString("username");
Border d = BorderFactory.createEmptyBorder(1,10,1,10);
Border d2 = BorderFactory.createLineBorder(Color.BLACK);
Border d3 = BorderFactory.createCompoundBorder(d2,d);
jl.setFont(new Font("Calibri",Font.BOLD,16));
jl.setBorder(d3);
jl.setOpaque(true);
jl.setBackground(Color.ORANGE);
jl.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
jl.setForeground(new Color(30,144,255));
}
public void mouseExited(MouseEvent arg0) {
jl.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
jl.setForeground(new Color(210,105,30));
jl.setBackground(new Color(154,205,50));
}
public void mouseReleased(MouseEvent e) {
jl.setBackground(Color.ORANGE);
jl.setForeground(Color.BLACK);
if(e.getClickCount() ==2)
new OneToOneChat(username);
}
});
Cursor c = new Cursor(Cursor.HAND_CURSOR);
jl.setCursor(c);
jtp.insertComponent(jl);
sd.insertString(sd.getLength(), "\n", SubPanel1.sas);
}
} catch (SQLException e) {
} catch (BadLocationException e) {
}
finally{
if (rs2 != null) {
try {
rs2.close();
} catch (SQLException sqlEx) { }
rs2 = null;
}
if (ps3 != null) {
try {
ps3.close();
} catch (SQLException sqlEx) { }
ps3 = null;
}
}
}
You can remove the labels from the JTextPane by using
setText("") or getStyledDocument().remove(0, doc.getLength())
if you need to get the labels this post could help: Get a component from a JTextPane through javax.swing.text.Element?
Then add the labels you want back into the JTextPane
Related
Hey guys,
I'm trying to make a digital version of this Simon says game, and I can't get the path entered from the player to save correctly.
Every color corresponds to a number, so Green = 0, Red = 1, Yellow = 2, and Yellow = 3.
The problem is that the playerPath is never resetting, so it will just add the current entered path to the path of last round, making it seem incorrect when compared to the original turnPath which is just a substring of the fullPath.
I attached all of the code below. Any help would be greatly appreciated.
import java.awt.Color;
import java.awt.event.*;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Simon implements ActionListener {
static JFrame f = new JFrame();
static JButton greenButton = new JButton("Green");
static JButton redButton = new JButton("Red");
static JButton yellowButton = new JButton("Yellow");
static JButton blueButton = new JButton("Blue");
static String playerPath = "";
static int turn = 1;
static int lostGame = 0;
static Random rand = new Random();
static String fullPath = "";
static String turnPath;
Simon() {
for (int i = 0; i < 100; i++) {
int maxIndex = 4;
int randomIndex = rand.nextInt(maxIndex);
fullPath = fullPath + randomIndex;
}
turnPath = fullPath.substring(0,turn);
prepareGUI();
buttonProperties();
}
public void prepareGUI() {
f.setSize(415,435);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void buttonProperties() {
greenButton.setBounds(0,0,200,200);
redButton.setBounds(200,0,200,200);
yellowButton.setBounds(0,200,200,200);
blueButton.setBounds(200,200,200,200);
greenButton.setBackground(Color.black);
redButton.setBackground(Color.black);
yellowButton.setBackground(Color.black);
blueButton.setBackground(Color.black);
greenButton.setOpaque(true);
redButton.setOpaque(true);
yellowButton.setOpaque(true);
blueButton.setOpaque(true);
greenButton.setForeground(Color.green);
redButton.setForeground(Color.red);
yellowButton.setForeground(Color.yellow);
blueButton.setForeground(Color.blue);
f.add(greenButton);
f.add(redButton);
f.add(yellowButton);
f.add(blueButton);
greenButton.addActionListener(this);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
greenButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
greenButton.setBackground(Color.green);
}
#Override
public void mouseReleased(MouseEvent e) {
greenButton.setBackground(Color.black);
}
});
redButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
redButton.setBackground(Color.red);
}
#Override
public void mouseReleased(MouseEvent e) {
redButton.setBackground(Color.black);
}
});
yellowButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
yellowButton.setBackground(Color.yellow);
}
#Override
public void mouseReleased(MouseEvent e) {
yellowButton.setBackground(Color.black);
}
});
blueButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
blueButton.setBackground(Color.blue);
}
#Override
public void mouseReleased(MouseEvent e) {
blueButton.setBackground(Color.black);
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
//Recording user input
if (e.getActionCommand().matches("Green")) {
playerPath += "0";
}
else if (e.getActionCommand().matches("Red")) {
playerPath += "1";
}
else if (e.getActionCommand().matches("Yellow")) {
playerPath += "2";
}
else if (e.getActionCommand().matches("Blue")) {
playerPath += "3";
}
}
public static void main(String[] args) {
while (lostGame < 1) {
lightButtons();
try {
Thread.sleep(1000 + (1000*turn));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (playerPath.equals(turnPath)) {
playerPath = "";
turn++;
}
else if (!(playerPath.equals(turnPath))) {
lostGame += 1;
System.out.println(playerPath);
System.out.println(turnPath);
System.out.println("GAME OVER" + '\n' + "Your Score: " + (turn-1));
}
}
}
public static void lightButtons() {
new Simon();
for (int i = 0; i < turnPath.length(); i++) { // iterates through string based on turn number
if (turnPath.charAt(i) == '0') {
greenButton.setBackground(Color.green); //* "Flashes" a color at appropriate box
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
greenButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '1') {
redButton.setBackground(Color.red); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
redButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '2') {
yellowButton.setBackground(Color.yellow); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
yellowButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '3') {
blueButton.setBackground(Color.blue); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
blueButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} ```
You can reset a String variable by writing playerPath = "";
I've code like this:
public main() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 500);
//tabbed pane
add(tb);
}
public JTextArea txtArea() {
JTextArea area = new JTextArea();
String st = String.valueOf(tab);
area.setName(st);
return area;
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new main();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==mnew) {
tab++;
tb.add("Untitled-"+tab,new JPanel().add(txtArea()));
int s = tb.getSelectedIndex();
s = tb.getTabCount()-1;
tb.setSelectedIndex(s);
}
if(source==save) {
int s = tb.getSelectedIndex()+1;
}
Every click on the "New" menu item, code creates new tab with new panel and textarea (it's similar to a lot of text editors like notepad++).
After clicked "Save" in menu bar I want to get text from focused jtextarea.
Please help.
Add a document listener to the text area.
public JTextArea txtArea() {
JTextArea area = new JTextArea();
tstDocumentListener dcL = new tstDocumentListener();
area.getDocument().addDocumentListener(dcL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
tstDocumentListener
public class tstDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
public void insertUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
}
Edit
As for getting the text when you gain or lose focus on the text area
public JTextArea txtArea() {
JTextArea area = new JTextArea();
CustomFocusListener cFL = new CustomFocusListener();
area.addFocusListener(cFL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
CustomFocusListener
public class CustomFocusListener implements FocusListener
{
#Override
public void focusGained(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
#Override
public void focusLost(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
}
I could really need your help, I tried to solve this problem for over one week, but haven't found a solution yet.
My Aim: I want to create a table, which can read the Data from a Database. I can also add Data to the DB by inserting it in my program.
My Problem: After inserting the Data i want the Database to refresh, so that it also shows my new record set. But no matter what i tried, it didn't work.
My Code: Here is my Mainframe-Class:
public class Gui_Test extends JFrame {
JButton addMovieButton;
JFrame frame = new JFrame("Movie Database");
JPanel panel;
JMenuBar menubar;
JMenu fileMenu;
JLabel label;
JTable table = new JTable();
MovieTableModel mtm;
public static void main(String[] args) {
Gui_Test test = new Gui_Test();
test.run();
}
public void run() {
// Gui ///
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setBackground(Color.black);
// Add - Movie Button ///
addMovieButton = new JButton("Add Movie");
addMovieButton.addActionListener(new addMovieButtonListener());
panel.add(addMovieButton);
// Table select ///
mtm = new MovieTableModel();
table.setModel(mtm);
JScrollPane pane = new JScrollPane(table);
frame.getContentPane().add(pane);
frame.getContentPane().add(BorderLayout.WEST, panel);
}
class addMovieButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddMoviePanel addmoviepanel = new AddMoviePanel();
addmoviepanel.moviepanel(mtm);
}
}}
Here is my TableModel:
public class MovieTableModel extends AbstractTableModel {
Connection con = null;
Vector columnNames = new Vector();
Vector data = new Vector();
ResultSet rs;
ResultSetMetaData meta;
public MovieTableModel() {
showResult();
}
void showResult() {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/...", "sa",
"");
java.sql.Statement stmt = con.createStatement();
String query = "SELECT * FROM movies ORDER BY id DESC";
ResultSet rs = stmt.executeQuery(query);
meta = rs.getMetaData();
int columns = meta.getColumnCount();
// get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(meta.getColumnName(i));
}
// get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
if (con != null)
try {
rs.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
#Override
public String getColumnName(int column) {
return columnNames.get(column).toString();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
#Override
public Class getColumnClass(int column) {
// TODO Auto-generated method stub
return getValueAt(0, column).getClass();
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int row, int column) {
return ((Vector) data.get(row)).get(column);
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
void addRow(final String value1, final String value2, final String value3,
final String value4, final String value5, final String value6,
final String value7) {
try {
Connection con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/Jonas/workspace/movieDB", "sa",
"");
try {
final java.sql.Statement state = con.createStatement();
try {
state.addBatch("INSERT INTO movies VALUES (DEFAULT, '"
+ value1 + "', '" + value2 + "'," + value3 + ", '"
+ value4 + "', " + value5 + ", '" + value6 + "', '"
+ value7 + "')");
state.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}
And here is my addMovieFrame, which opens to add new Movies:
public class AddMoviePanel {
MovieTableModel mtm;
JPanel addMoviePanel;
JFrame addMovieFrame;
JTextField value1Input;
JTextField value2Input;
// ... value3 - value7
Connection con = null;
public void moviepanel(MovieTableModel mtm) {
this.mtm = mtm;
addMovieFrame = new JFrame("Add Movie");
addMovieFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMovieFrame.setVisible(true);
addMovieFrame.setSize(550, 300);
addMoviePanel = new JPanel();
GroupLayout layout = new GroupLayout(addMoviePanel);
addMoviePanel.setLayout(layout);
JLabel label1 = new JLabel("label1:");
JLabel label2 = new JLabel("label2");
// ...JLabel 3-7 same as Label 1&2
addMoviePanel.add(label1);
addMoviePanel.add(label2);
// ...add Label 3-7
value1Input = new JTextField();
value2Input = new JTextField();
// ... value3- value7 Input
addMoviePanel.add(value1Input);
addMoviePanel.add(value2Input);
// ... add value3Input - value7Input
JButton ok = new JButton("Ok");
ok.addActionListener(new okActionListener());
addMovieFrame.add(ok);
addMovieFrame.getContentPane().add(addMoviePanel);
// here was just Layout Stuff //
}
class okActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
mtm.addRow(value1Input.getText(), value2Input.getText()
// ... value3Input.getText() - value7Input.getText()
);
mtm.fireTableDataChanged();
addMovieFrame.dispose();
}
}}
I already tried several types and positions of fireXXX-Methods...
Maybe somebody got an idea, how to refresh my jtable, when hitting the OK-Button in my addMovie-Frame? :)
As shown here and discuseed here, only your TableModel should fire table model events. While this is typically done in setValueAt(), you can insert a whole row and fire a single event, as shown here.
Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.
why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class
how to insert a combobox with values from the data base
I want to select from the database and add in the combobox
I have two class:
constructor Database() first class
//constructeur
Database()
{
void remplir_Jcomb() {
Connection conn = null;
Statement st = null;
String rq1 = "SELECT region FROM rg";
String rq2 = "SELECT ACTELS FROM rg";
// - Paramètres de connexion à la base de données
String url = "jdbc:mysql://localhost/réseau";
String login = "root";
String password = "";
String driver = "com.mysql.jdbc.Driver";
try {
//comboBox_gouver.removeAllItems();
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,login,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
st = conn.createStatement();
ResultSet rs1 = st.executeQuery(rq1);
ResultSet rs2 = st.executeQuery(rq2);
while ((rs1.next())&&(rs2.next())) {
comboBox_gouver.addItem(rs1.getString(1));
comboBox_ACTELS.addItem(rs2.getString(1));
}
st.close();
rs1.close();
rs2.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();}
}
}
interface swing second class which contains two JComboBox
call constructor Database()
private Database BD= new Database();
public Region() {
//first JComboBox
comboBox_gouver = new JComboBox<String>();
BD.remplir_Jcomb();
sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_gouver, 5, SpringLayout.NORTH, comboBox_gouver);
sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_gouver, 5, SpringLayout.NORTH, contentPanel);
sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_gouver, 16, SpringLayout.EAST, lbl_gouver);
sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_gouver, -26, SpringLayout.EAST, contentPanel);
contentPanel.add(comboBox_gouver);
comboBox_ACTELS = new JComboBox<String>();
sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_ACTELS, 5, SpringLayout.NORTH, comboBox_ACTELS);
sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_ACTELS, 6, SpringLayout.SOUTH, comboBox_gouver);
sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_ACTELS, 90, SpringLayout.EAST, lbl_ACTELS);
sl_contentPanel.putConstraint(SpringLayout.SOUTH, comboBox_ACTELS, -29, SpringLayout.SOUTH, contentPanel);
sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_ACTELS, -26, SpringLayout.EAST, contentPanel);
contentPanel.add(comboBox_ACTELS);
}}
erreur:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7139)
at tn.pack.ACTEL.Database.remplir_Jcomb(Database.java:94)
at tn.pack.ACTEL.Region.<init>(Region.java:75)
at tn.pack.ACTEL.Region.main(Region.java:41)
1) fill data from Db (use finally block for closing opened Objects, because this code is executed in all cases)
void whatever {
Connection conn = null;
Statement st1 = null;
try {
st1 = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st1.close();
rs1.close();
rs2.close();
conn.close();
} catch (SQLException ex) {
//
}
}
}
2) inside Db Statement fill data to the (notice difference in API betweens Java6 / Java7),
to the ComboBoxModel - JComboBox(ComboBoxModel aModel)/JComboBox(ComboBoxModel<E> aModel)
to the arrays of Objects/Elements - JComboBox(Object[] items)/JComboBox(E[] items)
to the Vector of Objects/Elements - JComboBox(Vector items)/JComboBox(Vector<E> items)
if Sql block ended then add array type to the JComboBox
EDIT:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ComboBoxListeners {
private JFrame f;
private JComboBox comboBox;
private JLabel label = new JLabel();
private DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel();
public ComboBoxListeners() {
comboBox = new JComboBox(comboBoxModel);
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if ((e.getStateChange() == ItemEvent.SELECTED)) {
String str = comboBox.getSelectedItem().toString();
label.setText("Selected Value From JComboBox is : " + str);
}
}
});
label.setPreferredSize(new Dimension(400, 30));
JButton btnAdd = new JButton(new AbstractAction("Append Items") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
addNewItemsFromDatabase();
}
});
JButton btnRefresh = new JButton(new AbstractAction("Refresh Items") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
refreshItemsFromDatabase();
}
});
f = new JFrame("ComboBox ItemListeners");
f.setLayout(new GridLayout(0, 1, 15, 15));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(comboBox);
f.add(label);
f.add(btnAdd);
f.add(btnRefresh);
f.setLocation(150, 150);
f.pack();
f.setVisible(true);
}
public void addNewItemsFromDatabase() {
ArrayList<Integer> ageList = new ArrayList<Integer>();
for (int i = 1; i <= 5; ++i) {
ageList.add(i);
}
for (final Integer i : ageList) {
EventQueue.invokeLater(new Runnable() {
public void run() {// updates to the Swing GUI must be done on EDT
comboBoxModel.addElement(i);
}
});
}
}
public void refreshItemsFromDatabase() {
comboBoxModel = new DefaultComboBoxModel();
ArrayList<Integer> ageList = new ArrayList<Integer>();
for (int i = 1; i <= 5; ++i) {
ageList.add(i);
}
for (final Integer i : ageList) {
EventQueue.invokeLater(new Runnable() {
public void run() {// updates to the Swing GUI must be done on EDT
comboBoxModel.addElement(i);
}
});
}
comboBox.setModel(comboBoxModel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxListeners comboBoxListeners = new ComboBoxListeners();
}
});
}
}
Use two separate Statement objects for the two ResultSet objects. You cannot reuse a Statement object when it is already open and used by a ResultSet. Something like this:-
void remplir_Jcomb() {
Connection conn = null;
Statement st1 = null;
Statement st2 = null;
String rq1 = "SELECT region FROM rg";
String rq2 = "SELECT ACTELS FROM rg";
//Rest of your code here
try {
// snipping off some more code
//...
st1 = conn.createStatement();
st2 = conn.createStatement();
ResultSet rs1 = st1.executeQuery(rq1);
ResultSet rs2 = st2.executeQuery(rq2);
while ((rs1.next())&&(rs2.next())) {
comboBox_gouver.addItem(rs1.getString(1));
comboBox_ACTELS.addItem(rs2.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
st1.close();
st1.close();
rs1.close();
rs2.close();
conn.close();
}
}