This question already has answers here:
How to Remove an icon on a JButton?
(3 answers)
Closed 5 years ago.
I am working on the Tic Tac application all things are set but the only problem is that I am using images on the Button and I want to make a restart button when this restart Button pressed I want that all the images on the Button should be removed. I have also tried to setIcon(null) but when the Restart button press image is removed and one another problem arises is that Button's get disabled and I am not able to play again.
Is there is any other methods available to remove the icon from the Button?
The OP issue is more than setIcon(null), so I am giving this reply,
Try below source code, but there is a good multi pane scenario for you:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* Used resources within this class or illustration done within is just for the
* study purpose.
*/
public class ImageExample extends JFrame {
private static final long serialVersionUID = 1L;
/*
* used fixed images resource, you can take all directory resources as per your
* need
*/
private String[] leopard = new String[] { "leopard0", "leopard1", "leopard2", "leopard3" };
private URL url;
private JLabel label1, label2, label3, label4;
private ArrayList<Integer> index = new ArrayList<Integer>();
public ImageExample() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageExample();
}
});
}
private void init() {
setTitle("Add And Remove Image");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setBounds(400, 150, 625, 400);
for (int i = 0; i < leopard.length; i++)
index.add(i);
GridBagConstraints c = new GridBagConstraints();
JPanel panel = new JPanel(); // 1
panel.add(label1 = new JLabel(getIndexIcon(index.get(0))));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 2
panel.add(label2 = new JLabel(getIndexIcon(index.get(1))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 3
panel.add(label3 = new JLabel(getIndexIcon(index.get(2))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 4
panel.add(label4 = new JLabel(getIndexIcon(index.get(3))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.weighty = 0.0;
c.gridx = 1;
c.gridy = 1;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // contains JButtons
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 2;
add(panel, c);
final JButton prev = new JButton("Previous");
final JButton addImage = new JButton("Add Image");
final JButton removeImage = new JButton("Remove Image");
final JButton next = new JButton("Next");
addImage.setEnabled(false);
panel.add(prev);
panel.add(addImage);
panel.add(removeImage);
panel.add(next);
prev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, revalidateIndex(0, index.get(0) - 1));
revalidateLabel(label2, revalidateIndex(1, index.get(1) - 1));
revalidateLabel(label3, revalidateIndex(2, index.get(2) - 1));
revalidateLabel(label4, revalidateIndex(3, index.get(3) - 1));
}
});
addImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, index.get(0));
revalidateLabel(label2, index.get(1));
revalidateLabel(label3, index.get(2));
revalidateLabel(label4, index.get(3));
addImage.setEnabled(false);
removeImage.setEnabled(true);
prev.setEnabled(true);
next.setEnabled(true);
removeImage.requestFocus();
}
});
removeImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
removeLabelImage(label1);
removeLabelImage(label2);
removeLabelImage(label3);
removeLabelImage(label4);
prev.setEnabled(false);
next.setEnabled(false);
removeImage.setEnabled(false);
addImage.setEnabled(true);
addImage.requestFocus();
}
});
next.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, revalidateIndex(0, index.get(0) + 1));
revalidateLabel(label2, revalidateIndex(1, index.get(1) + 1));
revalidateLabel(label3, revalidateIndex(2, index.get(2) + 1));
revalidateLabel(label4, revalidateIndex(3, index.get(3) + 1));
}
});
setVisible(true);
}
private ImageIcon getIndexIcon(int indexAt) {
if (indexAt < 0)
indexAt = leopard.length - 1;
if (indexAt > (leopard.length - 1))
indexAt = 0;
url = ImageExample.class.getResource("/resources/leopard" + indexAt + ".jpg");
ImageIcon icon = new ImageIcon(url.getPath());
return icon;
}
private void revalidateLabel(JLabel label, int indexAt) {
label.setIcon(getIndexIcon(indexAt));
label.revalidate();
}
private void removeLabelImage(JLabel label) {
label.setIcon(null);
label.revalidate();
}
private int revalidateIndex(int indexAt, int indx) {
if (indx < 0)
indx = leopard.length - 1;
if (indx > (leopard.length - 1))
indx = 0;
index.set(indexAt, indx);
return indx;
}
}
Related
Problem and Code Summary:This will make sense if you run the code below. I'm using a JScrollPane and its scroll bar is disappearing when it is placed in a JPanel with a BorderLayout (NORTH). When the JPanel has a BorderLayout (CENTER), it works fine (with the scroll bar showing up). If you try to remove many of the components with the remove buttons, it gets annoying because the JScrollPane (with all of its components) clumps up in the middle of the JPanel it's in, when you want it to stay at the top. I tried to prevent this by obviously changing the BorderLayout of the JPanel from CENTER TO NORTH, but that just takes out the scroll bar completely. In the following code, the Main.placement (line 28) (change it to CENTER/NORTH to mess with it) controls the type of layout being used and line 171 shows how it is implemented. I just want to align the JSCrollPane at the top with the scroll bar showing up when it is neccessary.
Code Summary:
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main{
public static final String placement = BorderLayout.CENTER;
public static void main(String[] args){
new TimeChart(true);
}
}
#SuppressWarnings("serial")
class TimeChart extends JFrame {
private boolean admin;
private TimeTable timeTable;
private static final JLabel title;
private final JLabel volLabel;
static {
title = new JLabel("Time Chart ");
}
private class TimeTable extends JPanel {
private JScrollPane scrollPane;
private JPanel table;
public final ArrayList<SessionRow> sessionRows;
private final JButton addButton;
private final JButton applyButton;
private static final double weight_sessnum = 0.2;
private static final double weight_signinout = 1.0;
private static final double weight_time = 0.3;
private static final double weight_delete = 0.0;
public class SessionRow {
private final SessionRow thisSessionRow; // for inner classes
private JTextField sessionnum, signinField, signoutField, total;
private JButton removeButton;
private SessionRow(int y) {
thisSessionRow = this;
String signinstring = "*signin time*";
String signoutstring = "*signout time*";
sessionnum = new JTextField("Session " + y + ": ");
sessionnum.setEditable(false);
signinField = new JTextField(signinstring);
signinField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
signinField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
signinField.setEditable(admin);
signoutField = new JTextField(signoutstring);
signoutField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
signoutField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
signoutField.setEditable(admin);
String totalstring = null;
try {
totalstring = "*session total*";
} catch (Exception e) {
totalstring = " -- ";
}
total = new JTextField(totalstring);
total.setEditable(false);
removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thisSessionRow.remove();
sessionRows.remove(thisSessionRow);
revalidate();
repaint();
}
});
}
public void remove() {
table.remove(this.sessionnum);
table.remove(this.signinField);
table.remove(this.signoutField);
table.remove(this.total);
table.remove(this.removeButton);
}
}
public TimeTable() {
super();
table = new JPanel();
scrollPane = new JScrollPane(table);
applyButton = new JButton("<html><div style=\"text-align: center;\">Apply<br>Changes</html>");
applyButton.setMargin(new Insets(5, 5, 5, 5));
applyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
applyAllChanges();
}
});
applyButton.setEnabled(false);
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sessionRows.add(new SessionRow(sessionRows.size() + 1));
setupAll();
revalidate();
repaint();
if (!applyButton.isEnabled())
applyButton.setEnabled(true);
}
});
sessionRows = new ArrayList<SessionRow>();
setupSessionRows();
setupAll();
this.setLayout(new BorderLayout());
this.add(scrollPane, Main.placement); //PAY ATTENTION HERE
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setPreferredSize(new Dimension(30, 0));
bar.setUnitIncrement(10);
InputMap im = bar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke("down"), "positiveUnitIncrement");
im.put(KeyStroke.getKeyStroke("up"), "negativeUnitIncrement");
scrollPane.setBorder(BorderFactory.createLineBorder(Color.red));
this.setBorder(BorderFactory.createLineBorder(Color.green));
}
public void setupSessionRows() {
sessionRows.clear();
for (int i = 0; i < 30; i++) {
sessionRows.add(new SessionRow(i + 1));
}
System.gc();
}
public void setupAll() {
table.removeAll();
table.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 0, 5, 2);
c.gridx = 0;
c.gridy = 0;
initColumnHeader(c);
for (int y = 0; y < sessionRows.size(); y++) {
c.gridy++;
initSessRow(sessionRows.get(y), c);
}
c.gridy++;
if (admin) {
initNewButtonRow(c);
c.gridy++;
}
initTotalHeader(c);
}
public void initSessRow(SessionRow row, GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
table.add(row.sessionnum, c);
c.weightx = weight_signinout;
c.gridx = 1;
table.add(row.signinField, c);
c.weightx = weight_signinout;
c.gridx = 2;
table.add(row.signoutField, c);
c.weightx = weight_time;
c.gridx = 3;
table.add(row.total, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
table.add(row.removeButton, c);
}
}
public void initTotalHeader(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
JTextField totalLabel = new JTextField("Total: ");
totalLabel.setEditable(false);
table.add(totalLabel, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField blank1 = new JTextField();
blank1.setEditable(false);
table.add(blank1, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField blank2 = new JTextField();
blank2.setEditable(false);
table.add(blank2, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField totaltime = new JTextField("*TOTAL*");
totaltime.setEditable(false);
table.add(totaltime, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
table.add(applyButton, c);
}
}
public void initNewButtonRow(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
table.add(addButton, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField blank1 = new JTextField();
blank1.setEditable(false);
table.add(blank1, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField blank2 = new JTextField();
blank2.setEditable(false);
table.add(blank2, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField blank3 = new JTextField();
blank3.setEditable(false);
table.add(blank3, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
JTextField blank4 = new JTextField();
blank4.setEditable(false);
table.add(blank4, c);
}
}
public void initColumnHeader(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
JTextField sessnum = new JTextField("Session #");
sessnum.setEditable(false);
table.add(sessnum, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField signintime = new JTextField("Sign in Time");
signintime.setEditable(false);
table.add(signintime, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField signouttime = new JTextField("Sign out Time");
signouttime.setEditable(false);
table.add(signouttime, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField time = new JTextField("Time");
time.setEditable(false);
table.add(time, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
JTextField delete = new JTextField("Delete");
delete.setEditable(false);
table.add(delete, c);
}
}
#Override
public void revalidate() {
if (sessionRows != null) {
int i = 1;
for (SessionRow sr : sessionRows) {
sr.sessionnum.setText("Session " + i);
i++;
}
}
super.revalidate();
}
}
public TimeChart(boolean admin) {
super();
this.admin = admin;
volLabel = new JLabel("Billy");
timeTable = new TimeTable();
this.setSize(900, 900);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initFrame();
this.setVisible(true);
scrollDown();
}
public void initFrame() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 0;
this.add(title, c);
c.weightx = 1.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
this.add(volLabel, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 2;
this.add(timeTable, c);
}
public void scrollDown() {
JScrollBar bar = timeTable.scrollPane.getVerticalScrollBar();
bar.setValue(bar.getMaximum());
}
public void applyAllChanges() {
}
}
Thanks in advance, I really appreciate it.
I'm creating a simple gui of options that containing a JScrollPanel.
The problem is when I'm scrolling all the content of the JPanel inside my JScrollPanel doesn't refresh like that :
Bad Refresh Scrolling
Another issues is that not all my text fields are well painted and the combobox fields are behind the first text field.
Here my code :
OptionsPanel.java the source of the problem
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import scroll.NavigationButtons.Navigation;
public class OptionsPanel extends JPanel implements ActionListener, TextListener {
private static final long serialVersionUID = 3800714599366218432L;
private NavigationButtons navBtn;
private ChangeOptionCB language;
private ChangeOptionTF option1;
private ChangeOptionTF option2;
private ChangeOptionTF option3;
private ChangeOptionTF option4;
private ChangeOptionTF option5;
private ChangeOptionTF option6;
private ChangeOptionTF option7;
private JScrollPane scrollPane;
public OptionsPanel() {
super();
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints constraint = new GridBagConstraints();
JPanel optionsPanel = new JPanel();
GridBagLayout l = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
optionsPanel.setLayout(l);
String[] langues = {"en", "fr", "es"};
language = new ChangeOptionCB("Languages", langues);
language.addTextListener(this);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(language, c);
option1 = new ChangeOptionTF("option 1");
option1.addTextListener(this);
option1.setText("option 1");
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option1, c);
option2 = new ChangeOptionTF("option 2");
option2.addTextListener(this);
option2.setText("option 2");
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option2, c);
option3 = new ChangeOptionTF("option 3");
option3.addTextListener(this);
option3.setText("option 3");
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option3, c);
option4 = new ChangeOptionTF("option 4");
option4.addTextListener(this);
option4.setText("option 4");
c.gridx = 0;
c.gridy = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option4, c);
option5 = new ChangeOptionTF("option 5");
option5.addTextListener(this);
option5.setText("option 5");
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option5, c);
option6 = new ChangeOptionTF("option 6");
option6.addTextListener(this);
option6.setText("option 6");
c.gridx = 0;
c.gridy = 6;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option6, c);
option7 = new ChangeOptionTF("option 7");
option7.addTextListener(this);
option7.setText("option 7");
c.gridx = 0;
c.gridy = 7;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option7, c);
scrollPane = new JScrollPane(optionsPanel);
constraint.gridx = 0;
constraint.gridy = 0;
constraint.fill = GridBagConstraints.BOTH;
constraint.weightx = 1;
constraint.weighty = 1;
add(scrollPane, constraint);
navBtn = new NavigationButtons(NavigationButtons.EXIT);
navBtn.addActionListener(this);
constraint.gridx = 0;
constraint.gridy = 1;
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.weightx = 1;
constraint.weighty = 0.25;
add(navBtn, constraint);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (navBtn == ae.getSource()) {
int id = ae.getID();
if (Navigation.EXIT.getId() == id) {
System.out.println("Get out !!");
}
}
}
#Override
public void textValueChanged(TextEvent te) {
if (language == te.getSource()) {
System.out.println("The option as changed : "+language.getOption());
}
if (option1 == te.getSource()) {
System.out.println("The option as changed : "+option1.getNewText());
}
if (option2 == te.getSource()) {
System.out.println("The option as changed : "+option2.getNewText());
}
if (option3 == te.getSource()) {
System.out.println("The option as changed : "+option3.getNewText());
}
if (option4 == te.getSource()) {
System.out.println("The option as changed : "+option4.getNewText());
}
if (option5 == te.getSource()) {
System.out.println("The option as changed : "+option5.getNewText());
}
if (option6 == te.getSource()) {
System.out.println("The option as changed : "+option6.getNewText());
}
if (option7 == te.getSource()) {
System.out.println("The option as changed : "+option7.getNewText());
}
scrollPane.revalidate();
scrollPane.repaint();
}
}
The Main Class
package scroll;
import java.awt.Dimension;
import javax.swing.JFrame;
public class ScrollTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setContentPane(new OptionsPanel());
frame.setTitle("Scrool Test");
frame.pack();
Dimension dimension = new Dimension(691, 263);
frame.setSize(dimension);
frame.setPreferredSize(dimension);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
The different stuff that you need :
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.EventListenerList;
public class ChangeOptionCB extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private JComboBox cb;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionCB(String label, String[] list) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
jLabel.setHorizontalAlignment(SwingConstants.LEFT);
c.fill = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.1;
add(jLabel, c);
cb = new JComboBox(list);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.8;
add(cb, c);
saveBtn = new JButton("Save");
saveBtn.addActionListener(this);
c.gridx = 2;
c.gridy = 0;
c.weightx = 0;
c.anchor = GridBagConstraints.LINE_END;
add(saveBtn, c);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == saveBtn) {
fireTextAsChange();
}
}
public String getOption() {
return (String) cb.getSelectedItem();
}
public void addTextListener(TextListener listener) {
listeners.add(TextListener.class, listener);
}
public void removeActionListener(TextListener listener) {
listeners.remove(TextListener.class, listener);
}
private void fireTextAsChange(){
TextListener[] listenerList = (TextListener[])listeners.getListeners(TextListener.class);
for(TextListener listener : listenerList){
listener.textValueChanged(new TextEvent(this, 0));
}
}
}
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class ChangeOptionTF extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private TextField tf;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionTF(String label) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
add(jLabel, c);
tf = new TextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.5;
add(tf, c);
saveBtn = new JButton("Save");
saveBtn.addActionListener(this);
c.gridx = 2;
c.gridy = 1;
c.weightx = 0;
c.anchor = GridBagConstraints.LINE_END;
add(saveBtn, c);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == saveBtn) {
fireTextAsChange();
}
}
public String getNewText() {
return tf.getText();
}
public void addTextListener(TextListener listener) {
listeners.add(TextListener.class, listener);
}
public void removeActionListener(TextListener listener) {
listeners.remove(TextListener.class, listener);
}
private void fireTextAsChange(){
TextListener[] listenerList = (TextListener[])listeners.getListeners(TextListener.class);
for(TextListener listener : listenerList){
listener.textValueChanged(new TextEvent(this, 0));
}
}
public void setText(String text) {
tf.setText(text);
}
}
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class NavigationButtons extends JPanel implements ActionListener {
private static final long serialVersionUID = -4844499317626526067L;
public enum Navigation {
NEXT(1), CANCEL(0), EXIT(-1);
private int id;
private Navigation(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public static int NEXT_CANCEL = 0;
public static int CANCEL = 1;
public static int EXIT = 2;
private JButton cancel;
private JButton next;
private JButton exit;
private EventListenerList listeners;
public NavigationButtons(int type) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
if ((NEXT_CANCEL == type) || (CANCEL == type)) {
cancel = new JButton("Cancel");
cancel.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 1;
add(cancel, c);
}
if (NEXT_CANCEL == type) {
next = new JButton("Next");
next.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 0;
add(next, c);
}
if (EXIT == type) {
exit = new JButton("Exit");
exit.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1;
add(exit, c);
}
}
public void setNextEnable(boolean b) {
next.setEnabled(b);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == next) {
fireActionPerformed(Navigation.NEXT);
}
if (ae.getSource() == cancel) {
fireActionPerformed(Navigation.CANCEL);
}
if (ae.getSource() == exit) {
fireActionPerformed(Navigation.EXIT);
}
}
public void addActionListener(ActionListener listener) {
listeners.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listeners.remove(ActionListener.class, listener);
}
public void fireActionPerformed(Navigation nav){
ActionListener[] listenerList = (ActionListener[])listeners.getListeners(ActionListener.class);
for(ActionListener listener : listenerList){
listener.actionPerformed(new ActionEvent(this, nav.getId(), null));
}
}
}
What is wrong in my code that make this ugly refresh ? I don't understand.
Maybe I need to implement a kind of listener that repaint my frame each time I scroll ?
The more strange things is, if I replace
add(scrollPane, constraint);
by
add(optionsPane, constraint);
the content get out well (at least in this example).
Thank's you
Julien
The basic problem is, you're using java.awt.TextField which is a heavy weight component inside a lighweight container. This is just asking for issues, they tend not to play well together.
Instead, use a javax.swing.JTextField
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;
public class ChangeOptionTF extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private JTextField tf;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionTF(String label) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
add(jLabel, c);
tf = new JTextField();
I have a problem with my login screen. Somehow it is not being correctly.
All the objects (JLabel,JButton,JTextfield etc.) is not being displayed correctly. This is how it should look:
It only appears once I resize the screen size by pulling at the window border.
The JFrame contains 2 JPanels as tabs. This is the code:
Login.java
package de.immozukunft.windows;
import javax.swing.*;
import de.immozukunft.tabs.LoginTab;
import de.immozukunft.tabs.MySQLConnectionTab;
import java.awt.BorderLayout;
import java.util.Locale;
import java.util.ResourceBundle;
public class Login {
/**The Login class implements the LoginTab and the MySQLConnectionTab
* to verify the user access*/
//String management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
JFrame window = new JFrame();
//Constructor
public Login() {
window.setTitle(r.getString("userlogin"));
frame();
}
//Frame method
private void frame() {
window.setSize(400,250);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
}
}
LoginTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.persons.UserDetails;
import de.immozukunft.programs.MySQL;
import de.immozukunft.windows.ButtonPanel;
public class LoginTab extends JPanel {
/** LoginTab does the userverfication by
* comparing the entered data with the MySQL-database
* There is no encryption implemented*/
private static final long serialVersionUID = 1L;
//Multilingual String-Management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
// static Connection con = null;
static Statement stnt = null;
static ResultSet rs = null;
//Constructor
public LoginTab(final JFrame window) {
panelMethod(window);
}
// LOGIN ITEMS
JLabel usernameLbl = new JLabel(r.getString("username"));
JLabel passwordLbl = new JLabel(r.getString("password"));
JTextFieldImmo usernameFld = new JTextFieldImmo(15);
JPasswordField passwordFld = new JPasswordField(15);
JButton loginBtn = new JButton(r.getString("login"));
JButton registerUserBtn = new JButton(r.getString("newUser"));
public void panelMethod(final JFrame window) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Insets
c.insets = new Insets(4, 5, 0, 0);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
this.add(usernameLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
this.add(usernameFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
this.add(passwordLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
this.add(passwordFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
this.add(loginBtn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
this.add(registerUserBtn, c);
// Actions Listener
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
MySQL.connect();
String username = usernameFld.getText().trim();
String password = String.valueOf(passwordFld.getPassword()).trim();
String sql = "SELECT username,password from per_user where username = '"
+ username + "'and password = '" + password + "'";
stnt = MySQL.getCon().createStatement();
rs = stnt.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
//JOptionPane.showMessageDialog(null, "User Found, Access Granded!"); //TODO String
window.setVisible(false);
window.dispose();
new ButtonPanel();
} else if (count > 1) {
JOptionPane.showMessageDialog(null,
"Duplicate User, Access Denied!"); // TODO String einfügen
} else {
JOptionPane.showMessageDialog(null, r.getString("userNotFound"));
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, r.getString("unableToConnectMySQL"));
e1.printStackTrace();
}
}
});
registerUserBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new UserDetails();
}
});
passwordFld.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
loginBtn.doClick();
}
});
}
}
MySQLConnectionTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.*;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.programs.MySQL;
public class MySQLConnectionTab extends JPanel { //Subclass of Jframe, with ActionListener as interface
/** MySQLConnectionTab is a JPanel which can be implemented
* in other JTabbedPanes in order to change the MySQL connection settings
*/
private static final long serialVersionUID = 1L;
private JButton connectBtn = new JButton(r.getString("connect")); //Connect-Button
private JButton cancelBtn = new JButton(r.getString("cancel")); //Cancel-Button
private JTextFieldImmo hostFld = new JTextFieldImmo(MySQL.getHost(), 20); // Host text field
private JTextFieldImmo usernameFld = new JTextFieldImmo(MySQL.getUsername(), 20); // Username text field
private JTextFieldImmo databaseFld = new JTextFieldImmo(MySQL.getDatabase(), 20); // Database text field
private JTextFieldImmo portFld = new JTextFieldImmo(String.valueOf(MySQL.getPort()), 20); // Port text field
private JPasswordField passwordFld = new JPasswordField(MySQL.getPassword(), 20); // Password text field
private JLabel hostLbl = new JLabel(r.getString("host")); // Host text label
private JLabel usernameLbl = new JLabel(r.getString("username")); // Username text label
private JLabel databaseLbl = new JLabel(r.getString("database")); // Database text label
private JLabel portLbl = new JLabel(r.getString("port")); // Port text label
private JLabel passwordLbl = new JLabel(r.getString("password")); // Password text label
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
//Constructor
public MySQLConnectionTab() {
panelMethod();
}
public void panelMethod(){
//Create GridBagConstraints
GridBagConstraints c2 = new GridBagConstraints();
//SetLayout to GridBagLayout
this.setLayout(new GridBagLayout());
//Insets
c2.insets = new Insets(4, 5, 0, 0);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 0;
this.add(hostLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 0;
this.add(hostFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 1;
this.add(usernameLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 1;
this.add(usernameFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 2;
this.add(databaseLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 2;
this.add(databaseFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 3;
this.add(portLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 3;
this.add(portFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 4;
this.add(passwordLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 4;
this.add(passwordFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 5;
this.add(connectBtn, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 5;
this.add(cancelBtn, c2);
connectBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//All the field data is being set for the MySQL-connection
MySQL.setHost(hostFld.getText());
MySQL.setUsername(usernameFld.getText());
MySQL.setDatabase(databaseFld.getText());
MySQL.setPort(Integer.parseInt(portFld.getText()));
MySQL.setPassword(String.valueOf(passwordFld.getPassword()));
JOptionPane.showMessageDialog(null, String.format("%s", MySQL.getStatus()));
}
}); // Add ActionListener for connect Button
cancelBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
hostFld.setText(MySQL.getHost());
usernameFld.setText(MySQL.getUsername());
databaseFld.setText(MySQL.getDatabase());
portFld.setText(String.valueOf(MySQL.getPort()));
passwordFld.setText(MySQL.getPassword());
}
}); // Add ActionListener for cancel Button
}
}
I am still a beginner.
It's because you are calling setVisible before you add components. Call setVisible after you add components on your JFrame.
Basically:
//Frame method
private void frame() {
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
//window.setSize(400,250);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
Also, call pack instead of setSize. Size of your JFrame will be based on preferred sizes of components within of JFrame and gaps between those components.
How to update a Java frame with changed content?
I want to update a frame or just the panel with updated content. What do I use for this
Here is where I want to revalidate the frame or repaint mainpanel or whatever will work
I have tried a number of things, but none of them have worked.
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else {
openURL(e.getActionCommand());
}
}
Here is the whole java file
/*
*
*
*/
package build;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import java.util.Arrays;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/*
* ButtonDemo.java requires the following files:
* images/right.gif
* images/middle.gif
* images/left.gif
*/
public class StockTable extends JPanel
implements ActionListener {
static int multi = 1;
int roll = 0;
static TextVars textvars = new TextVars();
static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
"seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
JFrame frame;
JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right;
JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()];
JLabel label[] = new JLabel[textvars.getNumberOfStocks()];
JLabel headlabel, dayspan, namelabel;
JRadioButton radioButton;
JButton button;
JScrollPane scrollpane;
int wid = 825;
public JPanel createContentPane() {
mainpanel = new JPanel();
mainpanel.setPreferredSize(new Dimension(wid, 800));
mainpanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(wid, 25));
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel1, c);
// Panel 2------------
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(wid, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel2, c);
panel2left = new JPanel();
panel2left.setPreferredSize(new Dimension(270, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2left, c);
panel2center = new JPanel();
panel2center.setPreferredSize(new Dimension(258, 51));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2center, c);
panel2right = new JPanel();
panel2right.setPreferredSize(new Dimension(270, 51));
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2right, c);
// ------------------
panel3 = new JPanel();
panel3.setLayout(new GridBagLayout());
scrollpane = new JScrollPane(panel3);
scrollpane.setPreferredSize(new Dimension(wid, 675));
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0,0,0,0);
mainpanel.add(scrollpane, c);
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
//b1 = new JButton("Disable middle button", leftButtonIcon);
//b1.setVerticalTextPosition(AbstractButton.CENTER);
//b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
//b1.setMnemonic(KeyEvent.VK_D);
//b1.setActionCommand("disable");
//Listen for actions on buttons 1
//b1.addActionListener(this);
//b1.setToolTipText("Click this button to disable the middle button.");
//Add Components to this container, using the default FlowLayout.
//add(b1);
headlabel = new JLabel("hellorow1");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(headlabel, c);
radioButton = new JRadioButton("Percentage");
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Days Range");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Open / Close");
c.gridx = 4;
c.gridy = 0;
c.insets = new Insets(0, 0, 0,0 );
panel1.add(radioButton, c);
button = new JButton("<<");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("reverse");
button.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2left.add(button, c);
dayspan = new JLabel("hellorow2");
dayspan.setHorizontalAlignment(JLabel.CENTER);
dayspan.setVerticalAlignment(JLabel.CENTER);
dayspan.setPreferredSize(new Dimension(270, 50));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2center.add(dayspan, c);
button = new JButton(">>");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("advance");
button.addActionListener(this);
if (multi == 0) {
button.setEnabled(false);
}
else {
button.setEnabled(true);
}
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2right.add(button, c);
int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7;
ArrayList<String[]> stocknames = textvars.getStockNames();
ArrayList<String[]> stocks = textvars.getStocks();
for (int column = 0; column < 8; column++) {
for (int row = 0; row < textvars.getNumberOfStocks(); row++) {
if (column==0) {
if (row==0) {
namelabel = new JLabel(stocknames.get(0)[0]);
namelabel.setVerticalAlignment(JLabel.CENTER);
namelabel.setHorizontalAlignment(JLabel.CENTER);
namelabel.setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
panel3.add(namelabel, c);
}
else {
stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon);
stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER);
stknames_btn[row].setActionCommand(stocknames.get(row)[1]);
stknames_btn[row].addActionListener(this);
stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]);
stknames_btn[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
//scrollpane.add(stknames[row], c);
panel3.add(stknames_btn[row], c);
}
}
else {
label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]);
label[row].setBorder(BorderFactory.createLineBorder(Color.black));
label[row].setVerticalAlignment(JLabel.CENTER);
label[row].setHorizontalAlignment(JLabel.CENTER);
label[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0,0,0,0);
panel3.add(label[row], c);
}
}
}
return mainpanel;
}
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
}
else {
openURL(e.getActionCommand());
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = StockTable.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
}
else { //assume Unix or Linux
boolean found = false;
for (String browser : browsers)
if (!found) {
found = Runtime.getRuntime().exec(
new String[] {"which", browser}).waitFor() == 0;
if (found)
Runtime.getRuntime().exec(new String[] {browser, url});
}
if (!found)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error attempting to launch web browser\n" + e.toString());
}
}
int reit = 0;
int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1;
public int columnMulti(int multi) {
reit++;
start++;
if (reit == textvars.getNumberOfStocks()) {
reit = 0;
start=start+64;
}
//start = start - (multi*(textvars.getNumberOfStocks()));
return start;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Stock Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
StockTable newContentPane = new StockTable();
//newContentPane.setOpaque(true); //content panes must be opaque
//frame.setContentPane(newContentPane);
frame.setContentPane(newContentPane.createContentPane());
frame.setSize(800, 800);
//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();
}
});
}
}
The moment you find yourself wanting to "re-create" a UI based on a small change, should raise alarm bells. There are situations when this is going to be a good idea, but in most cases, it's a sign of a bad design.
Let's start with...
frame.setContentPane(newContentPane.createContentPane());
This is a bad idea. You create a JPanel just to create another JPanel. All of sudden, you've not lost context to the UI.
Instead of the createContentPane, simple construct you UI from the constructor of the StockTable pane and add that to the frame...More like...
frame.setContentPane(newContentPane);
Get rid of mainPanel and use the StockTable panel directly.
I can't run your code, but it looks speciously like your trying to "emulate" a table layout. Instead, simplify your life and learn to use JTable. Updating the table more be significantly easier (not to mention look nicer) if you do...
My suggestion is if you want to update a swing component always use the Event Dispatcher Thread.
I think this may helps you
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
Runnable edt = new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
Runnable edt= new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else {
openURL(e.getActionCommand());
}
}
}
When I press the button in the program below I want the popup menu from the JComboBox to appear and remain up.
However it only does that when on the second push when the Combobox is already visible. Is there any way I can make it appear on the first push?
public class Problem extends JPanel
implements ActionListener{
private static String SEARCH = "start search";
private static String SELECTED = "Selected";
private JTextField field2;
private JTextField field1;
private JComboBox list = new JComboBox();
public Problem() {
super(new GridBagLayout());
//Construct the panel
field2=new JTextField("");
field1=new JTextField("7564");
JButton search=new JButton("Search");
search.addActionListener(this);
search.setActionCommand(SEARCH);
list.addActionListener(this);
list.setActionCommand(SELECTED);
//Add everything to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 8;
c.gridheight = 3;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 0;
c.anchor = GridBagConstraints.NORTH;
add(field2,c);
list.setVisible(false);
add(list,c);
c.gridx = 8;
c.gridy = 0;
c.gridwidth = 8;
c.gridheight = 3;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 0;
c.anchor = GridBagConstraints.NORTH;
add(field1,c);
c.gridx = 16;
c.gridy = 0;
c.gridwidth = 4;
c.gridheight = 3;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 0;
c.anchor = GridBagConstraints.NORTH;
add(search,c);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand()==SEARCH){
String f2=field2.getText();
String f1=field1.getText();
if(f2.equals("")){
f2=selection(f1);
f2=null;
}
if(f2!=null){
field2.setText(f2);
}
else{
System.out.println("setPopupVisible runs");
field2.setVisible(false);
list.setVisible(true);
field2.setText("");
list.setPopupVisible(true);
}
}
else if(ae.getActionCommand().equals(SELECTED)){
System.out.println("select");
String listtext=(String) list.getSelectedItem();
list.removeAllItems();
if(listtext==null||!listtext.contains(": ")){
return;
}
String f2=listtext.split(": ")[0];
list.setVisible(false);
field2.setVisible(true);
field2.setText(f2);
}
}
private String selection(String sn) {
System.out.println("selection runs");
String name="7";
list.removeActionListener(this);
list.removeAllItems();
list.addItem(name);
list.addActionListener(this);
return null;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Stuff");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Problem newContentPane = new Problem();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
frame.setSize(800, 600);
}
public static void main(String[] args) throws FileNotFoundException {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
When toggling visibility of components, make sure the component has completed its internal update before doing custom stuff, that is f.i. delay the call to showing a combo's popup relative to showing the combo itself:
list.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
list.setPopupVisible(true);
}
});