I am having problems with figuring how to use event handlers in order to remove and repaint between 2 panels.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelSwitcherView extends JFrame {
private JPanel panel1, panel2;
public PanelSwitcherView() {
super("Panel Switching Test");
Font font = new Font("SansSerif", Font.BOLD, 30);
panel1 = new JPanel();
panel1.setLayout(new GridLayout(2, 2, 5, 5));
font = new Font("Serif", Font.ITALIC, 30);
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
Here I decided to add a test ActionListener but am unsure if correctly used
font = new Font("Monospaced", Font.BOLD + Font.ITALIC, 30);
JButton button = new JButton("Switch Panels");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.print("Test");
PanelSwitcherModel.switchPanel(); // used to make value of whichpanel 1 or 2
}
});
button.setFont(font);
add(button, BorderLayout.NORTH);
add(panel1, BorderLayout.CENTER);
}
Not completely sure how to use this either
public void displayPanel(int whichPanel) {
remove(panel1);
remove(panel2);
if (whichPanel == 1) {
System.out.println("Should display panel1");
add(panel1, BorderLayout.CENTER);
} else {
System.out.println("Should display panel2");
add(panel2, BorderLayout.CENTER);
}
validate();
repaint();
}
My Controller (class below)
public void register(PanelSwitcherController controller) {
}
Problem lies mainly here, I am a newbie here, do I move my ActionListener here somehow? How do I access other classes in order to change the number from 1 to 2 for my panel options?
import java.awt.event.*;
public class PanelSwitcherController implements ActionListener{
public PanelSwitcherController(PanelSwitcherView view,
PanelSwitcherModel model) {
}
public void actionPerformed(ActionEvent e) {
}
}
Related
I made a desktop application to handle the configuration of some web services, it works but the code is hard to maintain because all de logic view is in the same class (main class), so I decided to redo it and apply the MVC architecture and the React philosophy to split the complex app into simple and reusable components. I end up whit this:
My app has a JFrame that has a main JPanel, this main JPanel has many other JPanels but the mains ones are centerJPanel and SaveJPanel for demonstration purposes. The centerJPanel has my Composite Component (blue rectangle), ContenedorSwtBtn.
My ContenedorSwtBtn consists of JPanel, JLabel for the title, and SwitchToggleBtn component, and I can have as many SwitchToggleBtn as I want because the idea is to add them dynamically.
My SwitchToggleBtn consists of a JPanel, JLabel for the name, and JToggleButton.
The code (Sorry for the Spanish word) for MyComponent: SwitchToggleBtn:
public class SwitchToggleBtn extends JPanel
{
private JToggleButton SwtBtn;
private JLabel nombLogs;
private String Name;
public SwitchToggleBtn(String Nombre, boolean bandera)
{
super(new BorderLayout(10,10));
this.Name = Nombre;
this.setBackground(new java.awt.Color(255, 255, 255));
this.setBorder( new EmptyBorder( 5, 5, 5, 12));
this.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(153, 153, 153)));
this.nombLogs = new JLabel(Nombre);
this.nombLogs.setFont(new java.awt.Font("Segoe UI Symbol", 0, 14));
this.add(nombLogs, BorderLayout.WEST);
this.SwtBtn = new JToggleButton();
this.SwtBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/principal/icon/btnToggleOff.png"))); // NOI18N
this.SwtBtn.setBorder(null);
this.SwtBtn.setBorderPainted(false);
this.SwtBtn.setContentAreaFilled(false);
this.SwtBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
this.SwtBtn.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/principal/icon/btnToggleOffDisabled.png"))); // NOI18N
this.SwtBtn.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/principal/icon/btnToggleOnDisable.png"))); // NOI18N
this.SwtBtn.setFocusPainted(false);
this.SwtBtn.setMaximumSize(new java.awt.Dimension(70, 34));
this.SwtBtn.setMinimumSize(new java.awt.Dimension(70, 34));
this.SwtBtn.setPreferredSize(new java.awt.Dimension(70, 34));
this.SwtBtn.setSelected(bandera);
this.SwtBtn.setName(Nombre);
IsSelected();
this.SwtBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
IsSelected();
}
});
this.add(SwtBtn, BorderLayout.EAST);
this.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mouseclicked(evt);
}
});
}
private void IsSelected()
{
if (this.SwtBtn.isSelected())
this.SwtBtn.setIcon(new ImageIcon(getClass().getResource("/principal/icon/btnToggleOn.png")));
else
this.SwtBtn.setIcon(new ImageIcon(getClass().getResource("/principal/icon/btnToggleOff.png")));
}
}
The code (Sorry for the Spanish word) for ContenedorSwtBtn:
public class ContenedorSwtBtn extends JPanel
{
public ContenedorSwtBtn(String Nombre)
{
super();
this.setBackground(new java.awt.Color(255, 255, 255));
this.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(153, 153, 153)));
this.setToolTipText("");
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel titulo = new JLabel();
titulo.setBackground(new java.awt.Color(0, 0, 0));
titulo.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
titulo.setForeground(new java.awt.Color(0, 51, 51));
titulo.setText(Nombre);
titulo.setAlignmentX(Component.CENTER_ALIGNMENT);
this.add(titulo);
}
public void AddComponent(String nombreLog, boolean bandera)
{
SwitchToggleBtn log = new SwitchToggleBtn(nombreLog, bandera);
this.add(log);
}
}
This is the final result :
when I clicked the JToggleButton inside of my SwichToggleBtn component it changes his state and changes the icon from off to on or vice versa.
And finally is matter of create the new component and add it into the main JPanel like this:
JPanel MainPanel= new JPanel();
MainPanel.setBackground(new java.awt.Color(255, 255, 255));
MainPanel.setEnabled(true);
MainPanel.setMaximumSize(new java.awt.Dimension(300, 280));
MainPanel.setMinimumSize(new java.awt.Dimension(300, 280));
MainPanel.setPreferredSize(new java.awt.Dimension(300, 280));
MainPanel.setVisible(true);
ContenedorSwtBtn myComponent= new ContenedorSwtBtn("SETTINGS");
myComponent.AddComponent("ONE", true);
myComponent.AddComponent("TWO", false);
myComponent.AddComponent("THREE",true);
MainPanel.add(myComponent);
When I clicked the JToggleButton and changes its state I want the exact component and its current state but from the main Jpanel or the center panel so that way I can "Save change" (red button from SaveJpanel) and implement some logic to save the configuration. How I pass the event from the child component to the parent's components or how from the parent's components can know when a child component changes its state. I read about creating a class that implements the actionlistener interface or implements the PropertyChangesListener interface but I don understand. thanks a lot for your help.
I am not sure what you are wanting to do given your question has anything to do with MVC (For an example of an MVC Swing app please look here), as far as I can tell all you really need is to bubble up events from your custom control so that you can register to receive these events in your main panel.
This can easily be done. Check my below example.
Essentially:
ButtonPanel is its own "component" (it doesnt extend JPanel as I dont think thats necessary, instead has a getter getPanel() for the component it creates).
ButtonPanel also implements an ActionListener for the buttons events it creates
ButtonPanel has the ability to add an ActionListener via addActionListener so others may register for ActionEvents sent from the ButtonPanel.
TestApp.java:
import java.awt.event.ActionEvent;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class TestApp {
public TestApp() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGUI() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
ButtonPanel buttonPanel = new ButtonPanel();
// here we register for events created from the button panel as buttons are pressed
buttonPanel.addActionListener((ActionEvent e) -> {
JToggleButton button = (JToggleButton) e.getSource();
switch (e.getActionCommand()) { // which button was pressed?
case "button1":
JOptionPane.showMessageDialog(panel, "Button 1 pressed and isSelected is: " + button.isSelected());
break;
case "button2":
JOptionPane.showMessageDialog(panel, "Button 2 pressed and isSelected is:" + button.isSelected());
break;
}
});
panel.add(buttonPanel.getPanel());
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
ButtonPanel.java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class ButtonPanel implements ActionListener {
private JPanel panel;
private JToggleButton button1;
private JToggleButton button2;
private ActionListener actionListener;
public ButtonPanel() {
initView();
}
private void initView() {
panel = new JPanel();
button1 = new JToggleButton("Button 1 (OFF)");
button2 = new JToggleButton("Button 2 (OFF)");
button1.addActionListener(this);
button2.addActionListener(this);
panel.add(button1);
panel.add(button2);
}
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton button = ((JToggleButton) e.getSource());
button.setText(button.getText().substring(0, button.getText().indexOf("(")) + "(" + (button.isSelected() ? "ON" : "OFF") + ")");
if (e.getSource() == button1) {
if (actionListener != null) {
actionListener.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, "button1"));// we send button1 as a command so we know what button was pressed
}
} else if (e.getSource() == button2) {
if (actionListener != null) {
actionListener.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, "button2"));// we send button2 as a command so we know what button was pressed
}
}
}
public JPanel getPanel() {
return panel;
}
void addActionListener(ActionListener actionListener) {
this.actionListener = actionListener;
}
}
I am a beginner in Java, but somehow have a bit of knowledge but still beyond. I wanted to ask , how do align buttons in this main menu I just created. The buttons are somehow aligned horizontally.
This is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class mainmenu extends JFrame
{
JButton b1;
JLabel l1;
JButton b2;
public mainmenu() {
setResizable(false);
setLocation(100, 100);
setSize(500, 500);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\BG HOROR.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
b2=new JButton(" EXIT! ");
b1.addActionListener(new btnFunc());
background.add(l1);
background.add(b1);
background.add(b2);
}
public void armaged() {
add(new gamesamplingbeta());
}
public static void main(String args[])
{
new mainmenu();
}
public class btnFunc implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
}
public class btnFunc2 implements ActionListener {
public void actionPerformed2 (ActionEvent e) {
System.exit(1);
}
}
}
You should take a look at Swing Layouts for a whole bunch of different layout managers that allow you to position your components in a bunch of different ways.
The one I believe you should be using for this question is the Box Layout if you would like your buttons centered vertically.
Here is an example of one.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("Vertical Buttons");
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public MainFrame()
{
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(label1);
mainPanel.add(button1);
mainPanel.add(button2);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
If you would like to add spacing in between any of the components, use a Rigid Area like so
container.add(component);
container.add(Box.createRigidArea(new Dimension(100, 100));
container.add(component1);
I am currently trying to make a little app using a jframe that has multiple jpanels. I have a couple questions about this.
There has to be a cleaner way of making an app with 16 different panels than having it all inside one class. What are some other options.
Currently I only have 3 panels. I haven't gone any further because 2 of the panels aren't reflecting my changes. They are the two panels I call using
removeAll();
add();
revalidate();
repaint();
What would be causing the other panels I am calling to be blank?
Here is a look at what I have, any advice would be great. Thanks
public class Jframetest extends JFrame {
private JPanel Home;
private JPanel masslog;
private JPanel DEH;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Jframetest frame = new Jframetest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Jframetest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(100, 100, 618, 373);
Home = new JPanel();
masslog = new JPanel();
DEH = new JPanel();
Home.setBackground(new Color(255, 250, 250));
Home.setBorder(new LineBorder(Color.DARK_GRAY, 1, true));
DEH.setBackground(new Color(255, 250, 250));
DEH.setBorder(new LineBorder(Color.DARK_GRAY, 1, true));
masslog.setBackground(new Color(255, 250, 250));
masslog.setBorder(new LineBorder(Color.DARK_GRAY, 1, true));
setContentPane(Home);
Home.setLayout(null);
JButton dehbutton = new JButton("Sign in");
dehbutton.setFont(new Font("Tahoma", Font.PLAIN, 14));
dehbutton.setForeground(new Color(0, 0, 0));
dehbutton.setBackground(UIManager.getColor("Menu.selectionBackground"));
DEH.add(dehbutton);
JButton btnNewButton = new JButton("Data Entry login");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnNewButton.setForeground(new Color(0, 0, 0));
btnNewButton.setBackground(UIManager.getColor("Menu.selectionBackground"));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Home.removeAll();
Home.add(DEH);
Home.revalidate();
Home.repaint();
// JOptionPane.showMessageDialog(null, "Username/Password incorrect");
}
});
btnNewButton.setBounds(44, 214, 204, 61);
Home.add(btnNewButton);
final JButton button = new JButton("Manager and Associate login");
button.setFont(new Font("Tahoma", Font.PLAIN, 14));
button.setBackground(UIManager.getColor("EditorPane.selectionBackground"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home.removeAll();
Home.add(masslog);
Home.revalidate();
Home.repaint();
}
});
button.setBounds(340, 214, 204, 61);
Home.add(button);
JTextPane txtpnEmployeeLogin = new JTextPane();
txtpnEmployeeLogin.setForeground(Color.DARK_GRAY);
txtpnEmployeeLogin.setBackground(Color.WHITE);
txtpnEmployeeLogin.setFont(new Font("Tahoma", Font.PLAIN, 34));
txtpnEmployeeLogin.setText("Employee Login");
txtpnEmployeeLogin.setBounds(181, 123, 260, 52);
Home.add(txtpnEmployeeLogin);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Will and April\\Downloads\\your-logo-here.jpg"));
lblNewLabel.setBounds(427, 11, 165, 67);
Home.add(lblNewLabel);
}
}
Your mistake is using a null layout, revalidate, invalidate and validate will no longer have any significant meaning, because they are related to supporting the layout management API.
Because you've removed the layout manager, you panels no longer have anything to tell them what size or location that they should appear at, meaning when you add a new component, it has a size of 0x0 and position of 0x0
Update with example
There are many reasons why you should take advantage of the layout manager API, including automatic handling of differences between how fonts are rendered on different systems, dynamic and resizable layouts, differences in screen resolution and DPI to name a few.
It will also encourage you to separate your UI into areas of responsibility instead of trying to dump your entire UI code into a single class (yes, I've seen this done, yes, I've spent most of my career cleaning up after people who do this...)
This example makes use of CardLayout and GridBagLayout, but you should take the time to become farmiluar with the some of the others avaiable in the default JDK
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.EmptyBorder;
public class FrameTest extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final CardLayout layout = new CardLayout();
setLayout(layout);
LoginPane loginPane = new LoginPane();
add(loginPane, "login");
add(new NewLoginPane(), "newLogin");
add(new ManagerLoginPane(), "managerLogin");
loginPane.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
System.out.println(command);
if ("new".equals(command)) {
layout.show(getContentPane(), "newLogin");
} else if ("manager".equals(command)) {
layout.show(getContentPane(), "managerLogin");
}
}
});
layout.show(getContentPane(), "layout");
pack();
setLocationRelativeTo(null);
}
public class LoginPane extends JPanel {
private JTextField userName;
private JButton newButton;
private JButton managerButton;
public LoginPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 1;
gbc.insets = new Insets(10, 10, 10, 10);
userName = new JTextField(10);
userName.setFont(new Font("Tahoma", Font.PLAIN, 34));
add(userName, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
newButton = new JButton("Sign in");
newButton.setActionCommand("new");
managerButton = new JButton("Manager and Associate login");
managerButton.setActionCommand("manager");
add(newButton, gbc);
gbc.gridx++;
add(managerButton, gbc);
}
public void addActionListener(ActionListener listener) {
newButton.addActionListener(listener);
managerButton.addActionListener(listener);
}
public void remveActionListener(ActionListener listener) {
newButton.removeActionListener(listener);
managerButton.removeActionListener(listener);
}
public String getUserName() {
return userName.getText();
}
}
public class NewLoginPane extends JPanel {
public NewLoginPane() {
setLayout(new GridBagLayout());
add(new JLabel("New Login"));
}
}
public class ManagerLoginPane extends JPanel {
public ManagerLoginPane() {
setLayout(new GridBagLayout());
add(new JLabel("Welcome overlord"));
}
}
}
There has to be a cleaner way of making an app with 16 different panels than having it all inside one class. What are some other options.
You are free to create and use as many classes as need be. So if a JPanel holds a complex bit of GUI that you may wish to re-use elsewhere, or that has its own specific and separate functionality, by all means put the code in its own class.
Currently I only have 3 panels. I haven't gone any further because 2 of the panels aren't reflecting my changes. They are the two panels I call using
removeAll();
add();
revalidate();
repaint();
Smells like you're trying to re-invent the CardLayout. Why re-invent it when you can just use it?
And yes, everything MadProgrammer says about null layout is true. You should avoid using it.
Oh, the CardLayout may work for you. I thought about using a JTabbedPane. Here are my thoughts in a code example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class TabbedPaneDemo extends JFrame {
public TabbedPaneDemo() {
// set the layout of the frame to all the addition of all components
setLayout(new FlowLayout());
// create a tabbed pane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setPreferredSize(new Dimension(500,500));
add(tabbedPane);
// create three panels to be added to this frame
JPanel redPanel = new JPanel();
JPanel greenPanel = new JPanel();
JPanel bluePanel = new JPanel();
// set the colors of the panels
redPanel.setBackground(Color.RED);
greenPanel.setBackground(Color.GREEN);
bluePanel.setBackground(Color.BLUE);
// set the preferred size of each panel
redPanel.setPreferredSize(new Dimension(150,150));
greenPanel.setPreferredSize(new Dimension(150,150));
bluePanel.setPreferredSize(new Dimension(150,150));
// add the panels to the tabbed pane
tabbedPane.addTab("Red Panel", redPanel);
tabbedPane.addTab("Green Panel", greenPanel);
tabbedPane.addTab("Blue Panel", bluePanel);
// finish initializing this window
setSize(500,500); // size the window to fit its components (i.e. panels in this case)
setLocationRelativeTo(null); // center this window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit application when this window is closed
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TabbedPaneDemo().setVisible(true);
}
});
}
}
And for your other question about having 16 panels in one class:
You can have panels within panel to organize things.
You can subclass JPanel and put the subclasses in their own .java files.
You can send me an email if I can be of further assistance. kaydell#yahoo.com (I like helping people with their programming and I learn from it too.)
the code is there for clearing the Frame area by clicking the sub menu(sub_menu_purchase and sub_menu_sale) of main menu.
public void clear()
{
Graphics g = getGraphics();
Dimension d = getSize();
g.setColor(Color.WHITE);
g.fillRect(0,0,d.width,d.height);
}
void sale()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblform =new JLabel("From Party : ");
lblto =new JLabel("To Party : ");
txtto=new JTextField();
txtfrom=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblto.setBounds(50,135,80,25);
txtto.setBounds(140,135,200,25);
lblform.setBounds(50,170,80,25);
txtfrom.setBounds(140,170,100,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblto);
add(lblform);
add(txtto);
add(txtfrom);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
void purchase()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblparty =new JLabel("Party Name: ");
txtparty=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblparty.setBounds(50,135,80,25);
txtparty.setBounds(140,135,200,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblparty);
add(txtparty);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
public void actionPerformed(ActionEvent event) //set up actionlistening
{
Object source=event.getSource();
if (source.equals(sub_menu_purchase))
{ clear();
purchase();
}
if (source.equals(sub_menu_sale))
{ clear();
sale();
}
}
But it is not clear the area and override to one another.
what code should I write?
There's a lot I would do differently from what you're doing, including
Don't get a component's Graphics via getGraphics(). The Graphics object thus obtained will not persist, and so it is not useful for making stable changes to a GUI's appearance.
Don't clear the GUI's graphics but rather change the view. Even if your code worked, the components would not have been removed from the GUI with your code. They would still exist and still sit on the GUI -- not good.
A CardLayout would work well for allowing you to swap a container's view, and is often used to swap JPanels, each holding its own GUI.
Avoid null layout and using setBounds(...) as this will lead to creation of GUI's that are a "witch" to upgrade and maintain and that look bad on all platforms except for one. Better to nest JPanels, each using its own simple layout, to achieve complex, beautiful and easy to maintain and improve GUI's.
Read/study the Swing tutorials as all of this is well explained there.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UglyGui2 {
private static final String SALE = "Sale";
private static final String PURCHASE = "Purchase";
private JMenuItem sub_menu_sale = new JMenuItem(SALE);
private JMenuItem sub_menu_purchase = new JMenuItem(PURCHASE);
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
public UglyGui2() {
cardPanel.add(new JLabel(), "");
cardPanel.add(createSalePanel(), SALE);
cardPanel.add(createPurchasePanel(), PURCHASE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton("Reset"));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Print"));
buttonPanel.add(new JLabel());
buttonPanel.add(new JButton("Cancel"));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
private JComponent createSalePanel() {
JPanel salePanel = new JPanel(new GridBagLayout());
salePanel.add(new JLabel("Sales"));
salePanel.add(new JTextField(10));
return salePanel;
}
private JComponent createPurchasePanel() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Purchases"));
topPanel.add(new JTextField(10));
JPanel purchasePanel = new JPanel(new BorderLayout());
purchasePanel.add(topPanel, BorderLayout.PAGE_START);
purchasePanel.add(new JScrollPane(new JTextArea(30, 60)), BorderLayout.CENTER);
return purchasePanel; }
private Component getMainPanel() {
return mainPanel;
}
private JMenuBar getJMenuBar() {
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());
}
};
sub_menu_purchase.addActionListener(aListener);
sub_menu_sale.addActionListener(aListener);
JMenu menu = new JMenu("Menu");
menu.add(sub_menu_purchase);
menu.add(sub_menu_sale);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static void createAndShowGui() {
UglyGui2 uglyGui = new UglyGui2();
JFrame frame = new JFrame("Ugly Gui Example");
frame.setJMenuBar(uglyGui.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(uglyGui.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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