Button in java jframe will not resize? - java

I started java programming yesterday, and have developed this. I have run into a problem, as the button will not resize. Please help if you can and thank you in advance.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class BgPanel extends JPanel {
Image bg = new ImageIcon("C:\\Users\\********\\Pictures\\tiger.jpg").getImage();
#Override
public void paintComponent(Graphics g) {
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}
public class FrameTestBase extends JFrame {
public static void main(String args[]) {
JPanel bgPanel = new BgPanel();
bgPanel.setLayout(new BorderLayout());
final FrameTestBase t = new FrameTestBase();
ImageIcon img = new ImageIcon("C:\\Users\\********\\Pictures\\gear-icon.png");
t.setLayout(null);
t.setIconImage(img.getImage());
t.setTitle("Login");
t.setSize(600,600);
t.setLocationRelativeTo(null);
t.setContentPane(bgPanel);
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setVisible(true);
JButton registerButton = new JButton("register");
registerButton.setBounds(80, 80, 80, 80);
t.add(registerButton);
}
}

I have run into a problem, as the button will not resize. Please help
if you can and thank you in advance.
bgPanel.setLayout(new BorderLayout());
// --------- your other code
t.setLayout(null);
//--------------- your other code
t.setContentPane(bgPanel); // you are setting bgPanel which has BorderLayout
JButton registerButton = new JButton("register");
registerButton.setBounds(80, 80, 80, 80);
t.add(registerButton); // t is the JFrame, your main window
Any JFrame.add(component) will essentially add your component to the content pane of the JFrame. After setting layout to null you have added the bgPanel as content pane to the JFrame, which has BorderLayout as its layout manager. Adding your button to the content pane i.e.,bgPanel will add your registerButton with BorderLayout.Center constraint. That is why this button is expanding to the size of the screen.
As you are so eager to see an output do the following:
// registerButton.setBounds(80, 80, 80, 80); comment out this line
registerButton.setPreferedSize(new Dimension(80, 80));
t.add(registerButton, BorderLayout.PAGE_START)
Now, About using NULL Layout:
In your own example you have lost to find the reason why the Button is expanding to the window size. In near future you will see that one of your component has head but lost its tail by going outside of the window border. You will see that one of your component is going to jump over the other without no reason. You will see that you have changed a position of component with relative to another component, but it will make relation with other component. Well you will be able to find the issues wasting lost of time and get fixed by setting xxxSize, setLocation, setBounds etc but....
people can be rich in money, they can't be rich in time.
Start learning LayoutManager: Lesson: Laying Out Components Within a Container

Don't use a null layout!!!
Swing was designed to be used with layout managers. And don't forget to follow Mike's suggestion.

Try to use registerButton.setSize(new Dimension(width, height)) instead of setBounds.
Remember to replace width and height for new values
And I forget to say the same thing guys are telling you:
Don't use null layout.
The sooner you learn, the better.
Layouts are not difficult, they're actually easy.

Related

Swing MigLayout cannot grow fill column to fill container length

I am using MigLayout for a very long window.
and I wish to "push" the second and fourth column to fill all the length of the whole window, but I cannot achieve it. There's no push option in column constraint, only grow and fill.
Here's a SCCEE, as someone once suggested, whose name I already forgot:
package com.WindThunderStudio.MigLayoutTest;
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutTest extends JFrame{
private JFrame mainFrame;
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutTest(){
run();
}
public void run(){
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, 1250, 500);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.setSize(mainFrame.getSize());
p.setLayout(new MigLayout("fill","[max!, grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
mainFrame.setContentPane(p);
panel = new JPanel();
panel.setLayout(new MigLayout("fillx", "[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto);
panel.add(lblResumenAutoResult);
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial);
panel.add(lblResumenRazonSocialResult,"wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo);
panel.add(lblResumenPeriodoResult);
//poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora);
panel.add(lblResumenFechaHoraResult);
p.add(panel,"cell 0 0");
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setBounds(0, 0, 1250, 500);
getContentPane().add(mainFrame.getContentPane());
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutTest test = new MigLayoutTest();
}
});
}
}
If you run the code, you can note that the columns' width increases as its containing text's length changes. But it never fills the whole width of its container.
What's desirable, is to fix the column 0 and 2 by 15% of the whole width, and let column 1 and 3 to ocupy the rest, 35%, with the first two columns occupying the 50% size of the whole width.
Am I missing something here? I don't want to specify the width of every column, setting pre:min:max, because it is bad practice, as suggested by this post, which gets lots of vote up.
panel.setLayout(new MigLayout("fillx",
"[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]",
"[center]10[center]"));
But, if I set pref:min:max, it can fill the whole width.
First the code, then explanation. Try this:
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutTest extends JFrame {
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutTest() {
run();
}
public void run() {
panel = new JPanel();
panel.setLayout(new MigLayout("debug, fill",
"[left, 15%]10[left, 35%]10[left, 15%]10[left, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto, "sg label");
panel.add(lblResumenAutoResult, "sg value");
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial, "sg label");
panel.add(lblResumenRazonSocialResult, "sg value, wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo, "sg label");
panel.add(lblResumenPeriodoResult, "sg value");
// poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora, "sg label");
panel.add(lblResumenFechaHoraResult, "sg value");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
getContentPane().add(panel);
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
MigLayoutTest test = new MigLayoutTest();
}
}
The explanation of my changes:
Now except for simplifying the code and layout I used “debug” within the layout constraints to see what actually happens to the layout. I suggest using it anytime things go wrong with the layout - it makes MigLayout draw the borders of components and cells, thus visualizing potential problems.
I removed the unnecessary mainframe and p - if you really need it for a nested layout try to add it once you have solved the inner layout to your liking.
As to p and panel - it might be that you need here two different layouts, one nested in another, but this is the actual source of your problem. p had also its own grid layout, with
p.add(panel,"cell 0 0");
you put panel in the top left cell of the p - this is why panel was not distributed over the whole window but sat in the upper left corner.
As you see without p it positions nicely in the middle of the screen without any constant size, still showing all components, but more importantly it has 50% of the window size for the first and 50% for the last two columns. This was achieved by giving the components a “sizegroup”:
Gives the component a size group name. All components that share a
size group name will get the same BoundSize (min/preferred/max). It is
used to make sure that all components in the same size group gets the
same min/preferred/max size which is that of the largest component in
the group. An empty name "" can be used.
And it also resizes like it should!
The nested layout might also had been the root of another problem – don’t know if you didn’t notice it or it just didn’t show up on your machine, but if I tried to resize your window the panel got wider and wider (never narrower) even if I shrunk the window. At some point it got wider than the window itself and even then growed further on each resize.
Next - setting the dimensions to a constant value didn’t make sense, since after pack the layout manager starts sizing everything based on preferred sizes of the window and its content. Besides, you never know which size is your users’ screen, so any constant size could be equally bad if effectively used. Better to drive the size through the content and available runtime environment. With your code on my machine it took all available horizontal space of my two screens (2 x 1280) and did’t look pretty.
I also think that you do not need to start the frame using EventQueue.invokeLater, just create a MigLayoutTest and that’s it.
EDIT after OP's own answer
Setting the size using setBounds(0, 0, 1250, 500) before pack is not working correctly (by this I mean making the window be that size). Even in the screenshot below OP's own answer it is not 500px high. Here is what I get on Windows 7 running JDK 1.8.0_91:
The size of my screen is 1280 x 1024, the size of the programm's window is 914 x 301.
I'd suggest using one of the following:
To set it to the constant size of 1250 x 500 px move the setSize between pack and setVisible:
...
pack();
setSize(1250, 500);
I'd use setSize, setBounds doesn't make sense, since by calling setLocationRelativeTo(null) you centering the programm's window on the screen anyway, so the origin is being dismissed immediately.
To maximize horizontally and let the height be 500 px set main window's preferred size before pack:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension(screenSize.width, 500));
And to maximize horizontally and let the preferred height as it was originally:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension(screenSize.width, getPreferredSize().height));
Of course you can make the window 1250 x 500 big by setting its preferred size instead of using setSize, too.
The resize problem is not so big now, but it's still there - make the window wider, than narrow it just a little bit. You'll notice that the panel gets wider even if the window got narrowed. The problem is that panel component doesn't get big enough to fill the one column of p initially (BTW you can add the 'debug' flag to each MigLayout, also that of the panel - it will then outline all of the inner components as well).
To make it fill the parent container add it like this:
p.add(panel, "cell 0 0, grow");
Now it is the full width of p from the very beginning and resizing works as expected.
Regarding starting the JFrame using invokeLater - we start our main windows usually without it and had never had problems, since there were no interactions with Swing until the first frame was visible, yet I have just noticed that it is regarded to be the best practise - even in Oracle's tutorials. It looks like I had learned something here, too :-).
Comparision of the frame's window with and without adding with "grow"
Test scenario: start the application and resize it to be wider.
As you see in the first screenshot the component size is smaller than the column width - it looks like the component were lying behind the column size while resizing. On the second screenshot the component width remains the same as the column width at all times. As I said previously the reason might be the Java and/or operating system combination, I don't know. But obviously it behaves differently and on my machine less than optimal.
Thanks to #Tomasz Stanczak, I have solved it finally. However, I found part of what he said is relevant, and others are not. For future readers who may see this, I have to made it clearer.
The final working code is:
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutMySCCEE extends JFrame{
private JFrame mainFrame;
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutMySCCEE(){
run();
}
public void run(){
JPanel p = new JPanel();
p.setLayout(new MigLayout("debug, fill","[grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
panel = new JPanel();
panel.setLayout(new MigLayout("fillx", "[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto);
panel.add(lblResumenAutoResult);
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial);
panel.add(lblResumenRazonSocialResult,"wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo);
panel.add(lblResumenPeriodoResult);
//poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora);
panel.add(lblResumenFechaHoraResult);
p.add(panel,"cell 0 0");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setBounds(0, 0, 1250, 500);
getContentPane().add(p);
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutMySCCEE test = new MigLayoutMySCCEE();
}
});
}
}
And the window looks like:
Some notes:
The debug trick is very useful and urges me to read DOC again. I wish it can gain more attention and importance in the Quick Start page, however.
The unnecessary nesting is a problem and Tomasz make me to review the hierarchy, great! I changed the nesting part to make it clearer. But it's irrelevant.
The sizeGroup part is great idea and I decide to use it in future development as much as possible, but it's irrelevant to my case. I solved it without using it.
I have found the wider-and-wider problem after Tomasz's tip, but it is due to [max!] combined with adding the panel to the first cell of grid layout, not frame/panel nesting. I removed [max!] and changed it to [grow] and the width is not expanding anymore. I didn't touch the p.add(panel, "cell 0 0") part. As observed and by definition,
p.setLayout(new MigLayout("debug, fill","[grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
the first line of the panel has only one column, if I understand well.
EDIT after Tomasz's edit
I surely have learned more than you did :) I tried to get rid of setBounds() part and to change add(panel, "cell 0 0") to add(panel, "grow"), but I cannot see much difference, am I missing something here? Yet "grow" is almost always the better choice and desirable.
Here's 2 GIFs showing what I got: (by ScreenToGif, a light-weighted but powerful tool, especially useful for showcase)

JFrame Layout set to null issues

I am trying to learn GUI from a book I just got, but I am having tons of problems (my code is attached). When I launch this app, All I get is a minimum window that need to expand every time, and the only thing it shows is one of my radio buttons. I am obviously doing something wrong here. Can somebody please advise me?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CarPayment
{
public static void main(String[] args)
{
new CarPaymentCalc();
} // main
} // CarPayment
class CarPaymentCalc extends JFrame
{
private JLabel labelTitle, labelInterest, labelLoan;
private JTextField tfLoan, tfInterest, tfAnswer;
private ButtonGroup bgSelect;
private JRadioButton rbPmts36, rbPmts48, rbPmts60;
private JButton bClear;
public CarPaymentCalc()
{
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Centers the window
setTitle("Car Payments Calculator");
// Labels
labelTitle = new JLabel("Calculate My Car Payment");
labelTitle.setVerticalAlignment(JLabel.TOP);
add(labelTitle, JLabel.CENTER);
labelLoan = new JLabel("Loan Amount");
labelLoan.setLocation(0, 10);
add(labelLoan);
labelInterest = new JLabel("Interest");
labelInterest.setLocation(0, 45);
add(labelInterest);
// Input Fields
tfLoan = new JTextField(20);
tfLoan.setLocation(0, 25);
add(tfLoan);
tfInterest = new JTextField(5);
tfInterest.setLocation(0, 60);
add(tfInterest);
JTextArea tfAnswer = new JTextArea(50,10);
tfAnswer.setLocation(0, 110);
add(tfAnswer);
// Radio buttons
bgSelect = new ButtonGroup();
rbPmts36 = new JRadioButton();
rbPmts36.setText("36 Payments");
rbPmts36.setLocation(0, 80);
bgSelect.add(rbPmts36);
add(rbPmts36);
bgSelect.add(rbPmts48);
rbPmts48.setText("48 Payments");
rbPmts48.setLocation(150, 80);
rbPmts48 = new JRadioButton();
add(rbPmts48);
bgSelect.add(rbPmts60);
rbPmts60.setText("60 Payments");
rbPmts60.setLocation(300, 80);
rbPmts60 = new JRadioButton();
add(rbPmts60);
setLayout(null);
pack();
} // CarPaymentCalc
}
Don't use null layouts. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen.
Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work.
By looking at JavaDocs for pack...
Causes this Window to be sized to fit the preferred size and layouts
of its subcomponents. The resulting width and height of the window are
automatically enlarged if either of dimensions is less than the
minimum size as specified by the previous call to the setMinimumSize
method. If the window and/or its owner are not displayable
yet, both of them are made displayable before calculating the
preferred size. The Window is validated after its size is being
calculated.
You will note that pack relies on the layout manager API to determine the preferred viewable size of the frames content. By setting the layout manager to null, you've prevented it from been able to determine this information, so basically, it's done nothing.
If your book is telling you to use null layouts, get rid of it, it's not teaching you good habits or practices.
Take a look at Laying Out Components Within a Container for more details about layout managers and how to use them
Other problems you are having:
Calling setVisible(true); before you've finished building the UI can sometimes prevent the UI from appearing the way you intended it to. You could call revalidate on the frame, but it's simpler to just call setVisible last.
The calculation used by setLocationRelativeTo uses the frames current size, but this hasn't been set yet. Instead, you should do something like:
public CarPaymentCalc() {
//...build UI here with appropriate layout managers...
pack();
setLocationRelativeTo(null);
setVisible(true);
}
I would also discourage you from extending directly from top level containers like JFrame, apart from the fact that you're not adding any functionality to the frame per se, it prevents you from re-using the IU later.
Better to start with a JPanel and add this to whatever you want, but that's just me.

JButton not visible until mouseover

I'm creating a gui for my project. When the gui is first loaded only background is visible, so buttons are not visible, but when mouse over them, they are visible. What is the solve this problem?
public class Home extends JFrame{
//New JPanel
private JPanel home;
//Creating image url. You must be change url
ImageIcon icon = new ImageIcon("img//home1.jpeg");
//Home Class
public Home(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 960, 640);
setTitle("LoneyTunes Crush");
home = new JPanel();
home.setBorder(new EmptyBorder(5, 5, 5, 5));
home.setLayout(new BorderLayout(0, 0));
setContentPane(home);
getContentPane().setLayout(null);
JLabel background = new JLabel(new ImageIcon("img//giphy."));
getContentPane().add(background);
background.setLayout(new FlowLayout());
//Creating Buttons
JButton play = new JButton("Play");
play.setBounds(20, 20, 200, 30);
JButton setting = new JButton("Settings");
setting.setBounds(20, 60, 200, 30);
JButton exit = new JButton("Exit");
exit.setBounds(20, 100, 200, 30);
//Adding Buttons
home.add(play);
home.add(setting);
home.add(exit);
//ActionListeners
play.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
home.setVisible(false);
difficulty.setVisible(true);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(1);
}
});
validate();
}
//Background paint method
public void paint(Graphics g){
g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), null);
}
}
Main Class
public class MainClass {
public static Home pencere;
public static void main(String args[]){
pencere=new Home();
pencere.setVisible(true);
}
}
Don't paint on top-level containers like JFrame as they already carry the burden of painting all of it's components.
Instead paint on JPanel or JComponent and Override it's paintComponent method.
On top of overriding paintComponent (or in your case paint), you need to also call super.paintComponent (in your case super.paint) inside the the method (first call under the method signature), as to not break the paint chain. Failing to do so may and probably will leave you with undesired paint artifacts.
Avoid using null layouts for a number of reason. Different platform will treat them differently. They are difficult to maintain, among many other reasons. Instead use layout managers, and let them do the laying out and sizing of the components, as they were designed to do with Swing apps. Learn more at Laying out components Within a Container
Setting Home pancere as a static class member of MainClass is completely pointless. Just declare and instantiate both in the main method.
Swing apps should be run on the Event Dispatch Thread (EDT). You can do so by wrapping your the code inside your main method with a SwingUtilities.invokeLater.... See more at Initial Threads
Instead of trying to make panels visible and not visible or adding an removing panel, consider using a CardLayout which will "layer" panels, and you can navigate through them with CardLayout's methods like show(), next(), previous(). See more at How to Use CardLayout
By time of deployments, the images you are using will need to become embedded resources, and should be loaded from the class path, and not from the file system. When you pass a String to ImageIcon, you are telling the program to look in the file system, which may work in your development environment, but that's it. See the wiki tag on embedded-resource an pay close attention to the very last link that will provide you will some resources on how to use and load embedded resources if the info doesn't provide enough detail.
Problem is with
getContentPane().setLayout(null);
remove it as you have already set the layout to a Border Layout and you will see all these buttons.
Just make sure that the setvisibility of all other panels except the one which you wish to display is set to false.I too had a similar problem but i had forgotten to set visibility of one of the 10 panels to false.Problem resolved once i set it to false.
I don't know how this worked for me I just typed jf.setVisible(true); at the end after adding all the GUI codes.
public Calculator(){
jf = new JFrame("Basic Calculator");
jf.setLayout(GridBagLayout);
jf.setSize(306, 550);
jf.setLocation(530, 109);
//all the GUI things like JButton, JLabel, etc...
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Try putting validate(); method on your main frame. I think it would help you.

JPanel inside another

I have a problem with a JPanel inside another one. I don't know why, but the result is a simple square, but the dimensions aren't correct. Why is that?
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class jj extends JFrame {
private JPanel painel3;
private JPanel painel5;
private Container container;
public jj() {
container = getContentPane();
container.setLayout(null);
painel5 = new JPanel();
painel5.setBackground(Color.red);
painel5.setBounds(120, 110, 100, 120);
painel3 = new JPanel();
painel3.setBackground(Color.white);
painel3.add(painel5);
painel3.setBounds(50, 50, 290, 220);
container.add(painel3);
// frame
setSize(1000, 900);
setLocation(200, 50);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new jj();
}
}
You need to set the layout for panel3 also to null otherwise the default FlowLayout is used:
panel3.setLayout(null);
A couple of additional recommendation. Learn to use LayoutManagers. They might have a slight learning curve but it will definitely be worth it. Nice tutorial: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
Also according to the Java Standards, class names should start with a capital letter. Doing this will help others read your code better.
Even better though is to avoid use of null layouts and setBounds/setSize but rather let layout managers help you in laying out your GUI. You can read up on them here: Laying out components in a container
Set the layout of painel3 to null before adding the painel5 panel.
painel3.setLayout(null);
painel3.add(painel5);
I recommend to use LayoutManagers.

java panel with png background

i found this link.. LINK what i want is there's a JPanel that has a background and another JPanel with half the size of the first JPanel but with an image that is transparent and with a face or a ball at the middle.. :) just like the screenshot from the link.. is that possible to code in java? :) im just thinking it like for web programming. just a sort of DIV's to have that but i dont know in java.. :) sorry for bad english.. :D i have this as a background..
package waterKing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class Main extends JFrame {
MainData data = new MainData();
public static void main(String[] args) {
Main frmMain = new Main();
frmMain.setExtendedState(Frame.MAXIMIZED_BOTH);
frmMain.setVisible(true);
}
public Main() {
data.tk = getToolkit();
data.d = data.tk.getScreenSize();
data.jP = new JPanel() {
protected void paintComponent(Graphics g) {
data.e = getSize();
data.iI = new ImageIcon("images/mainBG.png").getImage();
g.drawImage(data.iI,0, 0, data.d.width, data.d.height, null);
super.paintComponent(g);
}
};
data.jP.setOpaque(false);
data.jSp = new JScrollPane(data.jP);
data.jB = new JButton("EXIT");
data.jB.setBounds(10,10,200,40);
data.jB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
data.jP.setLayout(null);
data.jP.add(data.jB);
this.setTitle("Water King Inventory System");
this.setUndecorated(true);
this.getContentPane();
this.add(data.jSp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
}
i dont know how to add another JPanel to show in the middle with this background
i dont know how to add another JPanel to show in the middle with this background
Its just like adding components to a panel. You need to use a layout manager and then the component will be positioned properly based on the rules of the layout manager. In your case you can set the layout manager of the background panel to be a BorderLayout. Then you can add a JLabel with the appropriate Icon to the center of the BorderLayout.
You will need to set the preferred size (or override the getPreferredSize() method of your panel since you add it to a scroll pane. Scrollbars will only appear when the preferred size of the panel is greater than the size of the scroll pane.
You should not be reading the image in your paintComponent() method since this method is called multiple times.
You should not be using the "screen size" to determine the width/height of the image because the frame will contain a border. You need to use the size of the panel.
Get rid of all the setBounds() code. Learn to use layout managers.
For a general purpose background panel that takes into account most of the suggestions made here check out Background Panel.

Categories