Make a textfield visible on itemStatechanged event of a checkbox - java

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();
}
});
}
}

Related

Unable to drag and drop sometimes

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.

How To Hide The Tab Except Focus Tab of JTabbedPane

In My Application every tab has close button.I want to hide the Close Button when tab is not focused/selected.Here My Problem is I want to hide the Close button of every created tab Except Focus/selected tab.Whenever I select the Particular tab then only the Close button should be enabled.How can I Disable the close button when it is not focused.Please help me.Thank You.
My Working Example:
public class CloseCurrentTab extends javax.swing.JFrame {
JTextArea tx;
int i=0;
public CloseCurrentTab() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
tabbedPane = new CloseButtonTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
create = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
create.setText("Create");
create.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
createActionPerformed(evt);
}
});
jMenu1.add(create);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
);
pack();
}
private void createActionPerformed(java.awt.event.ActionEvent evt) {
i++;
tx = new JTextArea();
tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
JScrollPane scrollpane=new JScrollPane(tx);
tabbedPane.addTab("Doc"+i, scrollpane);
tabbedPane.setSelectedIndex(i-1);
pack();
}
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CloseCurrentTab.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new CloseCurrentTab().setVisible(true);
}
});
}
private javax.swing.JMenuItem create;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tabbedPane;
public class CloseButtonTabbedPane extends JTabbedPane {
public CloseButtonTabbedPane() {
}
#Override
public void addTab(String title, Icon icon, Component component, String tip) {
super.addTab(title, icon, component, tip);
int count = this.getTabCount() - 1;
setTabComponentAt(count, new CloseButtonTab(component, title, icon));
}
#Override
public void addTab(String title, Icon icon, Component component) {
addTab(title, icon, component, null);
}
#Override
public void addTab(String title, Component component) {
addTab(title, null, component);
}
public class CloseButtonTab extends JPanel {
private Component tab;
public CloseButtonTab(final Component tab, String title, Icon icon) {
this.tab = tab;
setOpaque(false);
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 3, 3);
setLayout(flowLayout);
setVisible(true);
JLabel jLabel = new JLabel(title);
jLabel.setIcon(icon);
add(jLabel);
JButton button = new JButton(MetalIconFactory.getInternalFrameCloseIcon(16));
button.setMargin(new Insets(0, 0, 0, 0));
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
button.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent();
tabbedPane.remove(tabbedPane.getSelectedIndex());
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
}
public void mouseExited(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
});
add(button);
}
}
}
}

How to add a JInternalFrame to JFrame?

I have my JFrame, and I want to attach to a button an ActionListener that triggers the JInternalFrame.
I do:
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame(); //jInternalFrame
this.add(about);
}
But it doesn't bring it to front. What did I miss?
You probable want to use a JDesktopPane, then set the content pane of your frame to the desktop pane
JDesktopPane desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
Then you can do something like this
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)
{
AboutFrame about = new AboutFrame(); <--- JInternalFrame
about.setVisible(true); //necessary as of 1.3 <--- set it visible
desktop.add(about); <--- add to desktop
try {
about.setSelected(true); <--- set it selected
} catch (java.beans.PropertyVetoException e) {}
}
See How to Us Internal Frames
UDATE
Run this example, I made on NetBeans GUI Builder also. It works fine, without the behavior yout're talking about.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 376, Short.MAX_VALUE)
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 302, Short.MAX_VALUE)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("About");
jMenuItem1.setText("About");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
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()
.addComponent(jDesktopPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame();
about.setVisible(true);
jDesktopPane1.add(about);
try {
about.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
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(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);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
AboutFrame.java
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class AboutFrame extends JInternalFrame{
public AboutFrame() {
add(new Panel());
pack();
}
private class Panel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("About Screen", 100, 100);
}
public Dimension getPreferredSize(){
return new Dimension(300, 300);
}
}
}
Steps I took
Opened a new JFrame form
Dragged a JDesktopPane to the main frame and expanded it the size of the frame
Dragged a JMenuBar to the top of the frame
Dragged a JMenuItem to the JMenuBar
Added an event listener to the JMenuItem
Added the action code that i provided for you earlier. That's all I did, and it works fine.
EDIT
A different apprach would be instead of using an JInternalFrame for this. Use a modal JDialog. You can create it the same way you did the JInternalFrame , and show it the same way. This will guarantee you don't get this result. :)

Nimbus L&F - Change Background color of Progress Bar

i'm developing a little GUI application with Java using Netbeans Editor.
I've put in a JFrame a simple Progress Bar.
I'm developing the project with JDK7
I want to change the background Color from default Orange to a personal one. I've already tried all the properties for the color changing but when i run the program the color still the same.
I've already tried using
ProgressBar1.setBackground(new java.awt.Color(0, 204, 255));
and
UIManager.put("ProgressBar.background", Color.YELLOW);
UIManager.put("ProgressBar.foreground", Color.MAGENTA);
UIManager.put("ProgressBar.selectionBackground", Color.red);
UIManager.put("ProgressBar.selectionForeground", Color.green);
Same result..... The background is always orange
Here the code of my test project
public class Frame extends javax.swing.JFrame
{
public Frame()
{
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jProgressBar1.setBackground(new java.awt.Color(0, 204, 255));
jProgressBar1.setValue(75);
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(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
}
and this is the result when you launch the code
(source: uploadscreenshot.com)
Orange color....
EDIT
With the following code
UIManager.getLookAndFeelDefaults().put("ProgressBar[Enabled].backgroundPainter", new FillPainter(Color.MAGENTA));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Disabled].backgroundPainter", new FillPainter(Color.MAGENTA));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Enabled+Indeterminate].progressPadding", new FillPainter(Color.ORANGE));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Enabled].foregroundPainter", new FillPainter(Color.GREEN));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Disabled].foregroundPainter", new FillPainter(Color.GREEN));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Enabled+Finished].foregroundPainter", new FillPainter(Color.GREEN));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Disabled+Finished].foregroundPainter", new FillPainter(Color.GREEN));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Disabled+Indeterminate].foregroundPainter", new FillPainter(Color.GREEN));
UIManager.getLookAndFeelDefaults().put("ProgressBar[Enabled+Indeterminate].foregroundPainter", new FillPainter(Color.GREEN)); `
after this line
javax.swing.UIManager.setLookAndFeel(info.getClassName());
I've successfully change the color of background.
But now the color is "plain", there is no gradient like the orange color.
(source: uploadscreenshot.com)
Is it possible to change color with the same effect of the original color?
maybe (Color and Font) issue talking about Nimbus Look and Feel
have to check this thread
value for
ProgressBar[Disabled+Finished].foregroundPainter
ProgressBar[Disabled+Indeterminate].foregroundPainter
ProgressBar[Disabled].backgroundPainter
ProgressBar[Disabled].foregroundPainter
ProgressBar[Enabled+Finished].foregroundPainter
ProgressBar[Enabled+Indeterminate].foregroundPainter
ProgressBar[Enabled+Indeterminate].progressPadding
ProgressBar[Enabled].backgroundPainter
ProgressBar[Enabled].foregroundPainter
.
4. maybe easiest for you will be to change nimbusOrange from the top of Nimbus defaults, but this change is everywhere,
funny output to the GUI with changed Control Color, for example
UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(127, 255, 191)));
.
5. for example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.swing.*;
public class MyPopupWithNimbus {
public MyPopupWithNimbus() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JList list = new JList();
panel.add(list);
JProgressBar progress = new JProgressBar();
progress.setStringPainted(true);
progress.setString("60 pct");
progress.setValue(60);
frame.add(panel);
frame.add(progress, BorderLayout.SOUTH);
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem("A"));
menu.add(new JMenuItem("B"));
menu.add(new JMenuItem("C"));
JMenu jmenu = new JMenu("D");
jmenu.add(new JMenuItem("E"));
menu.add(jmenu);
frame.setVisible(true);
menu.show(frame, 50, 50);
}
public static void main(String[] args) {
try {
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(127, 255, 191)));
UIManager.getLookAndFeelDefaults().put("PopupMenu[Enabled].backgroundPainter",
new FillPainter(Color.ORANGE));
}
}
} catch (Exception e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyPopupWithNimbus aa = new MyPopupWithNimbus();
}
});
}
}
class FillPainter implements Painter<JComponent> {
private final Color color;
FillPainter(Color c) {
color = c;
}
#Override
public void paint(Graphics2D g, JComponent object, int width, int height) {
g.setColor(color);
g.fillRect(0, 0, width - 1, height - 1);
}
}
This is what I have done in the application I currently develop
ColorUIResource colorResource = new ColorUIResource(Color.red.darker().darker());
UIManager.put("nimbusOrange",colorResource);
This simply changes the default orange color with something more appealing to the eyes and it changes it everywhere.

Dynamically create jCheckBox and add to a jScrollPane

EDIT: Using the solutions presented below, I have changed the code to have a JPanel inside a JScrollPane. Using a JButton i add JCheckBoxes to the JPanel inside the JScrollPane. This was one problem solved, as the a JScrollPanecan only take one JComponent. The rest of the issues were solved setting a gridlayout to the JPanel inside JScrollPane. I have kept my original question here for the sake of posterity:
ORIGINAL QUESTION: I'm trying to dynamically create JCheckBox and add them to a JScrollPane, but alas i am achieving little success. I have reduced this to a single proof-of-concept implementation.
I have a JScrollPaneon a JPanel inside a JFrame. Also on the JPanel, i have added a button that is supposed to add a JCheckBox to the JScrollPane when clicked. Should be simple enough. The code inside the button is as follows:
private void addCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jScrollPaneCheckBoxes.add(cb);
jScrollPaneCheckBoxes.revalidate();
}
The code runs seemingly without error. I have no exceptions and using the debugger shows that the JCheckBox is in fact added to the JScrollPane . Unfortunately, nothing is displayed in the application. I need direction as to where to look for the problem.
Here is a quick piece of code that you can just run. Unfortunately i threw this together using Netbeans and it's GUI designer and as such it's a bit longer than it needs to be, especially the generated code. Focus on the method jButton1ActionPerformed, that's where the above code is taken from.
EDIT: This code now does what i need it to. :-)
package dynamiccheckboxsscce;
import javax.swing.JCheckBox;
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = 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.setPreferredSize(new java.awt.Dimension(250, 250));
jPanel1.setPreferredSize(new java.awt.Dimension(300, 250));
jPanel1.setLayout(new java.awt.GridLayout(0, 2, 10, 10));
jScrollPane1.setViewportView(jPanel1);
jButton1.setText("Add Checkbox");
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)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(112, 112, 112)))));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap()));
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jPanel1.add(cb);
jPanel1.revalidate();
jPanel1.repaint();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
}
Thanks in advance.
without posting a SSCCE you have to accepting that JScrollPane is designated to nest only one JComponent,
if you want to add more that one JComponent to the JScrollPane, the put there JPanel and then add a new JComponent to the JPanel instead of JScrollPane
to check how dynamically add / remove JComponents
EDIT
you have to set proper LayoutManager to the JPanel
you ahve to add JPanel to the JScrollPane
for example (without using built_in designer, even safe time for ..., required best knowledge about used SwingFramework and Swing too, I'm satisfied with plain Swing)
code
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class AddJCheckBoxToJScrollPane {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private JButton jButton1;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
public AddJCheckBoxToJScrollPane() {
jPanel1 = new JPanel();
jPanel1.setLayout(new GridLayout(0, 2, 10, 10));
jScrollPane1 = new JScrollPane(jPanel1);
jButton1 = new JButton("Add Checkbox");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jPanel1.add(cb);
jPanel1.revalidate();
jPanel1.repaint();
}
});
frame.add(jScrollPane1);
frame.add(jButton1, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
//frame.pack();
frame.setLocationRelativeTo(null);
frame.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) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddJCheckBoxToJScrollPane();
}
});
}
}
You should be calling repaint() instead of revalidate().
See Revalidate vs. Repaint

Categories

Resources