JTabbedPane TabComponent default tab highlighting - java

I have a question regarding custom tab components in swing.
The following code will add 3 custom tab components:
public class TabbedExample extends JPanel {
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createUI();
}
}
}
public static void createUI() {
try {
for(LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch(Exception e) {}
JFrame frame = new JFrame("Tab Test");
frame.setMinimumSize(new Dimension(256,200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TabbedExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TabbedExample() {
super(new BorderLayout());
JTabbedPane pane = new JTabbedPane();
pane.addTab("tmp", new JTextField());
pane.addTab("tmp", new JTextField());
pane.addTab("tmp", new JTextField());
for(int i = 0; i < 3; i++) {
JPanel tabPanel = new JPanel();
tabPanel.setBackground(new Color(0,0,0,0));
tabPanel.setLayout(new BoxLayout(tabPanel, BoxLayout.X_AXIS));
JTextField textField = new JTextField("Tab " + i);
textField.setOpaque(false);
textField.setBackground(new Color(0,0,0,0));
textField.setBorder(new EmptyBorder(0,0,0,0));
tabPanel.add(label);
tabPanel.add(new JButton(Integer.toString(i)));
pane.setTabComponentAt(i, tabPanel);
}
add(pane, BorderLayout.CENTER);
}
}
the problem now is that the default tab behaviour stops working. normally, when you move your mouse over a tab, it automagically gets highlight by changing the background color. but as soon as the JTextField is hit, the tab most likely registers a mouseExited Event and stops the highlighting of the tab. so the tab will flicker when you move your mouse over the tab.
my question now is:
Is there a way (without implementing a new highlighting mechanism) to highlight the tab, where the custom tabComponent is located?

Here's my attempt:
Using a JLayer to dispatch the MouseMotionEvent from the tabs to the parent JTabbedPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TabbedExample2 extends JPanel {
public static void main(String... args) {
EventQueue.invokeLater(() -> {
createUI();
});
}
public static void createUI() {
try {
for (UIManager.LookAndFeelInfo laf: UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Tab Test");
frame.setMinimumSize(new Dimension(256, 200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TabbedExample2());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TabbedExample2() {
super(new BorderLayout());
JTabbedPane pane = new JTabbedPane();
pane.addTab("tmp", new JTextField(16));
pane.addTab("tmp", new JTextField(16));
pane.addTab("tmp", new JTextField(16));
for (int i = 0; i < 3; i++) {
JPanel tabPanel = new JPanel();
tabPanel.setOpaque(false);
//tabPanel.setBackground(new Color(0,0,0,0));
tabPanel.setLayout(new BoxLayout(tabPanel, BoxLayout.X_AXIS));
JTextField textField = new JTextField("Tab " + i);
//textField.setBackground(new Color(0,0,0,0));
//textField.setBorder(new EmptyBorder(0,0,0,0));
//tabPanel.add(label); //???
tabPanel.add(textField);
tabPanel.add(new JButton(Integer.toString(i)));
pane.setTabComponentAt(
i, new JLayer<JPanel>(tabPanel, new DispatchEventLayerUI()));
}
add(pane);
}
}
class DispatchEventLayerUI extends LayerUI<JPanel> {
#Override
public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
//TEST:
//((JLayer) c).setLayerEventMask(
// AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
}
#Override
public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
// //TEST:
// #Override
// protected void processMouseEvent(MouseEvent e, JLayer<? extends JPanel> l) {
// dispatchEvent(e);
// }
#Override
protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends JPanel> l) {
dispatchEvent(e);
}
private void dispatchEvent(MouseEvent e) {
Component src = e.getComponent();
Container tgt = SwingUtilities.getAncestorOfClass(JTabbedPane.class, src);
tgt.dispatchEvent(SwingUtilities.convertMouseEvent(src, e, tgt));
}
}

Related

Java - Show menu from CardLayout

I want to have a menu bar in my GUI. The menu is not visible.
public class GUI extends JPanel implements ItemListener{
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
JPanel p;
JPanel cards = new JPanel(new CardLayout());
public GUI(){
JFrame window = new JFrame();
TestRun runTest = new TestRun();
cards.add(runTest , RUN_TEST);
cards.add(runTest , SETTINGS);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, RUN_TEST);
window.setContentPane(cards);
window.pack();
window.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
}
How can I show to the user the menu "Test 4G" and "settings" so that they can change the JPanel?
Thanks for your help
This is an example of using JMenuBar in JFrame and JPopupMenu in JPanel (view).
public class MainFrame extends JFrame {
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
private JPanel viewPanel = new JPanel();
public MainFrame() throws HeadlessException {
super("MainFrame");
cretaeGUI();
}
private void cretaeGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setJMenuBar(cretaeMenuBar());
setMinimumSize(new Dimension(800, 600));
viewPanel.setLayout(new CardLayout());
viewPanel.add(new Test4GView(this), RUN_TEST);
viewPanel.add(new SettingsView(this), SETTINGS);
add(viewPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JMenuBar cretaeMenuBar() {
JMenuItem testMenuItem = new JMenuItem("Test 4G");
testMenuItem.addActionListener(this::showTest4GView);
JMenuItem settingsMenuItem = new JMenuItem("Settings");
settingsMenuItem.addActionListener(this::showSettingsView);
JMenu viewMenu = new JMenu("View");
viewMenu.add(testMenuItem);
viewMenu.add(settingsMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(viewMenu);
return menuBar;
}
private void showView(String name) {
((CardLayout)viewPanel.getLayout()).show(viewPanel, name);
}
public void showTest4GView(ActionEvent event) {
showView(RUN_TEST);
}
public void showSettingsView(ActionEvent event) {
showView(SETTINGS);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
аnd these are both views
public class Test4GView extends JPanel {
private MainFrame mainFrame;
public Test4GView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Test 4G"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Settings");
showSettingsView.addActionListener(mainFrame::showSettingsView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
public class SettingsView extends JPanel {
private MainFrame mainFrame;
public SettingsView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Settings"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Test 4G");
showSettingsView.addActionListener(mainFrame::showTest4GView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}

Make image Icon Jump from one Label to another by Mouse click

I'm quite new to java here , and right now i'm working on a program which involves the following actions. Lets say i have a 3 X 3 grid of JLabel. How do i load an ImageIcon and then move it from on label to another. For example, say each label is named as label_1 to label_9, and the imageicon is on label_2 . When i click on label_3,imageicon it should go to label_3
Very quick example which you can adapt to your needs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Test extends JFrame {
public Test() {
JPanel container = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
JLabel label = new JLabel("Label" + i);
label.setPreferredSize(new Dimension(100, 100));
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
Icon icon = UIManager.getIcon("OptionPane.informationIcon");
JLabel clickedLabel = (JLabel) e.getSource();
Container parent = clickedLabel.getParent();
clearIcons(parent);
clickedLabel.setIcon(icon);
}
private void clearIcons(Container parent) {
Component[] components = parent.getComponents();
for (Component component : components) {
((JLabel) component).setIcon(null);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
container.add(label);
}
add(container);
}
public static void main(String[] args) {
Test frame = new Test();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
}
}
Result should be following:

How to center component vertically in JPanel which useFlowLayout

I have a certain panel which contains a random number of items. This panel is added to the EAST of a JPanel which use BorderLayout.
I'd like to have them vertically centered.
How do i achieve this?
here is a code you can run
public class MainFrame {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new AlignDemo());
}
}
class AlignDemo implements Runnable {
#Override
public void run(){
try {
JFrame mainWindow = new JFrame();
mainWindow.getContentPane().add(initPanel());
mainWindow.pack();
mainWindow.setVisible(true);
} catch (Throwable th) {
JOptionPane.showMessageDialog(null,null,"General Error", JOptionPane.ERROR_MESSAGE);
}
}
private JPanel initPanel() {
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
layout.setHgap(15);
JPanel myContent = new JPanel();
myContent.setPreferredSize(new Dimension(400,200));
myContent.setBorder(BorderFactory.createLineBorder(Color.blue));
JButton button1 = new JButton("I'm a button");
JButton button2 = new JButton("I'm a button");
JButton button3 = new JButton("I'm a button");
myContent.add(button1,Component.CENTER_ALIGNMENT);
myContent.add(button2,Component.CENTER_ALIGNMENT);
myContent.add(button3,Component.CENTER_ALIGNMENT);
return myContent;
}
}
It can easily be achieved by combining layouts. A JPanel with FlowLayout (controls) to position the buttons relative to one another, placed as a single component into a JPanel with a GridBagLayout (ui).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class CenteredButtons2 {
private JComponent ui = null;
CenteredButtons2() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout()); // to center a single component
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel controls = new JPanel(new FlowLayout());
for (int ii=1; ii<4; ii++) {
controls.add(new JButton("Button " + ii));
}
controls.setBorder(new EmptyBorder(50, 90, 50, 90));
ui.add(controls);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CenteredButtons2 o = new CenteredButtons2();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Swapping JPanel, 2nd JPanel doesn't display

I have a JFrame and 2 JPanels. One panel is the start screen with buttons. The other panel is the game screen. When I remove the start screen and display the game screen nothing happens to the JFrame. The start screen is persistent but not usable and the game runs in the background without updating the screen. When the game completes the start screen is usable again. I've searched everywhere online for a solution. They all say removeAll, revalidate, repaint, pack, or getContentPane.removeAll. I've not been able to get any of these solutions to work. Here is the driver class:
public class BallDriver extends JFrame {
private static final long serialVersionUID = 1L;
int width = 500;
int height = 500;
Container cont;
StartScreen start;
BallGame ballGame;
public BallDriver() {
cont = getContentPane();
startScreen();
}
private void startScreen() {
setTitle("BallGame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(width, height));
setPreferredSize(new Dimension(500,500));
start = new StartScreen();
JButton[] startButtons = start.getButtons();
setupButtons(startButtons);
add(start, BorderLayout.CENTER);
}
private void startGame(String difficulty) throws InterruptedException {
removeAll();
setSize(new Dimension(width, height));
setPreferredSize(new Dimension(width, height));
ballGame = new BallGame(width, height);
ballGame.setPreferredSize(new Dimension(width, height));
add(ballGame, BorderLayout.CENTER);
revalidate();
repaint();
while(!ballGame.endGame()) {
ballGame.moveBall();
ballGame.repaint();
try {
Thread.sleep(2);
} catch (InterruptedException e) { e.printStackTrace(); }
}
removeAll();
add(start, BorderLayout.CENTER);
revalidate();
repaint();
}
private void setupButtons(final JButton[] buttons) {
for (JButton button : buttons) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object object = e.getSource();
try {
if (object == buttons[0])
startGame(StartScreen.MODE_EASY);
if (object == buttons[1])
startGame(StartScreen.MODE_NORMAL);
if (object == buttons[2])
startGame(StartScreen.MODE_HARD);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
});
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BallDriver ballDriver = new BallDriver();
ballDriver.setVisible(true);
}
});
}
}
EDIT:
I've updated the class to use cardlayout, but the same thing occurs.
public class BallDriver extends JFrame {
private static final long serialVersionUID = 1L;
int width = 500;
int height = 500;
JPanel cardPanel = new JPanel();
Container cont;
StartScreen start;
BallGame ballGame;
CardLayout cardLayout = new CardLayout();
public BallDriver() {
setTitle("BallGame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(width, height));
setPreferredSize(new Dimension(width, height));
cardPanel.setLayout(cardLayout);
cont = getContentPane();
add(cardPanel, BorderLayout.CENTER);
startScreen();
}
private void startScreen() {
start = new StartScreen();
JButton[] startButtons = start.getButtons();
setupButtons(startButtons);
cardPanel.add(start, "start");
cardLayout.show(cardPanel, "start");
}
private void startGame(String difficulty) throws InterruptedException {
ballGame = new BallGame(width, height);
cardPanel.add(ballGame, "game");
cardLayout.show(cardPanel, "game");
cardPanel.revalidate();
cardPanel.repaint();
while(!ballGame.endGame()) {
System.out.println("Running");
ballGame.moveBall();
ballGame.repaint();
try {
Thread.sleep(2);
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
private void setupButtons(final JButton[] buttons) {
for (JButton button : buttons) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object object = e.getSource();
try {
if (object == buttons[0])
startGame(StartScreen.MODE_EASY);
if (object == buttons[1])
startGame(StartScreen.MODE_NORMAL);
if (object == buttons[2])
startGame(StartScreen.MODE_HARD);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
});
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BallDriver ballDriver = new BallDriver();
ballDriver.setVisible(true);
}
});
}
}
CardLayout allows you to add multiple panels to a Container, displaying only 1 panel at a time, with the ability to switch between panels. You set the parent's layout to CardLayout, add panels to your frame specifying a name as the constraints:
CardLayout layout = new CardLayout();
JFrame frame = new JFrame();
frame.setLayout(layout);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel1, "first");
frame.add(panel2, "second");
The first panel added is the first tk be displayed. To switch between panels, call CardLayout#show(Container, String), passing in the parent of the panels (considered the "deck") and the name of the specific panel you want (considered the "card").
layout.show(frame, "second");
A common problem people have with CardLayout is having the parent resize to the current panel's size. This can be achieved by extending upon CardLayout

Java Swing: Enabling/Disabling all components in JPanel

I have a JPanel which contains a JToolbar (including few buttons without text) and a JTable and I need to enable/disable (make internal widgets not clickable). I tried this:
JPanel panel = ....;
for (Component c : panel.getComponents()) c.setEnabled(enabled);
but it doesn't work. Is there a better and more generic solution to enable/disable all internal components in a JPanel?
I have partially solved my problem using JLayer starting from the example here http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html:
layer = new JLayer<JComponent>(myPanel, new BlurLayerUI(false));
.....
((BlurLayerUI)layer.getUI()).blur(...); // switch blur on/off
class BlurLayerUI extends LayerUI<JComponent> {
private BufferedImage mOffscreenImage;
private BufferedImageOp mOperation;
private boolean blur;
public BlurLayerUI(boolean blur) {
this.blur = blur;
float ninth = 1.0f / 9.0f;
float[] blurKernel = {
ninth, ninth, ninth,
ninth, ninth, ninth,
ninth, ninth, ninth
};
mOperation = new ConvolveOp(
new Kernel(3, 3, blurKernel),
ConvolveOp.EDGE_NO_OP, null);
}
public void blur(boolean blur) {
this.blur=blur;
firePropertyChange("blur", 0, 1);
}
#Override
public void paint (Graphics g, JComponent c) {
if (!blur) {
super.paint (g, c);
return;
}
int w = c.getWidth();
int h = c.getHeight();
if (w == 0 || h == 0) {
return;
}
// Only create the offscreen image if the one we have
// is the wrong size.
if (mOffscreenImage == null ||
mOffscreenImage.getWidth() != w ||
mOffscreenImage.getHeight() != h) {
mOffscreenImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig2 = mOffscreenImage.createGraphics();
ig2.setClip(g.getClip());
super.paint(ig2, c);
ig2.dispose();
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(mOffscreenImage, mOperation, 0, 0);
}
#Override
public void applyPropertyChange(PropertyChangeEvent pce, JLayer l) {
if ("blur".equals(pce.getPropertyName())) {
l.repaint();
}
}
}
I still have 2 problems:
In the link above events are relative to mouse only. How can I manage the keyboard events?
How can I create a "gray out" effect in place of blur?
It requires a recursive call.
import java.awt.*;
import javax.swing.*;
public class DisableAllInContainer {
public void enableComponents(Container container, boolean enable) {
Component[] components = container.getComponents();
for (Component component : components) {
component.setEnabled(enable);
if (component instanceof Container) {
enableComponents((Container)component, enable);
}
}
}
DisableAllInContainer() {
JPanel gui = new JPanel(new BorderLayout());
final JPanel container = new JPanel(new BorderLayout());
gui.add(container, BorderLayout.CENTER);
JToolBar tb = new JToolBar();
container.add(tb, BorderLayout.NORTH);
for (int ii=0; ii<3; ii++) {
tb.add(new JButton("Button"));
}
JTree tree = new JTree();
tree.setVisibleRowCount(6);
container.add(new JScrollPane(tree), BorderLayout.WEST);
container.add(new JTextArea(5,20), BorderLayout.CENTER);
final JCheckBox enable = new JCheckBox("Enable", true);
enable.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
enableComponents(container, enable.isSelected());
}
});
gui.add(enable, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new DisableAllInContainer();
}
});
}}
I used the following function:
void setPanelEnabled(JPanel panel, Boolean isEnabled) {
panel.setEnabled(isEnabled);
Component[] components = panel.getComponents();
for(int i = 0; i < components.length; i++) {
if(components[i].getClass().getName() == "javax.swing.JPanel") {
setPanelEnabled((JPanel) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}
you can overlay whole Container / JComponent
GlassPane block by default MouseEvents, but not Keyboard, required consume all keyevents from ToolKit
JLayer (Java7) based on JXLayer (Java6)
can't see reason(s) why not works for you
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class AddComponentsAtRuntime {
private JFrame f;
private JPanel panel;
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
public AddComponentsAtRuntime() {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(600, 20));
panel = new JPanel(new GridLayout(0, 1));
panel.add(b);
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel, "Center");
f.add(getCheckBoxPanel(), "South");
f.setLocation(200, 200);
f.pack();
f.setVisible(true);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(true);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(true);
checkPack = new JCheckBox("pack");
checkPack.setSelected(true);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(400, 10));
panel.add(b);
makeChange();
System.out.println(" Components Count after Adds :" + panel.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = panel.getComponentCount();
if (count > 0) {
panel.remove(0);
}
makeChange();
System.out.println(" Components Count after Removes :" + panel.getComponentCount());
}
});
JButton disabledComp = new JButton("Disabled All");
disabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(false);
}
}
});
JButton enabledComp = new JButton("Enabled All");
enabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(true);
}
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
panel2.add(disabledComp);
panel2.add(enabledComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
panel.validate();
}
if (checkReValidate.isSelected()) {
panel.revalidate();
}
if (checkRepaint.isSelected()) {
panel.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
}
#Kesavamoorthi
if you want to make it more general:
void setPanelEnabled(java.awt.Container cont, Boolean isEnabled) {
cont.setEnabled(isEnabled);
java.awt.Component[] components = cont.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof java.awt.Container) {
setPanelEnabled((java.awt.Container) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}

Categories

Resources