JTable aren't refreshing when selecting from Combobox - java

The scrollPane table isn't refreshing for every time I selected something from the combo. Initially it has data but after I selected something, the data is removed successfully but new data isn't populating in
public void ConsultFrame(String id, String name, String ic){
GenerateMed("dp-000"); // to begin the scrollpane filled with Fever's medicine
JButton proc = new JButton("Proceed");
JButton addmed = new JButton(">>");
selected = new JTable(data, columnNames){
#Override
public boolean isCellEditable(int row,int column){
switch(column){
case 0:
return false;
case 1:
return false;
default: return true;
}
}};
selectedPane = new JScrollPane(selected);
//Dispensary's category combobox related
disp = dbDisp.getDispensary();
final JComboBox cBox = new JComboBox();
for(int count=0; count<disp.size(); count++)
cBox.addItem(disp.get(count).getDSP_desc());
cBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
for(int count=0; count<disp.size(); count++){
if(cBox.getSelectedItem().equals(disp.get(count).getDSP_desc())){
System.out.println(disp.get(count).getDSP_ID());
GenerateMed(disp.get(count).getDSP_ID());
break;
}
}
}
});
JTextArea tArea = new JTextArea(5, 30);
JScrollPane desc = new JScrollPane(tArea);
tArea.setLineWrap(true);
desc.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
JPanel info = new JPanel();
info.setLayout(new FlowLayout(FlowLayout.LEFT));
info.add(new JLabel("<html>Patient's ID : " + id + "<br>Patient's Name: " + name + "<br>Patient's IC : " + ic + "<br><br>Medical Description : </html>"));
info.add(desc);
JPanel medSelect = new JPanel();
medSelect.setLayout(new GridLayout(1,2));
medSelect.add(scrollPane);
medSelect.add(selectedPane);
JPanel medic = new JPanel();
medic.setLayout(new BorderLayout());
medic.add(cBox, BorderLayout.NORTH);
medic.add(medSelect, BorderLayout.CENTER);
medic.add(proc, BorderLayout.SOUTH);
JPanel all = new JPanel();
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(Calendar.getInstance().getTime());
title = BorderFactory.createTitledBorder(timeStamp);
title.setTitleJustification(TitledBorder.RIGHT);
all.setBorder(title);
all.setLayout(new GridLayout(2,1));
all.add(info);
all.add(medic);
JFrame consult = new JFrame();
consult.setTitle(name + "'s consultation");
consult.setResizable(false);
consult.setVisible(true);
consult.setSize(500, 460);
consult.setLocationRelativeTo(null);
consult.add(all);
}
This is where my Combobox's is heading as soon as something is selected and I've tried repaint & revalidate
public void GenerateMed(String dps_id){
if (tModel != null) {
for (int i = tModel.getRowCount() - 1; i > -1; i--)
tModel.removeRow(i);
}
tModel = dbMed.getDPSMedicine(dps_id);
tModel.fireTableDataChanged();
table = new JTable(tModel){
#Override
public boolean isCellEditable(int row,int column){
return false;
}};
table.setShowGrid(false);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
//Table customization
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.changeSelection(0, 0, false, false);
scrollPane = new JScrollPane(table);
scrollPane.repaint();
scrollPane.revalidate();
}

scrollPane = new JScrollPane(table);
The above line of code creates a new scrollPane, but doesn't add the scrollPane to the frame.
However, there is no need to even create a new JTable or a new JScrollPane. Get rid of all the code.
Instead you just change the model of your JTable by using:
table.setModel( dbMed.getDPSMedicine(dps_id) );
So basically your method becomes one line of code.
Also, use proper method names. Method names should NOT start with an upper case character.

Related

how do i make a button that sorts my list in an ascending order(java swing)?

I have created a an jtable in java swing which looks like the following
I have added 6 buttons and 3 of them work fine(add,update,delete). im not worried about random match button but i want "Sort By goals" button to sort out all the records entered by the highest number of goals. same goes for points. I have tried many times but i dont seem to be able to figure out.
Here is the code for my table arrays;
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
Here is my draft for the button;
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
Here is my delete button;
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
Here is my entire code;
public class table{
public static void main(String[] args) {
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
// create JTextFields
JTextField txtTeamName = new JTextField();
JTextField txtWins = new JTextField();
JTextField txtLosses = new JTextField();
JTextField txtGD = new JTextField();
JTextField txtPoints = new JTextField();
JTextField txtMatches = new JTextField();
JLabel lblTeamName = new JLabel("Team name");
JLabel lblWins = new JLabel("Wins");
JLabel lblLosses = new JLabel("Losses");
JLabel lblGD = new JLabel("Goal difference");
JLabel lblPoints = new JLabel("Points");
JLabel lblMatches = new JLabel("Matches");
// create JButtons
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnUpdate = new JButton("Update");
JButton btnSortPoints = new JButton("Sort by points");
JButton btnSortGoals = new JButton("Sort by goals");
JButton btnRandomMatch = new JButton("Add a random data");
txtTeamName.setBounds(1200, 230, 100, 25);
txtWins.setBounds(1200, 260, 100, 25);
txtLosses.setBounds(1200, 290, 100, 25);
txtGD.setBounds(1200, 320, 100, 25);
txtMatches.setBounds(1200,350,100,25);
txtPoints.setBounds(1200,380,100,25);
lblTeamName.setBounds(1100,230,100,25);
lblWins.setBounds(1100,260,100,25);
lblLosses.setBounds(1100,290,100,25);
lblGD.setBounds(1100,320,100,25);
lblMatches.setBounds(1100,350,100,25);
lblPoints.setBounds(1100,380,100,25);
btnAdd.setBounds(1150, 20, 200, 50);
btnUpdate.setBounds(1150, 80, 200, 50);
btnDelete.setBounds(1150, 140, 200, 50);
btnSortGoals.setBounds(920,20,200,50);
btnSortPoints.setBounds(920,80,200,50);
btnRandomMatch.setBounds(920,140,200,50);
// create JScrollPane
JScrollPane pane = new JScrollPane(table);
pane.setBounds(0, 0, 880, 400);
frame.setLayout(null);
frame.add(pane);
// add JTextFields to the jframe
frame.add(txtTeamName);
frame.add(txtWins);
frame.add(txtLosses);
frame.add(txtGD);
frame.add(txtMatches);
frame.add(txtPoints);
//Adding the labels to the frame
frame.add(lblTeamName);
frame.add(lblWins);
frame.add(lblLosses);
frame.add(lblGD);
frame.add(lblMatches);
frame.add(lblPoints);
// add JButtons to the jframe
frame.add(btnAdd);
frame.add(btnDelete);
frame.add(btnUpdate);
frame.add(btnSortGoals);
frame.add(btnSortPoints);
frame.add(btnRandomMatch);
// create an array of objects to set the row data
Object[] row = new Object[6];
// button add row
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = txtTeamName.getText();
row[1] = txtWins.getText();
row[2] = txtLosses.getText();
row[3] = txtGD.getText();
row[4] = txtMatches.getText();
row[5] = txtPoints.getText();
// add row to the model
model.addRow(row);
}
});
// Event listener for button remove row
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
// get selected row data From table to textfields
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
// i = the index of the selected row
int i = table.getSelectedRow();
txtTeamName.setText(model.getValueAt(i, 0).toString());
txtWins.setText(model.getValueAt(i, 1).toString());
txtLosses.setText(model.getValueAt(i, 2).toString());
txtGD.setText(model.getValueAt(i, 3).toString());
txtMatches.setText(model.getValueAt(i,4).toString());
txtPoints.setText(model.getValueAt(i,5).toString());
}
});
// button update row
btnUpdate.addActionListener(new ActionListener(){
#Override
public void actionPerformed (ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0)
{
model.setValueAt(txtTeamName.getText(), i, 0);
model.setValueAt(txtWins.getText(), i, 1);
model.setValueAt(txtLosses.getText(), i, 2);
model.setValueAt(txtGD.getText(), i, 3);
model.setValueAt(txtMatches.getText(),i,4);
model.setValueAt(txtPoints.getText(),i,5);
}
else{
System.out.println("Update Error");
}
}
});
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
frame.setSize(1400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You first need to add sorting support to your JTable. Read the Sorting and Filtering link from the tutorial for information on how to do that.
Once that is done the user will be able to sort any column by clicking on the column header of the column.
Verify the sorting works by manually clicking on the columns headers.
i want "Sort By goals" button to sort out all the records entered by the highest number of goals and points
Now that your JTable supports sorting you can add add an ActionListener to your buttons to do the specific sorting:
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Points column in the model is converted to the view column
int viewColumn = table.convertColumnIndexToView(4);
// Set up the columns you want to sort on
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
sortKeys.add(new RowSorter.SortKey(viewColumn, SortOrder.ASCENDING));
// Do the sorting
TableRowSorter sorter = (TableRowSorter)table.getRowSorter();
sorter.setSortKeys(sortKeys);
}
});
`

repaint() method doesn't work more than once

I am currently working on a gui project which is managing a sql database. I am currently adding,deleting logs and showing tables existing in mysql. The problem is my add and delete buttons on my panel are supposed to repaint/refresh the table on that panel as a record is added or deleted however while testing I discovered that repaint method doesn't refresh the table after the first use of the button. What can cause this problem? Thanks in advance..
public JTabbedPane addComponentToPane() {
//Container pane = new Container();
JTabbedPane tabbedPane = new JTabbedPane();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JPanel card3 = new JPanel();
JPanel card4 = new JPanel();
JPanel card5 = new JPanel();
JPanel card6 = new JPanel();
JPanel card7 = new JPanel();
JPanel card8 = new JPanel();
card1.setLayout(new BorderLayout());
card2.setLayout(new BorderLayout());
card3.setLayout(new BorderLayout());
card4.setLayout(new BorderLayout());
card5.setLayout(new BorderLayout());
card6.setLayout(new BorderLayout());
card7.setLayout(new BorderLayout());
card8.setLayout(new BorderLayout());
JScrollPane actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);
card3.add(createTables("address"), BorderLayout.CENTER);
card4.add(createTables("category"), BorderLayout.CENTER);
card5.add(createTables("city"), BorderLayout.CENTER);
card6.add(createTables("country"), BorderLayout.CENTER);
card7.add(createTables("customer"), BorderLayout.CENTER);
card8.add(createTables("film"), BorderLayout.CENTER);
JButton button = new JButton("Yeni Kayıt");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});
JButton delButton = new JButton("Kayıt sil");
delButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
delRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});``
card1.add(button, BorderLayout.SOUTH);
card1.add(delButton, BorderLayout.EAST);
tabbedPane.addTab("Şirketler", null, card1, "şirket tanımları");
tabbedPane.addTab("Sorumlular", card2);
tabbedPane.addTab("Varlık Grupları", card3);
tabbedPane.addTab("Bilgi Varlıkları", card4);
tabbedPane.addTab("Varlık Değerleri", card5);
tabbedPane.addTab("Açıklıklar", card6);
tabbedPane.addTab("Tehditler", card7);
tabbedPane.addTab("Ek-A", card8);
//pane.add(tabbedPane, BorderLayout.CENTER);
return tabbedPane;
}
Create tables method creating a Jtable from sql table.
private JScrollPane createTables(String tablename) {
Connection con = null;
Statement statement = null;
ResultSet result = null;
String query;
JScrollPane jsp = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root");
statement = con.createStatement();
query = "select * from " + tablename;
result = statement.executeQuery(query);
ResultSetMetaData rsmt = result.getMetaData();
int columnCount = rsmt.getColumnCount();
Vector column = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
defTableModel = new DefaultTableModel(data, column);
table = new JTable(defTableModel) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
;
};
//table.setAutoCreateRowSorter(true);
TableRowFilterSupport.forTable(table).searchable(true).apply();
table.setRowSelectionAllowed(true);
jsp = new JScrollPane(table);
}
catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
statement.close();
result.close();
con.close();
}
catch (Exception e) {
//JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
return jsp;
}
I could see couple of inconsistencies in the code:
The actor variable is not being set to the added component in the action listener.
First time you are adding new JScrollPane(createTables("actor")) and then onwards you only add createTables("actor").
The (1) might be causing the problem.
I think the problem is the reference to the actor:
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
Here, the variable actor is not more referenced in card1. To not lose this reference you should do something like this, in both actionPerformed methods:
card1.remove(actor);
actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);

java and database connection

I'm having a problem in my project i cant Connect the program with the data Source
So if there's any help plzz assist me
this is the error message and the source code below
I'm in trouble plzzz help meeeeee
//for creating the North Panel
private JPanel northPanel = new JPanel();
//for creating the Center Panel
private JPanel centerPanel = new JPanel();
//for creating the label
private JLabel northLabel = new JLabel("THE LIST FOR THE BOOKS");
//for creating the button
private JButton printButton;
//for creating the table
private JTable table;
//for creating the TableColumn
private TableColumn column = null;
//for creating the JScrollPane
private JScrollPane scrollPane;
//for creating an object for the ResultSetTableModel class
private ResultSetTableModel tableModel;
/***************************************************************************
* for setting the required information for the ResultSetTableModel class. *
***************************************************************************/
private static final String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
private static final String DATABASE_URL = "jdbc:odbc:Telecom";
private static final String DEFAULT_QUERY = "SELECT EmployeeID,EmployeeName,ProjectName,JobTitle,MobileNumber,DateOfSim,SimNumber,MCG,Active FROM [Telecom].[dbo].[Employee];";
//constructor of listBooks
public ListBooks() {
//for setting the title for the internal frame
super("Employee", false, true, false, true);
//for setting the icon
setFrameIcon(new ImageIcon(ClassLoader.getSystemResource("images/List16.gif")));
setLocale(new java.util.Locale("ar", "SA", ""));
//for getting the graphical user interface components displaygvk area
Container cp = getContentPane();
//for bassing the required information to the ResultSetTableModel object
try {
tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL, DEFAULT_QUERY);
//for setting the Query
try {
tableModel.setQuery(DEFAULT_QUERY);
}
catch (SQLException sqlException) {
}
}
catch (ClassNotFoundException classNotFound) {
System.out.println(classNotFound.toString());
}
catch (SQLException sqlException) {
System.out.println(sqlException.toString());
}
//for setting the table with the information
table = new JTable(tableModel);
//for setting the size for the table
table.setPreferredScrollableViewportSize(new Dimension(990, 200));
//for setting the font
table.setFont(new Font("Tahoma", Font.PLAIN, 12));
//for setting the scrollpane to the table
scrollPane = new JScrollPane(table);
//for setting the size for the table columns
for (int i = 0; i < 9; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0) //BookID
column.setPreferredWidth(20);
if (i == 1) //Subject
column.setPreferredWidth(100);
if (i == 2) //Title
column.setPreferredWidth(150);
if (i == 3) //Auther
column.setPreferredWidth(50);
if (i == 4) //Publisher
column.setPreferredWidth(70);
if (i == 5) //Copyright
column.setPreferredWidth(40);
if (i == 6) //Edition
column.setPreferredWidth(40);
if (i == 7) //Pages
column.setPreferredWidth(40);
if (i == 8) //NumberOfBooks
column.setPreferredWidth(80);
}
//for setting the font to the label
northLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
//for setting the layout to the panel
northPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//for adding the label to the panel
northPanel.add(northLabel);
//for adding the panel to the container
cp.add("North", northPanel);
//for setting the layout to the panel
centerPanel.setLayout(new BorderLayout());
//for creating an image for the button
ImageIcon printIcon = new ImageIcon(ClassLoader.getSystemResource("images/Print16.gif"));
//for adding the button to the panel
printButton = new JButton("print the books", printIcon);
//for setting the tip text
printButton.setToolTipText("Print");
//for setting the font to the button
printButton.setFont(new Font("Tahoma", Font.PLAIN, 12));
//for adding the button to the panel
centerPanel.add(printButton, BorderLayout.NORTH);
//for adding the scrollpane to the panel
centerPanel.add(scrollPane, BorderLayout.CENTER);
//for setting the border to the panel
centerPanel.setBorder(BorderFactory.createTitledBorder("Books:"));
//for adding the panel to the container
cp.add("Center", centerPanel);
//for adding the actionListener to the button
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Thread runner = new Thread() {
public void run() {
try {
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(new PrintingBooks(DEFAULT_QUERY));
if (!prnJob.printDialog())
return;
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
prnJob.print();
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
catch (PrinterException ex) {
System.out.println("Printing error: " + ex.toString());
}
}
};
runner.start();
}
});
//for setting the visible to true
setVisible(true);
//to show the frame
pack();
}
}
I got the following error
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid string
or buffer length
You should try this
for (int i = 0; i < 9; i++)
column = table.getColumnModel().getColumn(i+1);
instead of this
for (int i = 0; i < 9; i++)
column = table.getColumnModel().getColumn(i);
Maybe it works.

Adding a list of images in jscrollpane and show it

I need to add some images in jscrollpane and show the correct image when my jlist string is selected with relative image... but i have some doubt to do it.
public class Tela{
private JList<String> list;
public Tela(){
JFrame display = new JFrame();
display.setTitle("Maquina de Refrigerante");
String labels[] = { "Coca-Cola", "Fanta Laranja", "Fanta-Uva",
"Sprite"};
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel secondPanel = new JPanel();
//downPanel.add(BorderLayout.SOUTH);
//downPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 30, 260));
secondPanel.setBackground(Color.WHITE);
secondPanel.setPreferredSize(new Dimension(110,110));
final JButton comprar = new JButton("Comprar");
comprar.setEnabled(false);
list = new JList<String>(labels);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
list.setSelectedIndex(0);
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
firstPanel.add(pane);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int selections[] = list.getSelectedIndices();
//String selectedValue = list.getSelectedValue();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println("Value" + selectionValues[i] );
}}
comprar.setEnabled(true);
}
});
ImageIcon image = new ImageIcon("assets/fantalogo.jpg");
JScrollPane jsp = new JScrollPane(new JLabel(image));
panel.add(jsp);
buttonPanel.add(comprar);
buttonPanel.add(Box.createRigidArea(new Dimension(0,4)));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.add(firstPanel);
panel.add(secondPanel);
panel.add(buttonPanel);
//panel.add(buttonPanel, BorderLayout.CENTER);
panel.setBackground(Color.BLACK);
display.add(panel);
display.setSize(550, 500);
display.setLocationRelativeTo(null);
display.setDefaultCloseOperation(display.EXIT_ON_CLOSE);
display.setVisible(true);
comprar.addActionListener(new Paga());
}
}
in my code how i can implemments it and view the correctly output?
Take a look at the section from the Swing tutorial on How to Use Combo Boxes. You find an example that does almost exactly what you want. The example uses a combo box, but the code for a JList will be very similar. That is the combo box contains a list of Strings and when you select an item the matching image is displayed.

Dynamic JPanel with objects not displaying

Can someone take a look at this part of my code and tell me why it won't return the objects inside the JPanel? It definitely goes inside the loop since I tried printing statements inside. Also this JPanel object is being put inside a TabbedPane just for clarification. Let me know if I need to explain in more detail or show more code to find a solution. Thanks.
JPanel createTipTailoringPanel(TipCalcModel model)
{
JPanel content = new JPanel();
int size = model.getNumOfPeople();
content.removeAll();
content.updateUI();
content.setLayout(new GridLayout(0,4));
JTextField text[] = new JTextField[size];
JSlider slider[] = new JSlider[size];
JLabel label[] = new JLabel[size];
JLabel cash[] = new JLabel[size];
if(size == 0)
{
return content;
}
else
{
for(int i=0; i<size; i++)
{
text[i] = new JTextField();
slider[i] = new JSlider();
label[i] = new JLabel("$");
cash[i] = new JLabel();
content.add(text[i]);
content.add(slider[i]);
content.add(label[i]);
content.add(cash[i]);
}
return content;
}
}
Here is my calling method and the actionlistener that I use to pass in the numberofpeople:
TipCalcView(TipCalcModel model)
{
setTitle("Tip Calculator");
JTabbedPane tabbedPane = new JTabbedPane();
getContentPane().add(tabbedPane);
tabbedPane.addTab("Main Menu", createMainPanel());
tabbedPane.setSelectedIndex(0);
tabbedPane.addTab("Tip Tailoring", createTipTailoringPanel(model));
tabbedPane.addTab("Config Panel", createConfigPanel());
}
class GuestsListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int userInput = 0;
try{
userInput = m_view.getGuests();
m_model.setNumOfPeople(userInput);
m_view.createTipTailoringPanel(m_model);
}
catch(NumberFormatException nfex)
{
m_view.showError("Bad input: '" + userInput + "'");
}
}
}
I suspect that your problem is outside of the code you listed. Here's a simplified working example:
public static void main(String[] args) {
JFrame frame = new JFrame();
DynamicJPanel dynamic = new DynamicJPanel();
frame.add(dynamic.createTipTailoringPanel(3));
frame.pack();
frame.setVisible(true);
}
JPanel createTipTailoringPanel(int size) {
JPanel content = new JPanel();
content.setLayout(new GridLayout(0, 4));
for (int i = 0; i < size; i++) {
content.add(new JTextField());
content.add(new JSlider());
content.add(new JLabel("$"));
content.add(new JLabel());
}
return content;
}
First, since you don't use the arrays anywhere, it could be shortened to:
JPanel createTipTailoringPanel(TipCalcModel model)
{
JPanel content = new JPanel();
int size = model.getNumOfPeople();
content.setLayout(new GridLayout(0,4));
if(size == 0)
{
return content;
}
else
{
for(int i=0; i<size; i++)
{
content.add(new JTextField());
content.add(new JSlider());
content.add(new JLabel("$"));
content.add(new JLabel());
}
return content;
}
}
Second, seems like you add an empty components to the panel, maybe that's what you actually get?
Third, add you need to add the content panel to the JFrame (or other container) once it returns from the method above.

Categories