package newjframe;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.event.MouseInputAdapter;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
setLocationRelativeTo(null);
}
public class Draggable extends JComponent {
private Point pointPressed;
private JComponent draggable;
public Draggable(final JComponent component, final int x, final int y) {
draggable = component;
setCursor(new Cursor(Cursor.HAND_CURSOR));
setLocation(x, y);
setSize(component.getPreferredSize());
setLayout(new BorderLayout());
add(component);
MouseInputAdapter mouseAdapter = new MouseHandler();
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
public class MouseHandler extends MouseInputAdapter {
#Override
public void mouseDragged(final MouseEvent e) {
Point pointDragged = e.getPoint();
Point location = getLocation();
location.translate(pointDragged.x - pointPressed.x,
pointDragged.y - pointPressed.y);
setLocation(location);
}
#Override
public void mousePressed(final MouseEvent e) {
pointPressed = e.getPoint();
}
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel = new javax.swing.JPanel();
layer = new javax.swing.JLayeredPane();
cbb = new javax.swing.JComboBox<>();
label = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
cbb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3"}));
cbb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbbActionPerformed(evt);
}
});
layer.setLayer(cbb, javax.swing.JLayeredPane.DEFAULT_LAYER);
layer.setLayer(label, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout layerLayout = new javax.swing.GroupLayout(layer);
layer.setLayout(layerLayout);
layerLayout.setHorizontalGroup(
layerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layerLayout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(cbb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(129, 129, 129)
.addComponent(label)
.addContainerGap(202, Short.MAX_VALUE))
);
layerLayout.setVerticalGroup(
layerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layerLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label)
.addComponent(cbb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(329, Short.MAX_VALUE))
);
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(layer)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(layer)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void cbbActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int[] xy = {100, 200, 300};
label.setText("DRAG THIS");
switch (cbb.getSelectedIndex()) {
case 0:
draglabel = new Draggable(label, xy[0], xy[0]);
layer.add(draglabel);
break;
case 1:
draglabel = new Draggable(label, xy[0], xy[1]);
layer.add(draglabel);
break;
case 2:
draglabel = new Draggable(label, xy[0], xy[2]);
layer.add(draglabel);
break;
default:
draglabel = new Draggable(label, xy[0], xy[0]);
layer.add(draglabel);
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> cbb;
private javax.swing.JLabel label;
private javax.swing.JLayeredPane layer;
private javax.swing.JPanel panel;
// End of variables declaration
Draggable draglabel;
}
The above code should allow the Jlabels to be dragged and dropped with ease, but every time they're called with the actionlistener in JComboBox, they become harder to drag and drop. GIF added to for better clarity https://imgur.com/rPL5ZMC I have tried repaint() method in the class method, and actionlistner but it didn't work
Again, I would tend to simplify try to clarify things, including:
Use the much simpler MouseListener/MouseAdapter and not D&D as you initially were doing. You appear to have made this change.
Not wrapping the JLabel unnecessarily in another component
Thus the Mouse listeners would be added directly on the JLabel and not on a wrapper object.
Not changing the JLayeredPane's default and unique layout
Explicitly removing the old components before adding new ones
Calling repaint() on the JLayeredPane after adding or removing components.
For example, something like this:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestDragging extends JPanel {
private static final String[] ITEMS = {"Item One", "Item Two", "Item Three"};
private static final Dimension PREF_SIZE = new Dimension(400, 400);
private JLabel label;
private JComboBox<String> comboBox = new JComboBox<>(ITEMS);
private JLayeredPane layeredPane = new JLayeredPane();
public TestDragging() {
comboBox.addActionListener(new ComboListener());
JPanel topPanel = new JPanel();
topPanel.add(comboBox);
layeredPane.setPreferredSize(PREF_SIZE);
layeredPane.setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(layeredPane, BorderLayout.CENTER);
}
private class ComboListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (label != null) {
layeredPane.remove(label);
}
int index = comboBox.getSelectedIndex();
int x = 100;
int y = 100 + 100 * index;
String text = comboBox.getSelectedItem().toString();
label = createDraggingLabel(x, y, text);
layeredPane.add(label, JLayeredPane.DEFAULT_LAYER);
layeredPane.repaint();
}
private JLabel createDraggingLabel(int x, int y, String text) {
JLabel label = new JLabel(text);
label.setSize(label.getPreferredSize());
label.setLocation(x, y);
MyMouse myMouse = new MyMouse();
label.addMouseListener(myMouse);
label.addMouseMotionListener(myMouse);
return label;
}
}
private static void createAndShowGui() {
TestDragging mainPanel = new TestDragging();
JFrame frame = new JFrame("Test Dragging");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyMouse extends MouseAdapter {
private Point pointPressed = null;
#Override
public void mousePressed(MouseEvent e) {
pointPressed = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
label.setCursor(new Cursor(Cursor.HAND_CURSOR));
Point pointDragged = e.getPoint();
Point location = label.getLocation();
int dx = pointDragged.x - pointPressed.x;
int dy = pointDragged.y - pointPressed.y;
location.translate(dx, dy);
label.setLocation(location);
Container container = label.getParent();
container.repaint();
}
}
I've called and instantiated the drag n drop function in the constructor then I've used label.setLocation(x, y) to solve this problem since the JComboBox merely determines the position of the labels, I do not need to have re-instantiate the object every time actionperformed is called.
Related
I get an idea where i design panel contents graphically and all it's possible methods in a jframe then i use that panel in another jframe where all i need to do is to create instance of the other frame and get it panel and affect it to a panel in my current jframe.
here is the code that i tried
the first jframe that contains my designed panel model :
package chemsou;
import java.util.Hashtable;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class CheckListe extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
Hashtable<String, JCheckBox> model = new Hashtable<>();
public JPanel getPanel(){
return jPanel1;
}
public CheckListe(String[] list) {
initComponents();
jPanel1.setLayout(new java.awt.GridLayout(0, 1, 0, 4));
for (String element : list) {
model.put(element, new JCheckBox(element));
jPanel1.add(model.get(element));
}
}
public CheckListe() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new java.awt.GridLayout(0, 1, 0, 4));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 388, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CheckListe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
my jframe where i call the first frame and i set the panel to the modeled one :
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String[] list =new String[]{"e1","e2","e3"};
CheckListe checkListe = new CheckListe(list);
// CheckListePanel.setLayout(checkListe.getPanel().getLayout());
CheckListePanel = checkListe.getPanel();
checkListe.setVisible( true );
CheckListePanel.setVisible(true);
CheckListePanel.setSize(100, 500);
CheckListePanel.revalidate();
CheckListePanel.repaint();
System.out.println("done");
}
When I run the code I can see that the other jframe contains the designed panel but the caller jframe dont do anything
what I m supposed to do ?
You're not doing anything with the JPanel object that you're putting into the CheckListePanel variable that will allow it to be displayed.
You need to add that JPanel object to a top-level window for it to show.
Also, you can add a component to only one container, you know. It can only be visible once.
Why create a JFrame with the first code if you're only using it to create a JPanel??
You ask, "is there a way to make a copy a the panel that i designed" -- Sure. Rather than create it as you're doing, create the JPanel in a factory method of some sort. e.g., public JPanel createMyPanel() { /* creational code goes in here */ }
Or create a class that extends JPanel and create your JPanel object this way.
For example, here's a class that creates a JPanel that displays a List of Strings as a column of JRadioButtons, and then that notifies any observers of a selection:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class BunchARadios extends JPanel {
private static final int GAP = 5;
public static final String SELECTION = "selection";
private ButtonGroup buttonGroup = new ButtonGroup();
public BunchARadios(String title, List<String> radioLabels) {
Border innerBorder = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP);
Border outerBorder = BorderFactory.createTitledBorder(title);
Border border = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
setBorder(border);
setLayout(new GridLayout(0, 1, GAP, GAP));
RButtonListener rButtonListener = new RButtonListener();
for (String radioLabel : radioLabels) {
JRadioButton radioButton = new JRadioButton(radioLabel);
radioButton.setActionCommand(radioLabel);
add(radioButton);
buttonGroup.add(radioButton);
radioButton.addActionListener(rButtonListener);
}
}
public String getSelection() {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
return null; // throw exception?
} else {
return model.getActionCommand();
}
}
private class RButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
firePropertyChange(SELECTION, null, e.getActionCommand());
}
}
}
And here's a class that uses the above class/JPanel, that adds a PropertyChangeListener to the class so that when a selection is made, another component in this class, a JList, can display the new selection:
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestBunchARadios extends JPanel {
private static final int GAP = 5;
private String title = "Weekdays";
private List<String> labels = Arrays.asList(new String[] { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday" });
private BunchARadios bunchARadios = new BunchARadios(title, labels);
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> selectionList = new JList<>(listModel);
public TestBunchARadios() {
selectionList.setPrototypeCellValue("xxxxxxxxxxxxxxxxx");
selectionList.setVisibleRowCount(5);
JScrollPane scrollPane = new JScrollPane(selectionList);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(bunchARadios, BorderLayout.CENTER);
add(scrollPane, BorderLayout.LINE_END);
bunchARadios.addPropertyChangeListener(BunchARadios.SELECTION,
new BunchARadiosChangeListener());
}
private class BunchARadiosChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String selection = (String) evt.getNewValue();
listModel.addElement(selection);
}
}
private static void createAndShowGui() {
TestBunchARadios mainPanel = new TestBunchARadios();
JFrame frame = new JFrame("TestBunchARadios");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
I am writing an application which uses a JScrollPane. In this JScrollPane I want to automatically display search results, This means, that I have to dynamically add and remove the results within the JScrollPane. The results are realised as JTextArea, which are embeded within a GridBagLayout.
When there is a high number of search results, the JScrollPane automatically scrolls to the bottom (It should be at the top). I have solved it with a solution I found here. The problem hereby is, that you can see, how it scrolls back to the top. Is it possible to remove this behaviour?
The following things I found out:
I have to remove the previous search results to display the new ones. If I don't remove the previous ones, it displays correctly.
It neither solves the prblem wgeb I update the JScrollPane every tune after adding arow nor when updating only after adding all rows.
The best would be to just disable autoscroll. I have created an executable example to demonstrate this behavior. When clicking the button "Add Row", 500 rows are added. When clicking it several times, it becomes very clear.
Thank you very much for your help!
import java.awt.GridBagConstraints;
import javax.swing.JTextArea;
public class ScrollPaneTest extends javax.swing.JFrame {
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
/**
* Creates new form ScrollPaneTest
*/
public ScrollPaneTest() {
initComponents();
}
/**
* Adds a new row.
* #param index The index of the new row.
*/
private void addRow(int index) {
JTextArea row = new JTextArea("Area " + index);
row.setEditable(false);
row.setBorder(null);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = index;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(row, gridBagConstraints);
}
/**
* Initializes the components.
*/
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane1.setPreferredSize(new java.awt.Dimension(400, 400));
jScrollPane1.setViewportView(jPanel1);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setLayout(new java.awt.GridBagLayout());
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jScrollPane1.setViewportView(jPanel1);
jButton1.setText("Create Rows");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addGap(0, 21, Short.MAX_VALUE))
);
pack();
}
/**
* Creates 500 new rows.
* #param evt
*/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel2.removeAll();
for(int i = 0; i < 1000; i++) {
addRow(i);
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jScrollPane1.getVerticalScrollBar().setValue(0);
}
});
jPanel2.validate();
jPanel2.repaint();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ScrollPaneTest().setVisible(true);
}
});
}
}
UPDATE 1
I removed the lambda expressions. Hopefully it should be now compileable also with < Java 8.
UPDATE 2
The problem with the disturbing scrolling behavior has been solved by replacing
jPanel2.validate();
jPanel2.repaint();
with
jScrollPane1.validate();
jScrollPane1.repaint();
Nevertheless, both answers to this question can be very helpful in some other cases and should be given attention.
One way to achieve this is to have a custom JViewPort for your scrollpane. This custom viewport overrides setViewPosition and uses a flag to prevent the scroll, or not.
Here is an example of such code, before changing the content of the textarea, we "lock" the viewport to prevent scrolling, and we unlock it later:
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TestNoScrolling {
private int lineCount = 0;
private LockableViewPort viewport;
private JTextArea ta;
private final class LockableViewPort extends JViewport {
private boolean locked = false;
#Override
public void setViewPosition(Point p) {
if (locked) {
return;
}
super.setViewPosition(p);
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
}
protected void initUI() {
JFrame frame = new JFrame("test");
ta = new JTextArea(5, 30);
JScrollPane scrollpane = new JScrollPane();
viewport = new LockableViewPort();
viewport.setView(ta);
scrollpane.setViewport(viewport);
frame.add(scrollpane);
frame.pack();
frame.setVisible(true);
Timer t = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
viewport.setLocked(true);
ta.append("Some new line " + lineCount++ + "\n");
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
viewport.setLocked(false);
}
});
}
});
t.setRepeats(true);
t.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestNoScrolling().initUI();
}
});
}
}
You could simply set the Caret position to the start position (0), for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ScrollNoMore {
public static void main(String[] args) {
new ScrollNoMore ();
}
public ScrollNoMore () {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea ta;
private JScrollPane sp;
private Random rnd = new Random();
private boolean initalised = false;
public TestPane() {
setLayout(new BorderLayout());
ta = new JTextArea(20, 40);
sp = new JScrollPane(ta);
add(sp);
Timer timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long value = rnd.nextLong();
ta.append(String.valueOf(value) + "\n");
if (!initalised) {
ta.setCaretPosition(0);
initalised = true;
}
}
});
timer.start();
}
}
}
This will only set it the first time the Timer runs, this means that if you move the Caret or scroll position for some reason, it won't "flick" back. You could set up a series of states where by if the user moved the current view, it didn't effect the scrolling, but could be reset as required.
How to make a text field visible on itemStatechanged event of a check box in Swing?
I am trying to create a frame with a check box and a text field. I want the text field to be displayed only when the check box is selected. So when I initialize the components, I have set the textfield.setvisible to false and for the check box added a addItemListener and call the itemStateChanged event and there is the check box is selected, I set the setVisible method to true.
My SSCCE looks like:
package ui;
public class Evaluator extends javax.swing.JFrame {
public Evaluator() {
initComponents();
}
private void initComponents() {
jCheckBox1 = new javax.swing.JCheckBox();
jTextField1 = new javax.swing.JTextField();
jTextField1.setVisible(false);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(800, 800));
jCheckBox1.setFont(new java.awt.Font("Tahoma", 0, 14));
jCheckBox1.setText("Properties");
jCheckBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBox1ItemStateChanged(evt);
}
});
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jCheckBox1)
.addGap(41, 41, 41)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(155, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(229, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34))
);
pack();
}
private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange()== java.awt.event.ItemEvent.SELECTED){
jTextField1.setVisible(true);
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Evaluator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Evaluator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Evaluator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Evaluator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Evaluator().setVisible(true);
}
});
}
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JTextField jTextField1;
}
Basically, you need to invalidate the frame (or parent container) to force it be re-layout
private void jCheckBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
jTextField1.setVisible(jCheckBox2.isSelected());
invalidate();
validate();
}
Updated
I'd also suggest that you avoid adding your entire UI onto a top level container, instead use a JPanel as you base component and build you UI's around them. When you're ready, simply add the base panel to what ever top level container you need.
For many components in one space, use a CardLayout as see in this short example.
Here is a more specific example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo {
public static void main(String[] args) {
Runnable r = new Runnable () {
public void run() {
final JCheckBox show = new JCheckBox("Have Text", false);
JPanel ui = new JPanel(new
FlowLayout(FlowLayout.CENTER, 5, 5));
ui.add( show );
final CardLayout cl = new CardLayout();
final JPanel cards = new JPanel(cl);
ui.add(cards);
cards.add(new JPanel(), "notext");
cards.add(new JTextField(8), "text");
ItemListener al = new ItemListener(){
public void itemStateChanged(ItemEvent ie) {
if (show.isSelected()) {
cl.show(cards, "text");
} else {
cl.show(cards, "notext");
}
}
};
show.addItemListener(al);
JOptionPane.showMessageDialog(null, ui);
}
};
SwingUtilities.invokeLater(r);
}
}
great lesson, how the LayoutManager works, only GridLayout can do that without any issue, but this is its property
last JComponent in the row or column (part of then is about) can't be invisible, then container is shrinked
easiest work_around is to display container, then to call setVisible(false) wrapped into invokeLater
... ....
import java.awt.event.ItemEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Evaluator {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JCheckBox checkBox = new JCheckBox();
private JTextField textField = new JTextField(10);
public Evaluator() {
checkBox.setText("Properties");
checkBox.addItemListener(new java.awt.event.ItemListener() {
#Override
public void itemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
textField.setVisible(true);
} else {
textField.setVisible(false);
}
}
});
//panel.setLayout(new GridLayout());
//panel.setLayout(new SpringLayout());
//panel.setLayout(new BorderLayout());
//panel.setLayout(new GridBagLayout());
//panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(checkBox/*, BorderLayout.NORTH*/);
panel.add(textField/*, BorderLayout.SOUTH*/);
//panel.doLayout();
//textField.setVisible(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
textField.setVisible(false);
}
});
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Evaluator evaluator = new Evaluator();
}
});
}
}
I have created the following JTable and some buttons.
One of the buttons (jbtClear) is trying to empty the table using the setRowCount() function.
Any ideas , why it is not working and produces this error?
Here is the code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nysemarketpick;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* #author Administrator
*/
public class PortfolioForm extends javax.swing.JFrame {
/**
* Creates new form PortfolioForm
*/
public PortfolioForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jbtAddRow = new javax.swing.JButton();
jbtDeleteRow = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jbtSave = new javax.swing.JButton();
jbtClear = new javax.swing.JButton();
jbtRestore = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Row functions"));
jbtAddRow.setText("Add New Row");
jbtDeleteRow.setText("Delete Selected Row");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(34, 34, 34)
.add(jbtAddRow))
.add(jPanel1Layout.createSequentialGroup()
.add(16, 16, 16)
.add(jbtDeleteRow)))
.addContainerGap(40, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jbtAddRow)
.add(18, 18, 18)
.add(jbtDeleteRow)
.addContainerGap(26, Short.MAX_VALUE))
);
jTable1.setAutoCreateRowSorter(true);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Stock Symbol", "Stock Name", "Shares", "Value (in Dollars)", "Total Value"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
true, false, true, true, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tableModel = (DefaultTableModel)jTable1.getModel();
jTable1.setColumnSelectionAllowed(true);
jTable1.setRowSelectionAllowed(true);
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jTable1);
jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
//add action listeners
jbtAddRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (jTable1.getSelectedRow() >= 0)
tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
else
tableModel.addRow(new Vector());
}
});
jbtDeleteRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (jTable1.getSelectedRow() >= 0)
tableModel.removeRow(jTable1.getSelectedRow());
}
});
jbtSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("portfolio.dat"));
out.writeObject(tableModel.getDataVector());
out.writeObject(getColumnNames());
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jbtClear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
tableModel.setRowCount(0);
}
});
jbtRestore.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("portfolio.dat"));
Vector rowData = (Vector)in.readObject();
Vector columnNames = (Vector)in.readObject();
tableModel.setDataVector(rowData, columnNames);
in.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
//add other listeners
tableModel.addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent e)
{
DefaultTableModel model = (DefaultTableModel)e.getSource();
//Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
if (e.getColumn() == 0)
{
Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
String stockSymbol = (String)data;
XMLService2 myService = new XMLService2(stockSymbol);
String stockName = XMLService2.getStockName();
model.setValueAt(stockName, e.getFirstRow(), e.getColumn() + 1);
}
if (e.getColumn() != 4 && model.getValueAt(e.getFirstRow(), 2) != null && model.getValueAt(e.getFirstRow(), 3) != null)
{
Double myDouble =(Integer)model.getValueAt(e.getFirstRow(), 2)*(Double)model.getValueAt(e.getFirstRow(), 3);
model.setValueAt(myDouble, e.getFirstRow(), 4);
}
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Table functions"));
jbtSave.setText("Save");
jbtClear.setText("Clear");
jbtRestore.setText("Restore");
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(34, 34, 34)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jbtRestore)
.add(jbtClear)
.add(jbtSave))
.addContainerGap(41, Short.MAX_VALUE))
);
jPanel2Layout.linkSize(new java.awt.Component[] {jbtClear, jbtRestore, jbtSave}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(jbtSave)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jbtClear)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jbtRestore))
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(21, 21, 21)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 645, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(31, 31, 31)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(78, 78, 78)
.add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(50, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 399, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(27, 27, 27)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PortfolioForm().setVisible(true);
}
});
}
//---other methods
private Vector getColumnNames()
{
Vector<String> columnNames = new Vector<String>();
for (int i = 0; i < jTable1.getColumnCount(); i++)
columnNames.add(jTable1.getColumnName(i));
return columnNames;
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private DefaultTableModel tableModel;
private javax.swing.JButton jbtAddRow;
private javax.swing.JButton jbtClear;
private javax.swing.JButton jbtDeleteRow;
private javax.swing.JButton jbtRestore;
private javax.swing.JButton jbtSave;
// End of variables declaration
}
Post edit : Here is working code from a book with the same function :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projecttable5;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
*
* #author Administrator
*/
public class ModifyTable extends JFrame{
//Create table column names
private String[] columnNames = {"Country", "Capital", "Population in Millions", "Democracy"};
//Create table data
private Object[][] rowData = {
{"USA", "Washington DC", 280, true},
{"Canada", "Ottawa", 32, true},
{"United Kingdom", "London", 60, true},
{"Germany", "Berlin", 83, true},
{"France", "Paris", 60, true},
{"Norway", "Oslo", 4.5, true},
{"India", "New Delhi", 1046, true}
};
//Create a table model
private DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);
//Create a table
private JTable jTable1 = new JTable(tableModel);
//Create buttons
private JButton jbtAddRow = new JButton("Add New Row");
private JButton jbtAddColumn = new JButton("Add New Column");
private JButton jbtDeleteRow = new JButton("Delete Selected Row");
private JButton jbtDeleteColumn = new JButton("Delete Selected Column");
private JButton jbtSave = new JButton("Save");
private JButton jbtClear = new JButton("Clear");
private JButton jbtRestore = new JButton("Restore");
//Create a combo box for selection modes
private JComboBox jcboSelectionMode = new JComboBox(new String[] {"SINGLE_SELECTION", "SINGLE_INTERVAL_SELECTION", "MULTIPLE_INTERVAL_SELECTION"});
//Create check boxes
private JCheckBox jchkRowSelectionAllowed = new JCheckBox("RowSelectionAllowed", true);
private JCheckBox jchkColumnSelectionAllowed = new JCheckBox("ColumnSelectionAllowed", false);
//---Default constructor
public ModifyTable()
{
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2, 2));
panel1.add(jbtAddRow);
panel1.add(jbtAddColumn);
panel1.add(jbtDeleteRow);
panel1.add(jbtDeleteColumn);
JPanel panel2 = new JPanel();
panel2.add(jbtSave);
panel2.add(jbtClear);
panel2.add(jbtRestore);
JPanel panel3 = new JPanel();
panel3.setLayout(new BorderLayout(5, 0));
panel3.add(new JLabel("Selection Mode"), BorderLayout.WEST);
panel3.add(jcboSelectionMode, BorderLayout.CENTER);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
panel4.add(jchkRowSelectionAllowed);
panel4.add(jchkColumnSelectionAllowed);
//Gather panel3 and panel4
JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayout(2, 1));
panel5.add(panel3);
panel5.add(panel4);
//Gather panel1 and panel2
JPanel panel6 = new JPanel();
panel6.setLayout(new BorderLayout());
panel6.add(panel1, BorderLayout.SOUTH);
panel6.add(panel2, BorderLayout.CENTER);
add(panel5, BorderLayout.NORTH);
add(new JScrollPane(jTable1), BorderLayout.CENTER);
add(panel6, BorderLayout.SOUTH);
//Initialize table selection mode
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Add listeners
jbtAddRow.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedRow() >= 0)
tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
else
tableModel.addRow(new Vector());
}
});
jbtAddColumn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String name = JOptionPane.showInputDialog("New Column Name");
tableModel.addColumn(name, new Vector());
}
});
jbtDeleteRow.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedRow() >= 0)
tableModel.removeRow(jTable1.getSelectedRow());
}
});
jbtDeleteColumn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedColumn() >= 0)
{
TableColumnModel columnModel = jTable1.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(jTable1.getSelectedColumn());
columnModel.removeColumn(tableColumn);
}
}
});
jbtSave.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablemodel.dat"));
out.writeObject(tableModel.getDataVector());
out.writeObject(getColumnNames());
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jbtClear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
tableModel.setRowCount(0);
}
});
jbtRestore.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablemodel.dat"));
Vector rowData = (Vector)in.readObject();
Vector columnNames = (Vector)in.readObject();
tableModel.setDataVector(rowData, columnNames);
in.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jchkRowSelectionAllowed.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
jTable1.setRowSelectionAllowed(jchkRowSelectionAllowed.isSelected());
}
});
jchkColumnSelectionAllowed.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
jTable1.setColumnSelectionAllowed(jchkColumnSelectionAllowed.isSelected());
}
});
jcboSelectionMode.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = (String)jcboSelectionMode.getSelectedItem();
if (selectedItem.equals("SINGLE_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
else if (selectedItem.equals("SINGLE_INTERVAL_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
else if (selectedItem.equals("MULTIPLE_INTERVAL_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
});
}//end of default constructor
private Vector getColumnNames()
{
Vector<String> theColumnNames = new Vector<>();
for (int i = 0; i < jTable1.getColumnCount(); i++)
theColumnNames.add(jTable1.getColumnName(i));
return theColumnNames;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}
catch(Exception e)
{
}
ModifyTable frame = new ModifyTable();
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("TableSortFilter");
frame.pack();
//frame.setSize(new Dimension(300, 300));
frame.setVisible(true);
}
}
If you wish to alter table content, it's better to work with table model directly. Create your own model and do what you want.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
Here is the final solution.
The last answer of this question (http://stackoverflow.com/questions/2668547/stackoverflowerror-being-caused-by-a-tablemodellistener) helped me alot :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nysemarketpick;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
/**
*
* #author Administrator
*/
public class PortfolioForm extends javax.swing.JFrame {
//Create table column names
private String[] columnNames = {"Stock Symbol", "Stock Name", "Shares", "Price (in dollars)", "Total"};
//Create table data
private Object[][] rowData = {
{null, null, null, null, null}
};
//Create a table model
private MyTableModel myTableModel = new MyTableModel(rowData, columnNames);
//Create a table
private JTable jTable1 = new JTable(myTableModel);
/**
* Creates new form PortfolioForm
*/
public PortfolioForm() {
initComponents();
add(new JScrollPane(jTable1), BorderLayout.CENTER);
//Initialize table selection mode
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Allow row selection
jTable1.setRowSelectionAllowed(true);
//Load data
loadData();
//add listeners
jbtAddRow.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedRow() >= 0)
myTableModel.insertRow(jTable1.getSelectedRow(), new Vector());
else
myTableModel.addRow(new Vector());
}
});
jbtDeleteRow.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if ((jTable1.getSelectedRow() >= 0) && (myTableModel.getValueAt(jTable1.getSelectedRow(), 1) != null))
{
System.out.println(myTableModel.getValueAt(jTable1.getSelectedRow(), 1));
myTableModel.removeRow(jTable1.getSelectedRow());
}
}
});
jbtSave.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("portfolio.dat"));
out.writeObject(myTableModel.getDataVector());
out.writeObject(getColumnNames());
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
disposeForm();
}
});
jbtClear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
myTableModel.setRowCount(0);
}
});
jbtTotal.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
double sum = 0;
int numberOfRows = myTableModel.getRowCount();
for (int i = 0; i < numberOfRows; i++)
{
sum = sum + (Double)myTableModel.getValueAt(i, 4);
}
jLabelTotal.setText(String.valueOf(sum));
}
});
jbtTotals.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Double myDouble;
for (int i = 0; i < myTableModel.getRowCount(); i++)
{
myDouble = (Integer)myTableModel.getValueAt(i, 2) * (Double)myTableModel.getValueAt(i, 3);
myTableModel.setValueAt(myDouble, i, 4);
}
}
});
myTableModel.addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent e) {
myTableModel.removeTableModelListener(this);
if (myTableModel.getRowCount() > 0)
{
if (e.getColumn() == 0)
{
Object data = myTableModel.getValueAt(e.getFirstRow(), e.getColumn());
String stockSymbol = (String)data;
XMLService2 myService = new XMLService2(stockSymbol);
String stockName = XMLService2.getStockName();
myTableModel.setValueAt(stockName, e.getFirstRow(), e.getColumn() + 1);
}
}
myTableModel.addTableModelListener(this);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jbtAddRow = new javax.swing.JButton();
jbtDeleteRow = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jbtSave = new javax.swing.JButton();
jbtClear = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jLabelTotal = new javax.swing.JLabel();
jbtTotal = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jbtTotals = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setSize(new java.awt.Dimension(600, 400));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Row functions"));
jPanel2.setLayout(new java.awt.GridLayout(2, 1));
jbtAddRow.setText("Add New Row");
jPanel2.add(jbtAddRow);
jbtDeleteRow.setText("Delete Selected Row");
jPanel2.add(jbtDeleteRow);
jPanel1.add(jPanel2);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Table functions"));
jPanel3.setMinimumSize(new java.awt.Dimension(200, 111));
jPanel3.setPreferredSize(new java.awt.Dimension(150, 100));
jPanel3.setLayout(new java.awt.GridLayout(3, 1));
jbtSave.setText("Save & Close");
jPanel3.add(jbtSave);
jbtClear.setText("Clear");
jPanel3.add(jbtClear);
jPanel1.add(jPanel3);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Total Position"));
jPanel4.setLayout(new java.awt.GridLayout(2, 1));
jLabelTotal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelTotal.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel4.add(jLabelTotal);
jbtTotal.setText("Calculate");
jPanel4.add(jbtTotal);
jPanel1.add(jPanel4);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
jbtTotals.setText("Calculate Totals");
org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 145, Short.MAX_VALUE)
.add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel5Layout.createSequentialGroup()
.add(0, 0, Short.MAX_VALUE)
.add(jbtTotals)
.add(0, 0, Short.MAX_VALUE)))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 336, Short.MAX_VALUE)
.add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel5Layout.createSequentialGroup()
.add(0, 153, Short.MAX_VALUE)
.add(jbtTotals)
.add(0, 154, Short.MAX_VALUE)))
);
getContentPane().add(jPanel5, java.awt.BorderLayout.EAST);
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new PortfolioForm().setVisible(true);
}
});
}
//---Other methods
private Vector getColumnNames()
{
Vector<String> columnNames = new Vector<String>();
for (int i = 0; i < jTable1.getColumnCount(); i++)
columnNames.add(jTable1.getColumnName(i));
return columnNames;
}
private void disposeForm()
{
this.dispose();
}
private void loadData()
{
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("portfolio.dat"));
Vector rows = (Vector)in.readObject();
Vector columns = (Vector)in.readObject();
myTableModel.setDataVector(rows, columns);
in.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabelTotal;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JButton jbtAddRow;
private javax.swing.JButton jbtClear;
private javax.swing.JButton jbtDeleteRow;
private javax.swing.JButton jbtSave;
private javax.swing.JButton jbtTotal;
private javax.swing.JButton jbtTotals;
// End of variables declaration
}
I have two forms. First one is to decide numbers of button by using jslider. Second form is to display jbuttons according to jslider value. When i click jbutton2, the second form shows and display buttons. It is working perfectly. However, I want to create jbutton on the second form without clicking jbutton2 in the first form.
Instead, when I change jslider, it should create jbuttons on the second form at the run time and once i change jslider it should create that amount of button again on the second form and refreshing the second form button numbers according to jslider value.
I have tried revalidate();, repaint(); but they do not work, they dont refresh the second form.
So, How can I refresh second form when the jslider ,that is on the first form, changes ? Please help.....
Edit:I am using default Jframe of netbeans....
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class NewJFrame7 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame7
*/
public NewJFrame7() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSlider1 = new javax.swing.JSlider();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSlider1.setMajorTickSpacing(2);
jSlider1.setMaximum(20);
jSlider1.setMinimum(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setToolTipText("");
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(273, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(262, 262, 262)
.addComponent(jButton2)
.addContainerGap(262, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(168, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addComponent(jButton2)
.addContainerGap(139, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
form2 = true;
new NewJFrame8().setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame7().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JSlider jSlider1;
// End of variables declaration
}
2.form
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class NewJFrame8 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame8
*/
public NewJFrame8() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(371, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(242, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame8().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
One layout constraint (BorderLayout.CENTER) to place them, and one component to appear therein. (With apologies to Tolkien.)
Do check this sample Program, is this what you need. revalidate() and repaint() is what works here for this.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
for (int i = 0; i < value; i++)
{
ButtonPanel.panel.add(new JButton("JButton " + i));
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private JButton[] buttonArray;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(button.getText());
}
};
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
buttonArray = new JButton[value];
for (int i = 0; i < value; i++)
{
buttonArray[i] = new JButton(String.valueOf(i));
buttonArray[i].addActionListener(actionButton);
ButtonPanel.panel.add(buttonArray[i]);
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
For your statement this.buttonArray[i].addActionListener(this);, the reason as to why this is not working, is because, you are inside the object of anonymous class new ChangeListener(), which doesn't have anything named buttonArray[i] inside itself, it's the Instance Variable of SliderExample class, so either place an object of SliderExample class or if you are referring to your code, then use the Object of the class which initializes the array like inside inside NewFrame8 you had written JButton[] buttonArray = new JButton[120];, so use NewFrame8's object instead of this to refer to the buttonArray[i] thingy.