DevDavid DevDavid - 1 year ago 166
Java Question

Update a JTabbedPane when item added to JList

I have two tabs in a Java program. One to add a stock and another to list stocks that I have created. I have tried to find away to update my list of items in the first tab when I a new item in my second tab. Any Ideas?

I want the first tab to show a list of items i am creating in the second tab...

public class StocksGUI extends javax.swing.JFrame {

private JTextField stock, qty, purchasePrice, currentPrice;
private JButton addStockButton;
private JList<StockClass> stockList;
private DefaultListModel<StockClass> stockModel;

public StocksGUI()
super("Portfolio Management");
stock = new JTextField();
qty = new JTextField();
purchasePrice = new JTextField();
currentPrice = new JTextField();
addStockButton = new JButton("Add Stock");

stockList = new JList<>();
stockModel = new DefaultListModel<StockClass>();

JTabbedPane tab =new JTabbedPane();

JPanel p2 = new JPanel();
if(stockModel.size() > 1)
p2.add(new JScrollPane(stockList));
p2.add(new JLabel("Currently No Stocks"));
tab.addTab("List",null, p2, " Panel #2");

JPanel p1 = new JPanel(new GridLayout(5,2));
p1.add(new JLabel("Stock"));
p1.add(new JLabel("Quantity"));
p1.add(new JLabel("Purchase Price"));
p1.add(new JLabel("Current price"));
tab.addTab("Add Stock",null, p1," Panel #1");


TickerAdd ta = new TickerAdd();
TickerAdd.StockADD stad = StockADD();


public class TickerAdd
public class StockADD implements ActionListener
public void actionPerformed(ActionEvent e)

StockClass passing = new StockClass();
passing.stock = stock.getText();
passing.qty = Integer.parseInt(qty.getText());
passing.pp = Double.parseDouble(purchasePrice.getText());
passing.cp = Double.parseDouble(currentPrice.getText());

StockBackEnd sh = new StockBackEnd();





Enter the data here:

Data goes in

And data should show here:

Data out

Answer Source

You need to add the JScrollPane containing JList to your GUI. Your code doesn't do that, and so the list never shows. Yes, you've got code to do this, but its within an if block, a block whose code is called only once at a time when the if condition is guaranteed to be false. So either get rid of the if block and call that code regardless of the model's size, or else have the swapping code within your action listener so that it is called more than once. Note also that it's better and easier to swap using a CardLayout.

Also you'll want to add your model once to the JList at the program start.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download