Center panel when window resized - java

I would like to keep a panel I have created using an absolute layout in the center of my window even when the window is resized (if possible). I've come across a couple of suggestions here and [here][2] but no dice! Below is my sample code, any ideas or suggestions? I have no problems centered a single component like a JLable but I want to center a panel with many components!
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.JLabel;
public class TestPanel extends JFrame {
private JLabel lblSetupTitle;
private Border compoundBorder, outlineColorBorder, outlineBorder;
private JTextArea txtrManageData;
private JPanel childPanel;
public TestPanel()
{
setBackground(Color.white);
outlineColorBorder = BorderFactory.createLineBorder(Color.gray);
outlineBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
compoundBorder = BorderFactory.createCompoundBorder(outlineColorBorder, outlineBorder);
lblSetupTitle = new JLabel("Setup");
lblSetupTitle.setBounds(443, 288, 44, 23);
txtrManageData = new JTextArea("Text Area Text");
txtrManageData.setBounds(393, 322, 142, 61);
childPanel = new JPanel();
childPanel.setLocation(89, 38);
childPanel.setSize(921, 452);
childPanel.setBorder(compoundBorder);
setupGUIElements();
setupPanel();
}
private void setupGUIElements()
{
txtrManageData.setBackground(null);
txtrManageData.setLineWrap(true);
txtrManageData.setWrapStyleWord(true);
}
private void setupPanel()
{
getContentPane().setLayout(new GridBagLayout()); // set layout of parent panel to GridBagLayout
childPanel.setLayout(null); // set layout of child panel to AbsoluteLayout
childPanel.add(lblSetupTitle);
childPanel.add(txtrManageData);
getContentPane().add(childPanel, new GridBagConstraints());
this.setSize(1020, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestPanel ex = new TestPanel();
ex.setVisible(true);
}
});
}
}
EDIT: Any tips, links, guidance on creating something like this

I'd nest layouts.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class ThreeButtonTextFieldCombo {
private JPanel ui = null;
ThreeButtonTextFieldCombo() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new TitledBorder("Parent Panel"));
JPanel controls = new JPanel(new GridLayout(1,0,10,10));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
for (int ii=1; ii<4; ii++) {
addLabelAndField(controls, "String " + ii);
}
}
public JComponent getUI() {
return ui;
}
private void addLabelAndField(JPanel panel, String text) {
JPanel controls = new JPanel(new BorderLayout(3, 3));
controls.setBorder(new EmptyBorder(20,20,20,20));
JLabel l = new JLabel(text);
controls.add(l, BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(text, 2, 8);
controls.add(new JScrollPane(ta));
panel.add(controls);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Three Button/Text Field Combo");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
ThreeButtonTextFieldCombo tbtfc =
new ThreeButtonTextFieldCombo();
f.setContentPane(tbtfc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

The first problem with your code is that you are adding your child panel using an empty instantiation of GridBagConstraints. I have never seen it used like that before.
getContentPane().add(childPanel, new GridBagConstraints());
Do not set any layout to content pane and just add it like this :
getContentPane().add(childPanel);
Now if you run it you will get the two components in the middle, where you defined them using the setBounds(..) method.
Like almost everyone commenting on your question, you should not use null layout, and use some other layout instead. I would use a GridBagLayout to organise the three buttons and three textfields in your diagram. You could then setBounds(..) on your child panel.
If you really must use absolute layout then you will have to do a bit of maths.
If your first label is like this :
labell1.setBounds(443, 288, 44, 23);
then your second label should be something like this :
labell2.setBounds(443 + someXDisplacement, 288, 44, 23);
..and third :
labell3.setBounds(443 + (someXDisplacement x 2), 288, 44, 23);
You get the picture.

Related

How to refresh JInternalFrame or JPanel form on button click where JPanel is a separate class and used in JInternalFrame

Iam trying to build a desktop application with multiple screens inside one single JFrame.
So each button click event will take us to the separate screen with refreshed components in the screen. So far this approach is working for me but the problem I am facing is even after using ".dispose(), .repaint(), .revalidate(), .invalidate()" functions. JInternalFrame or Jpanel seems to not refresh its components.
Which works something like below gif.
Tabbed Style
I do know JtabbedPane exists but for my method JtabbedPane is not viable.
Below I am posting minified code by replicating the problem I am facing.
MainMenu.Java(file with Main Class)
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
public class MainMenu extends JFrame {
private JPanel contentPane;
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();
}
}
});
}
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 522);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 807, 63);
contentPane.add(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
JButton Tab1 = new JButton("Tab1");
panel.add(Tab1);
JButton Tab2 = new JButton("Tab2");
panel.add(Tab2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 88, 807, 387);
contentPane.add(scrollPane);
JInternalFrame internalFrame1 = new JInternalFrame();
JInternalFrame internalFrame2 = new JInternalFrame();
Tab1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel1 panel1 = new Panel1();
if(internalFrame1 !=null) {
internalFrame1.dispose();
panel1.invalidate();
panel1.revalidate();
panel1.repaint();
}
internalFrame1.setTitle("Panel 1");
scrollPane.setViewportView(internalFrame1);
internalFrame1.getContentPane().add(panel1);
internalFrame1.setVisible(true);
}
});
Tab2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel2 panel2 = new Panel2();
if(internalFrame2 !=null) {
internalFrame2.dispose();
panel2.invalidate();
panel2.revalidate();
panel2.repaint();
}
internalFrame2.setTitle("Panel 2");
scrollPane.setViewportView(internalFrame2);
internalFrame2.getContentPane().add(panel2);
internalFrame2.setVisible(true);
}
});
}
}
and the corresponding Jpanel class files where JInternal Frames
Panel1.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel1 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel1() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Example Button");
btnNewButton.setBounds(10, 156, 430, 21);
add(btnNewButton);
}
}
Panel2.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel2 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel2() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button2");
btnNewButton.setBounds(21, 157, 419, 21);
add(btnNewButton);
}
}
P.S: This is my first time asking question in Stackoverflow so forgive me and if possible guide me if i miss anything
Thank you :)
Edit:
The problem I am facing is on the surface it looks like the Jpanel has been refreshed but the components like JtextField Still hides the previously written text in it and only show the text when i click on that JTextField
Below I am Attaching another gif which show highlights the issue. I have highlighted the part where I am facing issue.
Issue I am Facing
The dispose() method does not remove components so you keep adding components to the internal frame when you use the following:
internalFrame1.getContentPane().add(panel1);
Instead you might do something like:
Container contentPane = internalFrame1.getContentPane();
contentPane.removeAll();
contentPane.add( panel1 );
contentPane.revalidate();
contentPane.repaint();
You can use the JPanels in the Jframes and then use the CardLayout to change the panel ( which could than act like the different screens )

How to create this button over the other button?

As the title, I want to create two buttons in java swing and these two buttons can overlap each other (as image). I searched the internet but I could not find it.
Thanks so much
You can simply do this by setting the JFrame layout to Absolute Layout, and adding a JButton on top of another JButton. Make sure the small button is on top of the other button in the navigator.
You can use an OverlayLayout here.
An SSCCE (with comments inside) would be:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
public class OverlayLayoutExample extends JFrame {
JPanel overlayoutPanel;
JButton jButton2, jButton1;
public OverlayLayoutExample() {
overlayoutPanel = new JPanel() {
#Override
public boolean isOptimizedDrawingEnabled() {
//Required to have always visible both components
return false;
}
};
OverlayLayout overlay = new OverlayLayout(overlayoutPanel);
overlayoutPanel.setLayout(overlay);
jButton1 = new JButton("jButton");
Dimension d1 = new Dimension(350, 100);
jButton1.setMaximumSize(d1);
jButton1.setAlignmentX(0.7f); //Some X-Y values, play with them
jButton1.setAlignmentY(0.65f); //Some X-Y values, play with them
jButton2 = new JButton("jButton2");
Dimension d2 = new Dimension(100, 25);
jButton2.setMaximumSize(d2);
jButton2.setAlignmentX(0.01f); //Some X-Y values, play with them
jButton2.setAlignmentY(0.01f); //Some X-Y values, play with them
overlayoutPanel.add(jButton2); //First the top component
overlayoutPanel.add(jButton1); //Then the above component
getContentPane().add(overlayoutPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> new OverlayLayoutExample().setVisible(true));
}
}
More about isOptimizedDrawingEnabled() can be found here.
Preview:
You can do this using the layered pane of JFrame like this:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class ButtonOnTop
{
public static void main(String[] args)
{
JButton button1 = new JButton("jButton1");
button1.setBounds(30, 50, 260, 160);
JButton button2 = new JButton("jButton2");
button2.setBounds(150, 150, 100, 40);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane layeredPane = f.getLayeredPane();
layeredPane.add(button1, Integer.valueOf(0));
layeredPane.add(button2, Integer.valueOf(1));
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}

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);
}
}

Swing: create a CompoundBorder with 3 borders?

I am creating a JFrame object with some JPanels next to each other side by side.
I want the JPanels to have a 15px margin, etched border, and 15px padding. At first I thought that this would be something really intuitive just like the HTML box model, so I tried to create CompoundBorder inside a CompoundBorder but that wouldn't work.
Here's my code:
import java.awt.Dimension;
import javax.swing.*;
public class StackOverFlowExample extends JFrame {
public static void main() {
stackOverFlowExample window = new stackOverFlowExample();
window.setVisible(true);
}
public StackOverFlowExample() {
// create buttons
JButton foo = new JButton("foo");
JButton bar = new JButton("bar");
JButton foo2 = new JButton("foo2");
JButton bar2 = new JButton("bar2");
// create panels and add buttons to them
JPanel left = new JPanel();
left.setBorder(BorderFactory.createEtchedBorder());
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.add(foo);
left.add(bar);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createEtchedBorder());
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.add(foo2);
right.add(bar2);
// add panels to frame
this.getContentPane().setLayout(new BoxLayout(
getContentPane(), BoxLayout.LINE_AXIS));
this.getContentPane().add(left);
this.getContentPane().add(right);
// finalize layout
this.setPreferredSize(new Dimension(150,150));
this.pack();
this.setVisible(true);
}
}
I'm aware that I could have just used GridBagConstraints or JButton.setMargin() to create the padding, and then use CompoundBorder to create the etched border with an empty border. What if I don't want to make my code look messy with those techniques though?
I'm not sure what problems you might be having, as you've not supplied an example of what you've tried, but the basic process would be to...
Create the inner border requirements (EtchedBorder wrapping a EmptyBorder), for example, new CompoundBorder(emptyBorder, etchedBorder)
Create the outer border requirements (EmptyBorder wrapping the inner compound border), for example, new CompoundBorder(inner, emptyBorder);
Apply this outer border to the component...
As an example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
EmptyBorder emptyBorder = new EmptyBorder(15, 15, 15, 15);
EtchedBorder etchedBorder = new EtchedBorder();
CompoundBorder inner = new CompoundBorder(emptyBorder, etchedBorder);
CompoundBorder outter = new CompoundBorder(inner, emptyBorder);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(outter);
panel.add(new JButton("Hello"));
add(panel);
}
}
}
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class ThreePartBorder {
public static void main(String[] args) {
final BufferedImage bi = new BufferedImage(
400, 100, BufferedImage.TYPE_INT_RGB);
Runnable r = new Runnable() {
#Override
public void run() {
JLabel l = new JLabel(new ImageIcon(bi));
Border twoPartBorder = new CompoundBorder(
new EmptyBorder(15, 15, 15, 15),
new EtchedBorder());
Border threePartBorder = new CompoundBorder(
twoPartBorder,
new EmptyBorder(15, 15, 15, 15));
l.setBorder(threePartBorder);
JFrame f = new JFrame("Three Part Border");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(l);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
I came back and just realized I asked a dumb question haha. Both answers above are very helpful and helped me solve the problem so I accepted one of them. Here's my solution after reading the two answers...
left.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(10,10,10,10), // margin
BorderFactory.createEtchedBorder() // border
),
BorderFactory.createEmptyBorder(50,50,50,50) // padding
));
right.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(10,10,10,10), // margin
BorderFactory.createCompoundBorder(
BorderFactory.createEtchedBorder(), // border
BorderFactory.createEmptyBorder(50,50,50,50) // padding
)
));

adding a jpanel into a jpanel in java

I have a Jpanel named mainPanel and another class named MyPanel that extends JPanel. I want to add MyPanel into mainPanel. I did this code and getting no result .
This is my Main class that holds mainPanel:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame {
private JPanel contentPane;
private final JPanel mainPanel = new JPanel();
/**
* 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() {
inItGUI();
}
private void inItGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 662, 417);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
mainPanel.setBounds(25, 11, 611, 341);
contentPane.add(mainPanel);
mainPanel.setLayout(null);
mainPanel.add(new MyPanel());// **Here i added MyPanel**
mainPanel.revalidate();
repaint();
}
}
and this is my MyPanel class that has beeb added to mainPanel earlier:
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyPanel extends JPanel {
private final JButton btnNewButton = new JButton("New button");
private final JButton btnNewButton_1 = new JButton("New button");
public MyPanel() {
inItGUI();
}
private void inItGUI() {
setLayout(null);
btnNewButton.setBounds(60, 49, 106, 43);
add(btnNewButton);
btnNewButton_1.setBounds(189, 49, 89, 43);
add(btnNewButton_1);
}
}
Welcome to one of the wonderful pitfalls of null layout managers
If you remove the layout manager, you remove any chance of your components from being automatically size and positioned.
Basically what's happening is that MyPanel is being added to mainPanel and position 0x0 with a size of 0x0, so nothing is begin displayed.
The real solution is use an appropriate layout manager
Don't fool your self. Managing the position and size of components, especially the relationship between the components, in the field of modern computer systems is a complex one. You have to be able to take into account how each component is rendered based on the font, DPI, orientation, etc... of the current system, then take into account how that might effect other components that share the same container...You also have to monitor for changes in the hierarchy of components that you are attached to...
This is the job that layout managers provide...Swing is designed around the use of layout managers and you should have a VERY good reason to ignore them...IMHO

Categories

Resources