update/refresh combobox with glazedlists - java

how could i ahhm.."auto-update" my comboBox..?im using glazedlists autoComplete and im bit lost on how to do it..ive read some like use eventlists and basiclistbut i couldnt get the idea on how to make it work..
pls help :(
heres my sample code..but i dunno whats next to it..ive tried using eventlists but couldnt make it update on its own..
abc = AutoCompleteSupport.install(comboSearch,GlazedLists.eventListOf(auto));
abc.setStrict(false);
public void count(){
try{
String sql2 = "select count(*) from daily_input";
stmt = conn.prepareStatement(sql2);
rs=stmt.executeQuery();
while(rs.next()){
String x = rs.getString("count(*)");
z = Integer.parseInt(x);
}
auto = new String[z];
idNum = new int[z];
}
catch(SQLException | NumberFormatException e){
}
}
public void cB(){
count();
i=0;
try{
String sql = "Select concat(first_name, ' ',last_name) as full_name from daily_input";
stmt = conn.prepareStatement(sql);
rs=stmt.executeQuery();
while(rs.next()){
String name = rs.getString("full_name");
auto[i] = name;
i++;
}
comboSearch.isEditable();
}

You need to connect your combo-box with event list and then add elements to event list.
public class ComboBoxTest {
private final EventList<String> values;
public ComboBoxTest() {
this.values = GlazedLists.eventListOf("A", "B", "C", "D");
}
public Component createControl() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(this.createComboBox(), BorderLayout.NORTH);
panel.add(new JButton(new AbstractAction("Add Elements") {
#Override
public void actionPerformed(ActionEvent e) {
ComboBoxTest.this.addElements();
}
}), BorderLayout.SOUTH);
return panel;
}
public void addElements() {
List<String> toAdd = new ArrayList<>(2);
toAdd.add("E");
toAdd.add("F");
this.values.addAll(toAdd);
}
private Component createComboBox() {
JComboBox<String> box = new JComboBox<>();
box.setEditable(true);
AutoCompleteSupport.install(box, this.values);
return box;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxTest testApp = new ComboBoxTest();
JFrame frame = new JFrame("ComboBox Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(testApp.createControl());
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Related

how can i remove and replace jlabel with image icon in java?

Im trying to create a banking system and to not make it boring we tried to add some image icon into the program in jlabel, when i tried to run the code and first pin mistake, removes the tester label successfully but the problem is when tries are equal to 4, Label pinwrongtester doesn't seem to remove instead it is mixing with the Label that i programmed when they entered pin 4 times, i hope you guys can help me to solve this mistakes
public void Option()
{
//option title
JLabel label = new JLabel("Choose Options");
label.setFont(new Font("Consolas",Font.BOLD,20));
JButton choose = new JButton();
choose.add(label);
choose.setBounds(200,300,200,40);
choose.setBackground(Color.white);
choose.setEnabled(false);
// Buttons Option
JButton Balance = new JButton("Balance");
JButton Withdraw= new JButton("Withdraw");
JButton Send = new JButton("Transfer");
JButton Exit = new JButton("Exit");
//Set Bounds
Balance.setBounds(50,350,200,40);
Withdraw.setBounds(50,450,200,40);
Send.setBounds(350,350,200,40);
Exit.setBounds(350,450,200,40);
//addActionListener
Balance.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinbalance();
}
});
Withdraw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinwithdraw();
}
});
Send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pintransferfunds();
}
});
//add buttons and labels
p.add(choose);
p.add(Balance);
p.add(Withdraw);
p.add(Send);
p.add(Exit);
}
JPanel enterpinbg;
JFrame enterpinframe;
String account_name;
String balance;
String pindb;
JLabel tester;
JLabel pinwrongtester;
JLabel pinwrongertester;
JLabel balancetester;
JFrame balanceframe;
JPanel balancepanel;
ImageIcon enteryourpin;
ImageIcon pinwrong;
ImageIcon pinwronger;
ImageIcon balanceicon;
private LinkedList<String> picturetrans;
JTextField inputpin;
boolean police = false;
int x =0;
public void pinbalance()
{
//PIN FRAME
enterpinframe = new JFrame("Enter Pin");
enterpinframe.setSize(WIDTH,HEIGHT);
enterpinframe.setVisible(true);
enterpinframe.setResizable(false);
enterpinframe.setLocationRelativeTo(null);
enterpinframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//PIN PANEL
enterpinbg = new JPanel();
enterpinbg.setSize(WIDTH,HEIGHT);
enterpinbg.setBackground(Color.orange);
enterpinbg.setVisible(true);
enterpinbg.setLayout(null);
enterpinframe.add(enterpinbg);
inputpin = new JTextField();
inputpin.setFont(new Font("Consolas",Font.BOLD,20));
inputpin.setForeground(Color.gray);
//Setbounds
inputpin.setBounds(250,600,100,40);
//tester + image
enteryourpin = new ImageIcon(getClass().getResource("Enter yout PIN.png"));
tester = new JLabel(enteryourpin);
tester.setBounds(50,50,500,500);
//enterpin Add
enterpinbg.add(tester);
enterpinbg.add(inputpin);
this.dispose();
inputpin.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==(KeyEvent.VK_ENTER))
{
String pinx = inputpin.getText();
Connection con= null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER1);
Class.forName(JDBC_DRIVER2);
con = DriverManager.getConnection(URL,USER,PASS);
stmt=con.createStatement();
String sql ="SELECT*FROM TBL_BANK WHERE PIN ='"+pinx+"' ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
pindb = rs.getString("PIN");
account_name = rs.getString("ACCOUNT_NAME");
balance = rs.getString("BALANCE");
}
rs.close();
}
catch(Exception f)
{
System.out.println(f);
}
//if Login Success and Failed
if(pinx.equals(pindb))
{
// Balance will show up
}
else if(pinx!=(pindb))
{
enterpinbg.remove(tester);
x++;
System.out.println("x");
inputpin.setText("");
pinwrong = new ImageIcon(getClass().getResource("PIN Wrong (1_2Times).png"));
pinwrongtester = new JLabel(pinwrong);
pinwrongtester.setBounds(50,50,500,500);
enterpinbg.add(pinwrongtester);
enterpinbg.repaint();
if(x>=4 )
{
// this doesnt quite work please help me fix it
enterpinbg.remove(pinwrongtester);
enterpinbg.repaint();
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

How to put Names from my database into a JLIst that i have made in another class?

public void GetUsersName(){
try
{
java.sql.Connection con = DriverManager.getConnection(url + dbName, userName, password);
java.sql.Statement s = con.createStatement();
ResultSet result = s.executeQuery("SELECT Username FROM tblcustomers ORDER BY UserID");
if(result != null){
while (result.next())
{
ListUserNames.usersJList.setListData(Username);
}
}
s.close();
con.close();
} catch (SQLException e)
{
System.out.println("Error: " + e);
}
Here my Code from the class where I make my JList Panel , which I then insert to another Class. I cans see my JScrollPane perfectly, the only problem is i can't insert the usernames into it, but I can see other values from a test array for example.
public class ListUserNames extends JPanel{
public static JList<String> usersJList;
public ListUserNames()
{
setLayout(new FlowLayout()) ;
usersJList =new JList<String>();
usersJList.setVisibleRowCount(10) ;
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}
JList has no mehtod to add or remove an elment once it's initialized. Instead you can use a ListModel with the JList.
Example:
public class ListUserNames extends JPanel {
public static DefaultListModel<String> listModel = new DefaultListModel<>();
public ListUserNames() {
setLayout(new FlowLayout());
JList<String> usersJList = new JList<String>(listModel);
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}
and your fetch method:
public void getUsersName() throws SQLException {
java.sql.Connection con = DriverManager.getConnection(url + dbName, userName, password);
JList<String> list = new JList<>();
PreparedStatement ps = con.prepareStatement("SELECT Username FROM tblcustomers ORDER BY UserID");
ResultSet result = ps.executeQuery();
DefaultListModel<String> listModel = new DefaultListModel<>();
if (result != null) {
while (result.next())
{
ListUserNames.listModel.addElement(result.getString("Username"));
}
}
ps.close();
con.close();
}
You are using the static aceess to the list. ListUserNames.usersJList.setListData(Username);
That means "usersJList" might have not been initialized yet.
In your can , it was not.
2 solutions.
Solution 1
Initialize "usersJList" in ListUserNames.
such as public static
JList usersJList = new JList();
This is not a recommended way
Solution 2
The second solution make a method to initialize userJList
Code:
GetUsersName.java
public void GetUsersName(){
/*-----your other codes----*/
JList<String> usersJList = ListUserNames.getUsersJList();
if(result != null){
while (result.next())
{
usersJList.setListData(Username);
}
}
/*-----your other codes----*/
}
ListUserNames.java
public class ListUserNames extends JPanel{
private static JList<String> usersJList;
public static JList<String> getUsersJList(){
if (usersJList == null){
usersJList =new JList<String>();
}
return usersJList;
}
public ListUserNames(){
getUsersJList();
setLayout(new FlowLayout()) ;
usersJList.setVisibleRowCount(10) ;
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}

how to refresh JTable

I'm making a simple program that show the teams, the matches and racking goal of Euro2016 in France.
I have some problem with JTable when changing query.
Here is what happens:
when I change from a Table of (for example) 10 rows to another one that contains only 5 rows it works. But if I change from a table that contains 5 rows to another of 10, the table doesn't change, it displays only 5 rows.
Here the code:
public class Euro2016GUI extends JFrame {
private Container container;
private Sfondo pnlSfondo;
JTable table;
JPanel panel;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
static Vector<String> headers = new Vector<String>();
public Euro2016GUI() {
data.removeAll(data);
headers.removeAll(headers);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setTitle("Euro2016");
this.setLocationRelativeTo(null);
pnlSfondo = new Sfondo();
container = this.getContentPane();
container.add(pnlSfondo);
}
public void createTable(String pQuery) {
data.removeAll(data);
headers.removeAll(headers);
Control control = new Control();
panel = new JPanel(new BorderLayout());
panel.setSize(300, 300);
panel.setBackground(Color.red);
control.getData(pQuery);
data = control.getData();
headers = control.getHeaders();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setMaximumSize(new Dimension(100, 300));
header_size();
JScrollPane scroll = new JScrollPane(table);
//scroll.setSize(600, 400);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.getContentPane().add(panel);
panel.add(scroll, BorderLayout.CENTER);
}
public void header_size() {
int colonne = table.getColumnModel().getColumnCount();
TableColumn column;
for (int i = 0; i < colonne; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(200);
}
}
public void cleanData() {
if (table != null) {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.setRowCount(0);
table.revalidate();
}
data.removeAll(data);
headers.removeAll(headers);
}
}
CLASS CONTROL
public class Control {
private static Vector<Vector<String>> data = new Vector<Vector<String>>();
private static Vector<String> headers = new Vector<String>();
public void getData(String pQuery) {
// Enter Your MySQL Database Table name in below Select Query.
String query = pQuery;
Connection con = null;
ResultSet rs;
Statement st = null;
int colonne = 0;
data.removeAll(data);
headers.removeAll(headers);
try {
con = DBConnectionPool.getConnection();
st = con.createStatement();
rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
colonne = rsmd.getColumnCount();
for (int i = 1; i <= colonne; i++) {
headers.add(rsmd.getColumnName(i));
}
while (rs.next()) {
Vector<String> d = new Vector<String>();
for (int i = 1; i <= colonne; i++) {
d.add(rs.getString(i));
}
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataInJTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
DBConnectionPool.releaseConnection(con);
}
}
}
public Vector<Vector<String>> getData() {
return this.data;
}
public Vector<String> getHeaders() {
return this.headers;
}
}
HERE THE ACTION LISTENER IN THE MENU:
...
//----ROSE---//
private class OnClickRose implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
str = str.replace("[", "");
str = str.replace("]", "");
String sx = "'";
String dx = "'";
String query = query2.concat(sx.concat(str.concat(dx)));
//frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query);
}
}
//----CALENDARIO----//
private class OnClickCalendario implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query4);
}
}
//----CLASSIFICA MARCATORI----//
private class OnClickMarcatori implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query3);
}
}
...
Could anybody tell me where I wrong?
Basically to tell the table to refresh itself, you just call the method fireTableDataChanged() of it's table model.
So in your example, after you run the query, you could just call:
((DefaultTableModel)yourTable.getModel()).fireTableDataChanged();
But I suggest you to stop using default table model, and implement your own table model. It's a lot easier to work.

How to put db value in jlist dynamicly?

Hi i have a j list where i want to put some database value and want to create jlist automatically but when i try to do this i am not able to achieve this when do i got only one value from database to jlist
how can i achieve this?
here is my code
public class RootSelection1 {
private String connectionURL = "jdbc:mysql://localhost:3306/Trainpis";
private String s1="";
private String s2="";
private final Map<String, ImageIcon> imageMap;
public RootSelection1() {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionURL, "root", "");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select route,fromr from route");
while(rs.next()){
s1=rs.getString("route");
s2=rs.getString("fromr");
}
} catch(Exception e) {
}
String[] nameList={s1,s2};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setVerticalTextPosition(JLabel.TOP);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setBorder(new MatteBorder( 0, 0, 2, 0, Color.GRAY));
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
for (String s : list) {
map.put(s, new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png"));
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RootSelection1 ();
// ComboboxDemo cb=new ComboboxDemo();
//System.out.println(cb.a);
}
});
}
}
Thanks in advance
You got only one value (one row) because
while(rs.next()){
s1=rs.getString("route");
s2=rs.getString("fromr");
}
has looped already thru the whole record set and s1,s2 hold the values of the last row in the record set.
Try something like this:
List<String> nameList = new ArrayList<String>();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionURL, "root", "");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select route,fromr from route"
while(rs.next()){
String s1=rs.getString("route");
String s2=rs.getString("fromr");
nameList.add(s1+" "+s2);
}
} catch(Exception e) {
}
JList list = new JList(nameList.toArray());

Categories