Java Sizing JPanel & JPanel Components - java

I'm trying to build a GUI in Java Swing. I have alot of trouble sizing components. I managed to size a JPanel by setting the dimensions with setPreferredSize(), but I can't get the components within that JPanel to size properly.
This is my screen with only the JPanel visible.
When I add the button to my JPanel the following happens:
As you can see the button is taking up the whole lenght and width of my JPanel/JFrame. Why is this happening? How can I fix it?
Here is my code:
Application.java
public void start() {
ControllerObserveer observeer = new ControllerObserveer();
frame = new JFrame("-");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.add(observeer.getView(), BorderLayout.CENTER);
frame.setResizable(false);
}
ControllerObserveer.java
public class ControllerObserveer {
private ModelObserveer model;
private ViewObserveer view;
public JPanel getView(){
return this.view.p;
}
}
ViewObserveer.java
public class ViewObserveer {
public JPanel p;
public ViewObserveer(){
this.p = new JPanel(new BorderLayout(), false);
p.setPreferredSize(new Dimension(500, 500));
p.setBackground(Color.red);
JButton b = new JButton("Hello World!");
b.setPreferredSize(new Dimension(40, 40));
p.add(b);
}
}
At last I would like to ask what the diffrences are between the diffrent layouts, like BorderLayout() or BoxLayout() for example.
Thank you for your time!

Install Java WindowBuilder on Eclipse. So, you can get things done.. "but I can't get the components within that JPanel to size properly."

Related

This is my first time using swing and I'm having issues with the JPanel

I am working on a program for my school to use. It is like match.com, but for a public school. Yes there has been permission from the school to do this.
This is the first time I have ever used swing and I am having an issue with adding my JPanel to my JFrame so that I can see and use the button.
private void Framing()
{
JPanel Panel = new JPanel();
Panel.setLayout(new BorderLayout());
JFrame Frame = new JFrame("Warning");
Frame.setUndecorated(true);
JButton OK = new JButton("EXIT");
OK.addActionListener((ActionEvent event) -> {System.exit(0);});
OK.setBounds(100,100,100,100);
Panel.add(OK, BorderLayout.CENTER);
Frame.getContentPane().add(Panel, BorderLayout.CENTER);
Panel.setLocation((Frame.getWidth()-Panel.getWidth())/2,0);
Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setLocation(600, 300);
Frame.setResizable(false);
Frame.setLayout(null);
Frame.setVisible(true);
}
What is the fastest way to fix the issue with the panel not even showing up?
Any solutions are welcomed.
Since you are a new Swing programmer, I'll try to explain with below sample code. Here I have taken your code and done few changes. See my comments in the code.
With these changes, now the program works and shows a window with a big button. When user clicks the button program exits.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
public class SwingTest
{
private void Framing() //Better method name would be "showFrame()"
{
JPanel Panel = new JPanel(); //Better variable name would be "panel"
Panel.setLayout(new BorderLayout());
JFrame Frame = new JFrame("Warning"); //Better variable name would be "frame"
Frame.setUndecorated(true);
JButton OK = new JButton("EXIT"); //Better variable name would be "exitButton"
OK.addActionListener((ActionEvent event) -> {System.exit(0);});
//Not necessary. Layout manager will handle this.
//OK.setBounds(100,100,100,100);
Panel.add(OK, BorderLayout.CENTER);
Frame.getContentPane().add(Panel, BorderLayout.CENTER);
//Not necessary. Layout manager will handle this.
//Panel.setLocation((Frame.getWidth()-Panel.getWidth())/2,0);
Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setLocation(600, 300);
Frame.setResizable(false);
//This is the main problem. You should avoid this.
//Frame.setLayout(null);
Frame.setVisible(true);
}
public static void main(String[] args)
{
new SwingTest().Framing();
}
}

how can i set the size of two JPanel in one JFrame?

how can i modify the size of the panel in the JFrame
am doing a calculator, the first panel will hold the JTextField which i suppose to be small
the second panel will hold the JButtons which suppose to be bigger
JFrame frame = new JFrame(new GridLayout(2, 1));
JPanel panel1 = new JPanel();
JPanel panel2 = new JPabel();
frame.add(panel1);
frame.add(panel2);
i've been trying to make panel1 smaller than panel2 yet nothing worked!
GridLayout would not be an appropriate choice in this scenario since it ignores the preferred sizes of the components inside the container and displays them all at an equal size instead.
I'd suggest using a BorderLayout. You can find a demonstration and description of that layout manager as well as a few others in Oracle's tutorial, A Visual Guide to Layout Managers.
Here's another example using BorderLayout which might be more relevant to your problem.
import java.awt.*;
import javax.swing.*;
public class Test {
public static void main(String []args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(200, 200));
frame.setVisible(true);
}
});
}
}
Edit: The JFrame's content pane uses a BorderLayout by default, hence the absence of a call to setLayout. Source

Switching JPanels in a JFrame without CardLayout

How can I switch Panels with ScrollPanes in a Frame? I've tried many possible ways but cannot come up with a solution to.
Actually this is one of the Java Problems my professor gave me and I needed to accomplish this by not using other layouts (such as CardLayout) and I should use the null layout only. Additional classes are allowed as long as I maintain these three classes and the scroll pane.
public class MainDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
panel1 p1 = new panel1();
panel2 p2 = new panel2();
JScrollPane jsp = new JScrollPane(panel1.panel);
Container c = frame.getContentPane();
jsp.getVerticalScrollBar().setUnitIncrement(10);
c.add(jsp);
//codes for panel switching from panel1 to panel2 vice versa
frame.setDefaultCloseOperation(JFrame.exit_ON_CLOSE);
frame.setSize(1058, 600);
frame.setLocation(100, 50);
frame.setVisible(true);
}
}
---------------------------------------------
public class panel1{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
---------------------------------------------
public class panel2{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
How can I switch Panels with ScrollPanes in a Frame?
scrollPane.setViewportView( anotherPanel );

Custom JPanel objects overlap when added to JFrame

I'm trying to create a custom timer that will record cumulative time passage separated by days. I have a custom JPanel that does all of the timer work for me. I would like to have a GUI interace with this JPanel represented 7 times. However, when I add more than one custom JPanel to either a JPanel or a JFrame, they don't show up. I've tried setting the layout and setting them to everything I can think of, but nothing works.
This is the basic setup of the Panel:
public class TimerPane extends JPanel{
private static JButton button = new JButton("Start");
private static JLabel label = new JLabel("Time elapsed:");
private static JLabel tLabel = new JLabel("0:0:0");
private static JLabel title = new JLabel("Timer");
public TimerPane(){
button.addActionListener(new ButtonListener());
this.add(title);
this.add(label);
this.add(tLabel);
this.add(button);
this.setOpaque(false);
this.setPreferredSize(new Dimension(100,100));
this.setMaximumSize(new Dimension(100,100));
}
}
This is my latest attempt at getting the JPanel to display multiple times (just twice here):
public static void main(String[] args){
JFrame frame = new JFrame("Timer");
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(700,110));
panel.setLayout(new BorderLayout());
panel.add(new TimerPane(), BorderLayout.EAST);
panel.add(new TimerPane(), BorderLayout.WEST);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
The GUI that executes after this is 700x110 of which only 100x100 on the far left is used for exactly one of my TimerPane panels. I have also tried GridLayout on the same code, but then only the TimerPane in the second "spot" shows up. Any suggestions?
First of all, please remove the static from the member variables: button, label, tLabel and title. Otherwise, having them static, it means they are shared by all the TimerPane instances.
You will see 2 timer panels now.
Next, you can change the BorderLayout to a FlowLayout for instance and add several instances of TimerPane.
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(new TimerPane());
panel.add(new TimerPane());

problem in nested Jpanel over Jframe

I have a JFrame and a Jpanel over that in which various buttons are placed.so on click of a button I have called a new class which is also having containers placed in a Jpanel.so I want to show that new class panel over the main Jframe panel.How can I do that?
And if we use card layout in it then how can i use that as on click button i have called an object of a new class.
as
Card layout consider each component in a container as card and i want whole Jpanel as a card so is it possible to do that???
Can We do nesting of Jpanels in it?
Please suggest me a right way to do that?
here is SSCCE:
// this is the main class on which i want to use panel of other class
public class mymain
{
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
public mymain()
{
jframe.setLayout(borderlayout);
JMenuBar menubar = new JMenuBar();
jframe.setJMenuBar(menubar);
JButton home_button = new JButton("HOME");
menubar.add(home_button);
jframe.getContentPane().add(panel,BorderLayout.CENTER);
panel.setLayout(new GridBagLayout());
//here used containers over that frame
and call it from main()
}
here is another class to manage category is
public class manageCategory
{
JPanel panel = new JPanel();
GridBagLayout gridbglayout = new GridBagLayout();
GridBagConstraints gridbgconstraint = new GridBagConstraints();
public manageCategory()
{
panel.setLayout(new BorderLayout());
// i have again here used containers placed with grid bag layout
}
}
So now i want that as i click on home button used in mymain class then the panel that is used in manageCategory() should be displayed on the same panel.and when i again click on home button then the mymain panel get displayed.how can i do that???
I would advise you to use a CardLayout for this task.
Updated example with JPanel and "classes":
static class MainPanel extends JPanel {
public MainPanel(final Container frame) {
add(new JButton(new AbstractAction("Click to view next") {
#Override
public void actionPerformed(ActionEvent e) {
frame.add(new NextPanel(), "NextPanel");
((CardLayout) frame.getLayout()).show(frame, "NextPanel");
}
}));
}
}
static class NextPanel extends JPanel {
public NextPanel() {
add(new JLabel("Next page in the card layout"));
}
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
frame.setLayout(new CardLayout());
frame.add(new MainPanel(frame.getContentPane()), "MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
CardLayout is one of possible ways, but there are another options valid or required by most completed GUI
1) BorderLayout, because there only one JComponent can occupate decision area
someContainer.add(myPanel, BorderLayout.CENTER)
revalidate();
repaint();
2) GridBagLayout
before anything you have to get declared GridBagConstraints from myOldComponent layed by GridBagLayout
myContainer.setVisible(myOldComponent);
//or
myContainer.remove(myOldComponent);
myContainer.add(myNewComponent, gbc);
revalidate();
repaint();
You can
JFrame myFrame = new JFrame();
JPanel panel1 = new JPanel();
Panel1.setVisible(true);
myFrame.add(panel1);
JPanel panel2 = new JPanel();
Panel2.setVisible(false);
myFrame.add(panel2);
//Here you setup your panels and your actionlisteners etc and when
//you wish for your second panel to show up just run the code below.
panel1.setVisible(false);
panel2.setVisible(true);
Obviously you first have to add both panels to your Jframe. Panel1 will be at first visible, as it is the one shown by default. Panel2 must be set to be invisible in the beginning.

Categories