Java swing gui change background of jlabel and make it reset - java

I have a gui that has:
a label at the top
a JFrame at the bottom with 2 Buttons called left and right
a panel in center that is gridlayout with 2 JLabel to either display an image or change the back ground color. (currently the background color is set to black for both jLabels).
*what I would like to happen.
When you click on button "left" the image appears on lblPicture1 and lblPicture2 has a black background and no image. and vise versa for the right button. and when you click on the left again, it repeats this cycle.
I accomplish that however, when i click the left and right button I just have two images and neither one has a black background.
I belive this is due to the image not resetting.
Can you direct me to the right place on how I can get this to work?
Thank you
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ExampleGUI extends JFrame {
private JPanel contentPane;
private JLabel lblPicture1;
private JLabel lblPicture2;
private int change;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleGUI frame = new ExampleGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblExampleGui = new JLabel("Example GUI");
lblExampleGui.setBorder(new EmptyBorder(8, 0, 8, 0));
lblExampleGui.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
lblExampleGui.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblExampleGui, BorderLayout.NORTH);
JPanel panelButton = createPanelButton();
contentPane.add(panelButton, BorderLayout.SOUTH);
JButton btnLeft = createBtnLeft();
panelButton.add(btnLeft);
JButton btnRight = createBtnRight();
panelButton.add(btnRight);
JPanel panelCenter = createPanelCenter();
contentPane.add(panelCenter, BorderLayout.CENTER);
JLabel lblPicture1 = createLblPicture1();
panelCenter.add(lblPicture1);
JLabel lblPicture2 = createPicture2();
panelCenter.add(lblPicture2);
}
public JLabel createPicture2() {
lblPicture2 = new JLabel();
lblPicture2.setOpaque(true);
lblPicture2.setBackground(Color.BLACK);
return lblPicture2;
}
public JLabel createLblPicture1() {
lblPicture1 = new JLabel();
lblPicture1.setOpaque(true);
lblPicture1.setBackground(Color.BLACK);
//lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
return lblPicture1;
}
public JPanel createPanelCenter() {
JPanel panelCenter = new JPanel();
panelCenter.setLayout(new GridLayout(0, 2, 8, 0));
return panelCenter;
}
public JButton createBtnRight() {
JButton btnRight = new JButton("right");
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture1.setBackground(Color.BLACK);
lblPicture2.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnRight.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnRight;
}
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}
public JPanel createPanelButton() {
JPanel panelButton = new JPanel();
return panelButton;
}
}

The background is painted beneath the icon, so if the icon is not reset, then it will continue to be displayed.
You can simply set the icon property by passing it null, for example
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setIcon(null);
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}

Related

Trying to set the location of a Java Button using JFrame isn't working?

Please look below for Edits.
So I've looking over numerous "solutions" to fix my problem, but I just can't seem to get it working.
This is what my application looks like with the code below:
Basically, I want to set the location of a button, but I can't manage to do so. Here is my code:
package me.cervinakuy.application;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
startRobo.setLocation(100, 100);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
EDIT:
I have now managed to create a GUI of what I was initially looking for, however, I have a new problem. Buttons are now pressable from different parts of the GUI, rather than only on the image. For those interested, here is what I have been able to accomplish:
New GUI look.
Updated Code:
package me.cervinakuy.application;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
panel.setLayout(null);
startRobo.setLocation(200, 200);
startRobo.setBounds(5, -95, 300, 300);
stopRobo.setBounds(5, 0, 300, 300);
restartRobo.setBounds(5, 95, 300, 300);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
There are typically a number of ways to layout components that end with the same effect. In this example, we use a panel to contain the buttons in a column (buttonContainer using a GridLayout) then a panel to restrict that container to the top (buttonConstrainPanel using a BorderLayout) then a container to put that panel on the left (ui with BorderLayout).
It could also be achieved using a single GridBagLayout or a GroupLayout, though the logic of achieving it might not be as simple.
The focus border seen on the blue button indicates the limits of where a mouse click would activate the button.
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThreeButtonAlignedLeft {
private JComponent ui = null;
private String prefix = "http://i.stack.imgur.com/";
private String[] suffix = {"gJmeJ.png","T5uTa.png","wCF8S.png"};
ThreeButtonAlignedLeft() {
try {
initUI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
public void initUI() throws MalformedURLException {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel buttonContainer = new JPanel(new GridLayout(0, 1, 5, 5));
for (int ii=0; ii<suffix.length; ii++) {
JButton b = new JButton(new ImageIcon(new URL(prefix + suffix[ii])));
b.setBorderPainted(false);
b.setMargin(new Insets(0,0,0,0));
b.setContentAreaFilled(false);
buttonContainer.add(b);
}
JPanel buttonConstrainPanel = new JPanel(new BorderLayout(0, 0));
buttonConstrainPanel.add(buttonContainer, BorderLayout.PAGE_START);
ui.add(buttonConstrainPanel, BorderLayout.LINE_START);
}
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) {
}
ThreeButtonAlignedLeft o = new ThreeButtonAlignedLeft();
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);
}
}

Switching between jpanels with a click of a button using CardLayout [duplicate]

This question already has answers here:
Implementing back/forward buttons in Swing
(3 answers)
Closed 8 years ago.
I want to know how do you go to another panel by pressing a button.
The codes for my main GUI is below:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MainMenu extends JFrame {
private JPanel contentPane, confirmPage_Panel;
private JTextField NumberofSoups_TEXTFIELD;
private JTextField NumberofSandwiches_TEXTFIELD;
private JTextField totalCost_TEXTFIELD;
private JTextField OrderNumber_TEXTFIELD;
private int Soupclicks = 0;
private int Sandwichclicks = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainMenu() {
super("Welcome Yo!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1268, 716);
contentPane = new JPanel();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new LineBorder(new Color(255, 200, 0), 4, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Header_Panel = new JPanel();
Header_Panel.setBackground(Color.DARK_GRAY);
Header_Panel.setBounds(145, 11, 977, 35);
contentPane.add(Header_Panel);
JLabel Header_Label = new JLabel("Super Sandwich Store");
Header_Label.setForeground(Color.PINK);
Header_Label.setFont(new Font("Tahoma", Font.PLAIN, 22));
Header_Panel.add(Header_Label);
JPanel Soup_Panel = new JPanel();
Soup_Panel.setBackground(Color.PINK);
Soup_Panel.setBounds(10, 71, 459, 339);
contentPane.add(Soup_Panel);
Soup_Panel.setLayout(null);
JButton Confirm_Button = new JButton("Confirm Now");
Confirm_Button.setFont(new Font("Tahoma", Font.PLAIN, 14));
Confirm_Button.setBounds(511, 558, 121, 23);
contentPane.add(Confirm_Button);
JButton Exit_Button = new JButton("Exit");
Exit_Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
Exit_Button.setFont(new Font("Tahoma", Font.PLAIN, 13));
Exit_Button.setBounds(641, 558, 111, 23);
contentPane.add(Exit_Button);
}// end of MainMenu()
}
And when i clicked the confirm button it will invoke this page :
public class ConfirmationGUI extends JFrame {
private JPanel contentPane;
private JTextField ConfirmedOrder_Field;
private JTextField totalCost_Field;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConfirmationGUI frame = new ConfirmationGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ConfirmationGUI() {
super("Confirmation Yo!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 668, 457);
contentPane = new JPanel();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new LineBorder(Color.ORANGE, 4, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Top_Panel = new JPanel();
Top_Panel.setBackground(Color.DARK_GRAY);
Top_Panel.setBounds(5, 5, 637, 93);
contentPane.add(Top_Panel);
Top_Panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Super Sandwich Store");
lblNewLabel.setForeground(Color.PINK);
lblNewLabel.setBounds(245, 11, 185, 45);
Top_Panel.add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
}
}
It would be much of a help,
Thank you :)
To switch between JFrames, call setVisible(true) for the JFrame you want to reveal and setVisible(false) for the one you want to hide. CardLayout doesn't apply here.
Suggestions: read the Swing tutorial on layouts, don't use null layouts with absolutely positioning, and familiarize yourself with the differences between ordinary containers and top-level containers.

Java - Swapping multiple JFrames on button press

this is the first time I've had a look at JFrames and JPannels and I've come a little stuck.
What I am trying to do is this, I wish to have an starting screen then based on the users button choice it swaps to another screen. To start I have only 2 screens, however once I've moved on there will be multiple screens. I've looked at CardLayout and while that is good it's not the way I wish to go I want to be able to do this first. Here is what I have.
Main.java
import java.awt.BorderLayout;
public class Main extends JFrame {
private JPanel contentPane;
protected boolean someCondition = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
if( someCondition == false ){
showTest();
someCondition = test.needToReg();
}else{
showTest2();
}
}
private void showTest(){
contentPane.removeAll();
contentPane.add(new test());
setContentPane(contentPane);
revalidate();
repaint();
}
private void showTest2(){
contentPane.removeAll();
contentPane.add(new test2());
setContentPane(contentPane);
revalidate();
repaint();
}
}
test.java
import javax.swing.JPanel;
public class test extends JPanel {
private JTextField textField;
protected static boolean toReg = false;
/**
* Create the panel.
*/
public test() {
setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
System.out.println("Before " + toReg);
toReg = true;
System.out.println("After " + toReg);
}
});
btnNewButton.setBounds(188, 166, 89, 23);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(150, 135, 86, 20);
add(textField);
textField.setColumns(10);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
rdbtnNewRadioButton.setBounds(6, 166, 109, 23);
add(rdbtnNewRadioButton);
}
public static boolean needToReg(){
return toReg;
}
}
test2.java
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
public class test2 extends JPanel {
/**
* Create the panel.
*/
public test2() {
setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(56, 59, 89, 23);
add(btnNewButton);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(122, 165, 46, 14);
add(lblNewLabel);
}
}
Running the program with the outputs I included I get this.
Mouse Clicked
Before false
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
I hope it's clear what I am trying to do and I hope you can lend a hand with this. Thanks
Try this out
On clicking the screenSwapper button in the main frame a new Panel is added to the main frame that can have multiple components I have added one button only
On second click this panel is removed and second panel is added to the main frame and previous one is removed.
The swapping is carried as you click the button continuously
You may use two singletons if you want to preserve once created panel in case of MyPanel1 and MyPanel2
You may add more components on each panel and test.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
public boolean switcher;
public JPanel currentPanel;
public JPanel panel1;
public JPanel panel2;
public Test() {
this.switcher = false;
this.currentPanel = null;
this.setSize(200, 200);
panel1 = new JPanel();
JButton screenSwapper = new JButton("Screen Swapper");
panel1.add(screenSwapper);
panel2 = new JPanel();
this.getContentPane().setLayout(new GridLayout(2, 2));
this.getContentPane().add(panel1);
this.getContentPane().add(panel2);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screenSwapper.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (switcher == false) {
currentPanel = new MyPanel1();
switcher = true;
if (panel2.getComponentCount() != 0) {
panel2.removeAll();
}
} else {
switcher = false;
currentPanel = new MyPanel2();
if (panel2.getComponentCount() != 0) {
panel2.removeAll();
}
}
panel2.add(currentPanel);
panel2.repaint();
panel2.revalidate();
}
});
}
public static void main(String[] args) {
Test t = new Test();
}
}
This is the first panel
import java.awt.BorderLayout;
import java.awt.Button;
import javax.swing.JPanel;
public class MyPanel1 extends JPanel{
public MyPanel1() {
// TODO Auto-generated constructor stub
this.setLayout(new BorderLayout());
this.add(new Button("Button1"));
}
}
This is the second Panel
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MyPanel2 extends JPanel {
public MyPanel2() {
this.setLayout(new BorderLayout());
this.add(new JButton("button2"));
}
}

How to remove the blue line from a Panel after creating a TitleBorder using BorderFactory?

I created a JPanel and i have added a TitleBorder with BorderFactory but it's showing a blue line around the panel.
I would like to remove this line.
Any suggestions?
Thank you
never tried to extract this value from TitleBorders API, methods are protected, or by using UIManager
have to use LineBorder inside TitleBorder
simpliest syntax could be xxx.setBorder(new TitledBorder(new LineBorder(Color.ORANGE, 1), "label")); or get the Color from (for example) myPanel.getBackground() instread of Color.ORANGE
another options are (is possible)
move desciption (top, bottom.....)
change Font
change Foreground (Color for description)
more options and description in Oracle tutorial How to Use Borders (CompounBorders)
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
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;
import javax.swing.border.TitledBorder;
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, 10));
panel = new JPanel(new GridLayout(0, 1));
panel.add(b);
panel.setBorder(new TitledBorder(new LineBorder(Color.ORANGE, 1),
"Add Components At Runtime"));
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(false);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(false);
checkPack = new JCheckBox("pack");
checkPack.setSelected(false);
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(600, 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());
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
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) {
EventQueue.invokeLater(new Runnable() {
public void run() {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
});
}
}
The blue line (in metal) is the default border used by TitledBorder if none is given explicitly. You need to provide another border if you don't like the default, f.i. an EmptyBorder:
myPanel.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEmptyBorder(), someTitle));

CardLayout display Next panel - java Swing

I am having some problem with CardLayout. I have a panel and a Next button on it. upon clicking on it i want to display the 2nd panel. In my code, when i click on the Next buton, the next panel is not displayed. Can someone help me solve this ?
package com.test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CardLay extends JFrame {
private JPanel contentPane;
private CardLayout ca;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CardLay frame = new CardLay();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CardLay() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
ca =new CardLayout(0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(ca);
JPanel panel = new JPanel();
panel.setLayout(null);
contentPane.add("1",panel);
JButton btnNext = new JButton("NEXT");
btnNext.setBounds(131, 93, 117, 29);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ca.show(contentPane,"1");
System.out.println("button clicked");
}
});
panel.add(btnNext);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, "name_1353086933711396000");
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel_1.add(chckbxNewCheckBox);
}
}
You need to call:
ca.show(contentPane, "name_1353086933711396000");
For this to work you will have to add the second panel like this:
contentPane.add("name_1353086933711396000", panel_1);
When using CardLayout make sure to keep navigation buttons on a separate container other then the 'cards' themselves, so that they can be visible throughout the navigation process. Here you could place a new navigation container in the frame's BorderLayout.SOUTH position. For sequential navigation, the methods previous and next are available.
Also avoid using absolute positioning (null layout). See Doing Without a Layout Manager (Absolute Positioning).
public CardLay() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 400);
ca = new CardLayout(0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(ca);
JPanel panel1 = new JPanel();
panel1.add(new JButton("Test Button"));
contentPane.add("card1", panel1);
JPanel panel2 = new JPanel();
contentPane.add("card2", panel2);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel2.add(chckbxNewCheckBox);
JPanel navigationPanel = new JPanel();
JButton btnPrevious = new JButton("< PREVIOUS");
btnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca.previous(contentPane);
}
});
navigationPanel.add(btnPrevious);
JButton btnNext = new JButton("NEXT >");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca.next(contentPane);
}
});
navigationPanel.add(btnNext);
add(contentPane);
add(navigationPanel, BorderLayout.SOUTH);
}
Recommended: How to Use CardLayout

Categories

Resources