I've searched and searched and found like 800 solutions, but none of 'em seems to work with my problem. I'm removing an item from a JList using a JButton, and then i want to refresh the GUI in the actionPerformed method. But things like repaint() or updateUI() hasn't helped. Here is my code:
public class Watchlist3 extends JPanel {
public static ArrayList<String> stocks = new ArrayList<String>();
JButton addStock, removeStock, viewStock, updaterInterval;
JLabel stocksAdded, currentInterval, listTitle;
JList stocklist;
JScrollPane listScroller;
public Watchlist3(JFrame frame) {
super(new BorderLayout());
//Adding some sample-components to the list
stocks.add("PLUG");
stocks.add("IDN");
stocks.add("GOOG");
//Create the components
addStock = new JButton("Add Stock");
addStock.setOpaque(true);
addStock.setBackground(Color.RED);
add(addStock, BorderLayout.LINE_START);
removeStock = new JButton("Remove Stock");
removeStock.setOpaque(true);
removeStock.setBackground(Color.YELLOW);
removeStock.putClientProperty("SENT_FRAME", frame);
add(removeStock, BorderLayout.LINE_END);
stocklist = new JList(stocks.toArray());
stocklist.setOpaque(true);
stocklist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
stocklist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
add(listScroller = new JScrollPane(stocklist), BorderLayout.CENTER);
removeStock.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int index = stocklist.getSelectedIndex();
if(index != -1){
stocks.remove(index);
System.out.println(stocks);
/* Here is where id like to refresh the gui! */
}
} catch (Exception ex) {}
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
final JFrame frame = new JFrame("Watchlist");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Watchlist3 newContentPane = new Watchlist3(frame);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Thanks in advance
You are removing from stocks List collection but not updating the JList model.
To update list model you need put this
// Add this item to the list and refresh
// convert stock list to Object array becuase seListData accept Object[]
Object[] array = stocks.toArray(new Object[stocks.size()]);
stocklist.setListData(array);
listScroller.revalidate();
listScroller.repaint();
Related
I try to initiate a "JTable", I added all my elements through the form designer and initiated them in the main function of my GUI.
The table is placed inside a "JScrollPanel" and used a "DefaultTableModel" to add the headers and rows.
Whatever I did, I can't make the table to display headers or rows.
What am I missing here?
class Controls extends JPanel{
private JButton compileButton;
private JPanel controls;
private JTabbedPane tabbedPane1;
private JButton insertButton;
private JTable insertedFilesTable;
private JScrollPane insertedFilesViewport;
private JPanel minify;
private JFileChooser insertChooser;
public Controls () {
insertChooser = new JFileChooser();
compileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
initCompile();
}
});
insertButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonActionPerformed(e);
}
});
}
public void main () {
JFrame frame = new JFrame("Controls");
frame.setLayout(new SpringLayout());
frame.setContentPane(new Controls().controls);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Files");
model.addColumn("Status");
insertedFilesTable = new JTable(model);
insertedFilesViewport = new JScrollPane(insertedFilesTable);
insertedFilesViewport.setViewportView(insertedFilesTable);
insertedFilesTable.setFillsViewportHeight(true);
String[] data = {"test","test"};
model.addRow(data);
frame.add(insertedFilesViewport);
frame.setSize(500,500);
frame.setVisible(true);
}
private void buttonActionPerformed(ActionEvent evt) {
insertChooser.showSaveDialog(this);
}
}
frame.setLayout(new SpringLayout());
....
frame.add(insertedFilesViewport);
Don't change the layout of the frame to a SpringLayout. There is no reason to do this.
The reason you don't see the scroll pane containing the table is because you didn't use any constraints for the add(...) method. Read the section from the Swing tutorial on How to Use SpringLayout to see how complex the constraints are for adding components.
If you leave the layout as the default BorderLayout, then the component will be added to the CENTER of the BorderLayout by default. The above tutorial also has a section on How to Use BorderLayout you should read.
I am trying to use a layered pane to make a menu for a program I'm working on, but the button won't display. I can't seem to figure out what it is...
public class FlashcardGUI {
public static void main(String[] args)
{
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
projectFrame.setContentPane(projectLayeredPane);
JPanel projectMenu1 = new JPanel();
projectLayeredPane.setLayer(projectMenu1, 0);
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
projectFrame.add(projectLayeredPane);
projectLayeredPane.add(projectMenu1);
projectMenu1.add(startNow);
}
}
Put these two lines at the end of your main method. The order is important in order to make the button display.
projectFrame.pack();
projectFrame.setVisible(true);
(Make sure to remove the projectFrame.setVisible(true); you already have on line 9.)
I have updated your code and it is working now. Please see the inline comments for the issue in your code. Hope this helps.
public class FlashcardGUI2 {
public static void main(String[] args) {
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
LayoutManager layout = new FlowLayout(); //creating a FlowLayout object
projectLayeredPane.setLayout(layout); //adding the layout to JLayeredPane
//because JLayeredPane do not have default layout of
//its own. The reason you were not
//getting the button displayed
projectLayeredPane.setPreferredSize(new Dimension(300, 310));
JPanel projectMenu1 = new JPanel();
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
projectLayeredPane.add(projectMenu1,new Integer(50));
projectLayeredPane.add(startNow,new Integer(10));
projectFrame.add(projectLayeredPane);
projectFrame.pack();
}
}
I need to refresh drop down list item just before doping down. I choose focusGained event. But when I do deactivate/activate form I have two events fired in actionPerformed that prints out :
***null
***aaa
I was not duing any dropdown selection why they are there?
Is focusGained right place to refresh items in JComboBox? What is better place of doing that?
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxDemo extends JPanel
implements ActionListener , FocusListener {
JLabel picture;
public ComboBoxDemo() {
super(new BorderLayout());
JComboBox petList = new JComboBox();
petList.addItem("1");
petList.addItem("2");
petList.addItem("3");
petList.addActionListener(this);
petList.addFocusListener(this);
add(petList, BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder(200,200,200,200));
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
System.out.println("***"+ petName);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ComboBoxDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void focusGained(FocusEvent fe) {
JComboBox cb = (JComboBox)fe.getSource();
cb.removeAllItems();
cb.addItem("aaa");
}
public void focusLost(FocusEvent fe) {
}
}
As part of my Diploma in Software Dev we have to create a Java GUI to manage a Soccer League. My group has produced numerous JPanels that in the click-through prototype we put into JTabbedPane. This worked fine up until now where I'm moving them into separate files and into a MVC layout.
I'm using a window class to hold the top level JFrame and menubar and adding in the tabbed panes to that. This works fine in the constructor but when I remove them from the constructor and try to add them from the Bootstrap via the Window.attachTabbedPanel(String name, JPanel panel) it doesn't display but querying tabbedPane.getTabCount() display an incrementing number of tabs.
Here's a stripped back set of code:
The Bootstrap file:
public class Bootstrap {
private Window mainWindow;
public Bootstrap() {
//Window class is our containing JFrame and JMenuBar
mainWindow = new Window();
//Load up our view classes
TestTab tab1 = new TestTab();
TestTab tab2 = new TestTab();
//Attach them
mainWindow.attachTabbedPanel("Tab1", tab1.getScreen());
mainWindow.attachTabbedPanel("Tab2", tab2.getScreen());
} // Bootstrap()
public gui.Window getWindow(){
return mainWindow;
}
} // Bootstrap
This is called by the Main file:
public class Main {
public static void main(String[] args) {
Bootstrap RunMVC = new Bootstrap();
gui.Window mainWindow = RunMVC.getWindow();
mainWindow.run();
} // main()
} // Main
The problem starts here at the Window class, I've added in a In Constructor tab to check I haven't stuffed up the tabbedPane but it works fine at that point.
public class Window {
private JFrame frame;
private JMenuBar menuBarMain;
private JMenu mnFile;
private JTabbedPane tabbedPane;
private int count;
/**
* Create the application.
*/
public Window() {
//Build the frame
frame = new JFrame();
frame.setBounds(100, 100, 1280, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
//End Build frame
TestTab conTab = new TestTab();
//Add the tabbed pane to hold the top level screens
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, "name_1");
tabbedPane.addTab("In Consructor", conTab.getScreen());
count = 1;
}
public void attachTabbedPanel(String name, JPanel panel){
System.out.println("Window: adding Jpanel name: "+name);
System.out.println("panel is a: "+panel);
tabbedPane.addTab(name, panel);
tabbedPane.updateUI();
System.out.println("Number of tabs: "+tabbedPane.getTabCount());
System.out.println("Last Tab .isEnabledAt() "+tabbedPane.isEnabledAt(count++));
tabbedPane.updateUI();
}
/**
* Launch the window.
*/
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
And lastly the Panel:
public class TestTab {
private JPanel screen;
private JLabel lblSeason;
private JButton btnEdit;
private JLabel lblRounds;
public JPanel getScreen() {
return screen;
}
/**
* Initialize the contents of the frame.
*/
public TestTab() {
screen = new JPanel();
screen.setLayout(new MigLayout("", "[8%,right][10%,left][8%,right][10%,left][grow][50%]", "[][][grow]"));
lblSeason = new JLabel("Test");
screen.add(lblSeason, "flowx,cell 0 0");
btnEdit = new JButton("Edit Test");
screen.add(btnEdit, "cell 5 0,alignx right");
lblRounds = new JLabel("More Testing");
screen.add(lblRounds, "cell 0 1,alignx left");
}
}
Your error is here:
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You are using new instance of window instead of using created earlier, try to use this code
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
updateUI() does not do what you think it does. It should never be called directly - it is called from the superclass constructor to allow the Swing look and feel delegate to initialize itself.
Eliminating the call to updateUI() may solve your problem; or if the tabbed pane is already on screen, you may need to force a repaint/revalidate - the incantation for that is invalidate(); revalidate(); repaint();.
I have a jTextField , and I set it's value to a certain sum when I create the frame.
Here is the initiation code:
totalTextField.setText(
itemsPriceTextField.getText() +
Float.toString(orderDetails.delivery)
);
This textfield should show a sum of items selected by the user.
The selection is done on a different frame, and both frames are visible / invisible
at a time.
The user can go back and forth and add / remove items.
Now, every time i set this frame visible again, I need to reload the value set to that field
(maybe no changes were made, but if so, I need to set the new correct sum) .
I'm quite desperate with it.
Can anyone please give me a clue?
Thanks in advance! :)
Before setting the frame visible again, one should update the fields with the new values / states.
something like:
jTextField.setText("put your text here");
jRadioButton.setSelected(!isSelected());
.
/* update all you need */
.
jFrame.setVisible(true);
The frame will come up with the new values / states.
Add a WindowListener to the frame. Then you can handle the windowActivated event and reset the text of the text field.
See How to Write Window Listeners.
Use a DocumentListener triggering the JTextField public void setText(String t)
Here an example with DocumentListener:
public class SetTextInJTextField extends JFrame implements DocumentListener {
JTextField entry;
JTextField entryToSet = new JTextField();
public SetTextInJTextField() {
createWindow();
entry.getDocument().addDocumentListener(this);
}
private void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createUI(final JFrame frame) {
JPanel panel = new JPanel();
entry = new JTextField();
entryToSet = new JTextField();
LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.add(this.entry);
panel.add(entryToSet);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
public void setTextInTargetTxtField() {
String s = entry.getText();
entryToSet.setText(s);
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void removeUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void changedUpdate(DocumentEvent ev) {
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SetTextInJTextField().setVisible(true);
}
});
}
}
inspired from: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextFieldDemoProject/src/components/TextFieldDemo.java
related lesson: https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html