So I am trying to learn how to use card layout and in this sample code I would like to change the size of the frame to a certain size but using setSize does not work.
the following also does not work in the when added to createAndShowGui() function
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setPreferredSize(new Dimension(500,200));
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainGui2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private WelcomePanel welcomePanel = new WelcomePanel(this);
private HomePanel homePanel = new HomePanel();
public MainGui2() {
setLayout(cardLayout);
add(welcomePanel, WelcomePanel.NAME);
add(homePanel, HomePanel.NAME);
}
public void showCard(String name) {
cardLayout.show(this, name);
}
private static void createAndShowGui() {
MainGui2 mainPanel = new MainGui2();
JFrame frame = new JFrame("MainGui2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
//frame.pack();
frame.setSize(550, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class WelcomePanel extends JPanel {
public static final String NAME = "welcome panel";
private MainGui2 mainGui2;
public WelcomePanel(final MainGui2 mainGui2) {
this.mainGui2 = mainGui2;
add(new JLabel(NAME));
add(new JButton(new AbstractAction("Logon") {
#Override
public void actionPerformed(ActionEvent e) {
mainGui2.showCard(HomePanel.NAME);
}
}));
}
}
class HomePanel extends JPanel {
public static final String NAME = "home panel";
public HomePanel() {
add(new JLabel(NAME));
}
}
I would like to change the size of the frame to a certain size
Don't try to hard code frame sizes.
If you want extra space around the panels then in the constructor of your MainGui2 class you can add:
setBorder( new EmptyBorder(50, 50, 50, 50) );
This will adjust the preferred size of the panel and this size will now be taken into account when the pack() method is used.
Related
I am trying to do when clicked button from form1 open form2. Its sounds very simple but i coudnt find any way to do this.I am using java intellij.
When i use netbeans and swing i was doing this with :
"Form2 form2=new Form2();
form2.setVisible(true);
dispose(); "
Form1(Main):
public class Main {
private JButton b_show;
private JButton b_Add;
private JPanel jp_main;
public Main() {
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
form2(Show):
public class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
Show show=new Show();
geriButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Show().jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
is any one can help me ?
when click b_show open form2(Show).
Here is an mcve demonstrating it
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
private final JButton b_show;
private final JPanel jp_main;
public Main() {
jp_main = new JPanel();
b_show = new JButton("Show");
b_show.addActionListener(actionEvent -> {
new Show();
});
jp_main.add(b_show);
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
createAndShowGui();
}
void createAndShowGui(){
JFrame frame=new JFrame();
frame.setLocationRelativeTo(null);
jpanelmain = new JPanel();
b_back = new JButton("Back");
jpanelmain.add(b_back);
frame.setContentPane(jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
However, please read The Use of Multiple JFrames: Good or Bad Practice?
The best way to do this would be using JDialogs. When actionPerformed() at 'Form1' is called, you would instantiate a new JDialog and set him visible. Here is an example:
public class Show extends JDialog {
private JButton b_back;
public JPanel jpanelmain;
public Show(Frame owner, boolean modal) {
super(owner, modal);
}
//method that creates the GUI
}
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
Show show = new Show(JOptionPane.getFrameForComponent(this), true);
show.setVisible(true);
}
});
Finally, when you want to close the dialog, implement an actionPerformed() in it, and call the dispose() method
am trying to add a button to Jframe from other class but it does not work
public class ShowMain {
public static void main(String[] args) throws Throwable {
//My JFrame
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setLayout(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.GRAY);
}
My other Class
public class Commands {
public static void main(String[] args) throws Throwable {
//JButtons
JButton button1 = new JButton();
button1.setText("");
button1.setBounds(120, 350, 400, 20);
button1.setVisible(true);
}
frame.add(button1) is not working
You've got all your code within two static main methods, meaning that the two classes can hardly interact at all. I suggest that you create true OOP-compliant classes, with instance fields ("state"), instance methods ("behavior"), and that you have one class call the method of another if you wish to change its state. For instance, if the Commands class is to add a JButton, then give your ShowMain class a method for this: public void addCommandButton(JButton button).
Having said this, I wouldn't do this at all if this were my code, but rather would follow a more MVC or "Model-View-Controller" program structure, where one set of classes would represent the program logic, another the user interactions (the listeners) and a 3rd set of classes for the GUI or "view".
For example, run this code that shows how to connect classes without them knowing about the other class (loose coupling):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ShowMain {
private static void createAndShowGui() {
MainPanel mainPanel = new MainPanel();
JScrollPane scrollPane = new JScrollPane(mainPanel);
CreateActionPanel actionPanel = new CreateActionPanel();
new Controller(actionPanel, mainPanel);
JFrame frame = new JFrame("ShowMain");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(actionPanel, BorderLayout.PAGE_START);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MainPanel extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 80;
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
public MainPanel() {
setBorder(BorderFactory.createTitledBorder("Main Panel"));
}
public void addButtonAction(Action action) {
add(new JButton(action));
// so the button will be displayed properly
revalidate();
repaint();
}
}
class Controller {
public Controller(final CreateActionPanel actionPanel, final MainPanel mainPanel) {
actionPanel.addPropertyChangeListener(CreateActionPanel.ACTION_NAME, pcEvt -> {
mainPanel.addButtonAction(new AbstractAction((String) pcEvt.getNewValue()) {
{
int mnemonic = (int) pcEvt.getNewValue().toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
System.out.printf("Button %s pressed!%n", evt.getActionCommand());
}
});
});
}
}
class CreateActionPanel extends JPanel {
public static final String ACTION_NAME = "action name";
private JTextField actionNameField = new JTextField(10);
public CreateActionPanel() {
actionNameField.addActionListener((e -> {
String text = actionNameField.getText();
firePropertyChange(ACTION_NAME, null, text);
actionNameField.selectAll();
}));
add(new JLabel("Button Text to Add:"));
add(actionNameField);
}
}
i want to add panel from "newWork" class on pressing of "drop" button in "menuPan" class.
i cant add panel.
simply how to add Panel from different class on pressing button.
here are the three different classes .
MainClass :-
public class userFrame extends JFrame{
public void Frame()
{
setTitle("TEST CASE");
setSize(900,670);
add(new MenuPan(),BorderLayout.NORTH);
add(new WorkPan(),BorderLayout.CENTER);
setLocationRelativeTo(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] args){
userFrame u =new userFrame();
u.Frame();
}
}
MenuPan
public class MenuPan extends JPanel implements ActionListener{
WorkPan work=new WorkPan();
JButton view;
public menuPan() {
setBackground(Color.white);
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
setLayout(new FlowLayout(1, 15, 10));
view=new JButton(" Registered Courses ");
view.addActionListener(this);
add(view);
}
#Override
public void actionPerformed(ActionEvent e) {
work.TaskPannel();
}
}
WorkPAN class :-
class WorkPan extends JPanel{
JPanel work=new JPanel();
public WorkPan() {
setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout(40, 50));
}
void TaskPannel() {
System.out.println("here");
add(new NewWork(),BorderLayout.CENTER);// adds NewWork panel
}
}
NewWork Class
class NewWork extends JPanel{
public NewWork(){
setBackground(Color.red);
}
}
One issue -- you create one workPan (which should be renamed WorkPan), change its state in your ActionListener, but never add it to your GUI. So you appear to be changing the state of a non-displayed GUI component, and so it would make sense that nothing will show in the GUI.
Suggestions:
Be sure to create only one WorkPan reference,
Be sure to display this single reference in the GUI
Be sure that your ActionListener calls the appropriate method on the same reference.
Side recommendation:
Learn and follow Java naming conventions so you others can more easily understand and follow your code.
To swap JPanels within a GUI, I strongly advise you to use a CardLayout rather than adding and removing components manually as you're currently doing. Please check out the CardLayout Tutorial.
And my solution does work, but you also must call revalidate and repaint to get the GUI to layout the new component and repaint it. Note additions and changes as marked by the \\ !! comment
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooWork {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
userFrame.main(args);
});
}
}
class NewWork extends JPanel {
public NewWork() {
setBackground(Color.red);
}
}
class WorkPan extends JPanel {
JPanel work = new JPanel();
public WorkPan() {
setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout(40, 50));
}
void TaskPannel() {
System.out.println("here");
add(new NewWork(), BorderLayout.CENTER);// adds NewWork panel
// !!
revalidate();
repaint();
// !!
}
}
class MenuPan extends JPanel implements ActionListener {
// !! WorkPan work = new WorkPan();
WorkPan work; // !!
JButton view; // !!
// !!
public MenuPan(WorkPan workPan) { // references are key
// !!
this.work = workPan; // set the reference!
// !!
setBackground(Color.white);
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
setLayout(new FlowLayout(1, 15, 10));
view = new JButton(" Registered Courses ");
view.addActionListener(this);
add(view);
}
#Override
public void actionPerformed(ActionEvent e) {
work.TaskPannel();
}
}
class userFrame extends JFrame {
public void Frame() {
setTitle("TEST CASE");
setSize(900, 670);
// !!
WorkPan workPan = new WorkPan();
MenuPan menuPan = new MenuPan(workPan);
// !!
// !!
// add(new MenuPan(), BorderLayout.NORTH);
// add(new WorkPan(), BorderLayout.CENTER);
add(menuPan, BorderLayout.NORTH);
add(workPan, BorderLayout.CENTER);
// !!
setLocationRelativeTo(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
userFrame u = new userFrame();
u.Frame();
}
}
But again, cleaner is to use a CardLayout to help with the swapping:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class SwapStuff {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
SwapMainPanel mainPanel = new SwapMainPanel();
JFrame frame = new JFrame("SwapStuff");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class SwapMainPanel extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private ButtonPanel buttonPanel = new ButtonPanel(this); // pass the reference
private WorkPanel workPanel = new WorkPanel();
private ViewPanel viewPanel = new ViewPanel();
public SwapMainPanel() {
cardPanel.add(workPanel, workPanel.getClass().getName());
cardPanel.add(viewPanel, viewPanel.getClass().getName());
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.PAGE_START);
add(cardPanel, BorderLayout.CENTER);
}
// one possible way to swap "cards"
public void nextCard() {
cardLayout.next(cardPanel);
}
}
class ButtonPanel extends JPanel {
private SwapMainPanel mainPanel;
public ButtonPanel(SwapMainPanel mainPanel) {
this.mainPanel = mainPanel; // set the reference!
add(new JButton(new SwapAction("Swap Panels", KeyEvent.VK_S)));
}
private class SwapAction extends AbstractAction {
public SwapAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.nextCard();
}
}
}
class WorkPanel extends JPanel {
public WorkPanel() {
setBorder(BorderFactory.createTitledBorder("Work Panel"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 400);
}
}
class ViewPanel extends JPanel {
public ViewPanel() {
setBorder(BorderFactory.createTitledBorder("View Panel"));
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 400);
}
}
I try to buid JPanels in a separate class to invoke them separately and add different items on it. Please can you tell me what i am doing wrong?
MyFrame.java
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
public MyFrame() {
setTitle("MyFrame");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
JButton testButton = new JButton("Test");
panel.add(testButton);
}
}
MyPanel.java
import javax.swing.*;
import java.awt.*;
class MyPanel extends JPanel {
public MyPanel() {
this.setOpaque(true);
this.setVisible(true);
}
}
You're not adding your panel variable to your JFrame's contentPane.
Add:
public MyFrame() {
setTitle("MyFrame");
// setSize(300, 200); // let's avoid this
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
JButton testButton = new JButton("Test");
panel.add(testButton);
add(panel); // *** here
pack(); // this tells the layout managers to do their thing
setLocationRelativeTo(null);
setVisible(true);
}
As a side note:
public MyPanel() {
this.setOpaque(true);
this.setVisible(true);
}
JPanels are opaque and visible by default, so your method calls within the MyPanel constructor do nothing useful.
Side note 2: I rarely if ever extend JFrame or any other top level window (with the exception of JApplet if I'm forced to use one of these), since I rarely change the innate behavior of the window. Better I think to create my top level windows (i.e., my JFrames) when needed.
Side note 3: Always strive to start your Swing GUI's on the Swing event thread. So do...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
});
}
Edit
You ask:
You wrote lets avoid setting the size.. can you tell me how i can pack it but set a minimum frame size?
I like to override the JPanel's getPreferredSize() method, and have it return a Dimension that makes sense.
For example, you could do something like this to be sure that your GUI is at lest PREF_W by PREF_H in size:
import java.awt.Dimension;
import javax.swing.*;
public class ShowGetPreferredSize extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int w = Math.max(superSize.width, PREF_W);
int h = Math.max(superSize.height, PREF_H);
return new Dimension(w, h);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ShowGetPreferredSize");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new ShowGetPreferredSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I made a 840 by 400 frame and added a text field. By default, the java app shrinked only to the size of the text field. I want it fixed to the respective size.
I tried setResizable(false), setExtendedState(), setBounds() with no avail.
Best to use a JPanel as your contentPane or add it to the contentPane, and to override its getPreferredSize() method and then usepack()` on the JFrame. For example:
import java.awt.Dimension;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyPanel extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
public MyPanel() {
//...
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("My GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(myPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
One advantage of this is that other classes cannot change MyPanel's size via setSize(...) or setPreferredSize(...).
Try
setPreferredSize(new Dimension(840,400));
If you named your frame you can do
name.setPreferredSize(new Dimension(840,400));