How to create this button over the other button? - java

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

Related

put two vertical JSplitPane on a frame java

I am a new java programmer and I use stackoverflow since my begin. I code a little "game", and it is a text-based game. Well, i begin a graphical interface, to case the text, and i would have this configuration
Basically, it is a double separation, with 3 horizontals elements. Actually, I have this:
and i want a separation
I have tried to put an other split pane on the top of the first one, like this:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
// topJSplitPane.setDividerLocation(400);
JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
But it gives me two sticked splitpane :-/
Can you help me please? I hope you understand my message, because I learn English. Contact me below if you want a next phase to this issue, thanks! ^^ Here is the actual graphical test java class:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
topJSplitPane.setDividerLocation(400);
// JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
// F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
You wrote in your question
I am a new java programmer and I use stackoverflow since my begin
I really think that the way to learn Swing programming is to follow a learning curve that starts with the basics and gradually progresses. Everybody has his preferred way to learn, for example by attending a course or watching a video or reading a book. Personally I prefer books. If you do too, then I can recommend a few.
You also wrote in your question
I code a little "game"
I would say that is a very ambitious project for a beginner. While I'm sure that there are people who learn best by starting off with ambitious projects, I would say they are in the minority.
That said, the key to correctly implementing your GUI is having a deep understanding of how Swing works, in particular layout managers and Component sizes as well as at what point in the code can you set those Component sizes.
The below code will initially display your desired GUI, since I understand, from your question, that that is what you are trying to accomplish now.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class WindowCapture extends WindowAdapter implements Runnable {
private JFrame frame;
private JLabel label;
private JSplitPane splitPane;
private JSplitPane topPane;
#Override // java.lang.Runnable
public void run() {
showGui();
}
#Override // java.awt.event.WindowAdapter
public void windowOpened(WindowEvent event) {
int height = event.getWindow().getHeight();
splitPane.setDividerLocation(0.7);
double high = height * 0.7;
height = (int) Math.rint(high);
high = height * 0.8;
height = (int) Math.rint(high);
label.setPreferredSize(new Dimension(event.getWindow().getWidth(), height));
}
private JTextField createBottomPane() {
JTextField textField = new JTextField(20);
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
return textField;
}
private JSplitPane createSplitPane() {
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createTopPane(), createBottomPane());
splitPane.setDividerLocation(0.4);
return splitPane;
}
private JSplitPane createTopPane() {
label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
topPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
label,
new JPanel());
topPane.setDividerLocation(0.9);
return topPane;
}
public void showGui() {
frame = new JFrame("Window Capture");
frame.addWindowListener(this);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.add(createSplitPane());
frame.setVisible(true);
}
/**
* Start here!
*/
public static void main(String[] args) {
EventQueue.invokeLater(new WindowCapture());
}
}
Here is a screen capture of the running app.

Changing JScrollPane height in Swing

I failed to change the height of JPanel or JScrollPane to make more lines to appear, I used GridLayout. It seems that, every component in it should have the same size even when I use setSize(). Should I use another layout?
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Main {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private imagePanel image;
JTextField textField = new JTextField(20);
public Main() throws IOException{
prepareGUI();
}
class imagePanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File("file.jpg"));
g.drawImage(image, 170, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException{
Main swingControlDemo = new Main();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,500);
GridLayout gridlayout = new GridLayout(4, 1);
gridlayout.setVgap(1);
mainFrame.setLayout(gridlayout);
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
JScrollPane scroller = new JScrollPane(statusLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
image = new imagePanel();
image.setLayout(new FlowLayout());
// mainFrame.add(headerLabel);
mainFrame.add(image);
mainFrame.add(controlPanel);
mainFrame.add(scroller);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
JButton okButton = new JButton("reload");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("reload");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
//controlPanel.add(cancelButton);
controlPanel.add(textField);
System.out.println("---------------------");
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "reload" )) {
statusLabel.setText(convertToMultiline("Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8\nLine9\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine"));
}
else {
statusLabel.setText("Submit Button clicked.");
}
}
}
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
}
The GUI need to look like this
I want to remove the large vertical gaps between the componets, and the jLabel should use that space
Well in your comment you say you want the label to use the space. But in your picture you show the text area with all the space. How can we answer a question when you give us conflicting requirements? Be specific and accurate when describing a problem.
In any case, the default layout of a JFrame is a BorderLayout so you would probably start with that.
Then the component that you want to grow/shrink as the frame is resized should be added to the CENTER of the frame.
Then you create a second panel to contain your other components. This panel would then be added to either the PAGE_START or PAGE_NORTH of the frame depending on your exact requirement.
The layout manager of this panel can then be whatever your want. Maybe a GridLayout, or a GridBagLayout or a vertical BoxLayout.
Read the section from the Swing tutorial on Layout Managers for more information and working examples. The key point is you create nest panels each with a different layout manager to achieve your layout.

Center panel when window resized

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.

External JPanels called from a JFrame

A while back I started a project that soon built up a shed load of code, most of the code was made up of components and their properties. All was going well until I hit an error. Off the top of head, the error was something on the line of exceeding the code limit of a constructor, roughly 65000 bytes.
This error has literally bought me and my project to halt. At the same time I have also found major problems in my understanding of SWING.
What I tried was to break my game code into logical sections, putting each section into a different class. For example, a jpanel which dealt with buying and selling would be its own .java file. Another jpanel that dealt with shipping would be in another .java file.
What I hoped to achieve was a JFrame that called each of these jpanels when the user requested it at the press of a jbutton. However, this didn't quite work as I wished, putting me in a position where I need help.
What I have done is simplified my problem by creating an example framework, hoping that somebody could point out what I need to be looking at, possibly even a solution.
I have created a JFrame which holds a panel called bg, which itself holds 2 JButtons (btn1 and btn2). In a different class file I have created a JPanel called panel1, and in another class again I have created another JPanel called panel2.
When the user opens the application they are presented with a frame and the option of two buttons, when any of these buttons are pressed I would like for either panel1 or
panel2 to open. How would this be done?
Any help would be greatly appreciated. Thanks in advance.
////////////// frame
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame implements ActionListener {
public JPanel bg;
public static JButton btn1, btn2;
public Frame(){
JFrame f = new JFrame();
f.setSize(308, 205);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
bg = new JPanel();
bg.setSize(300, 200);
bg.setLocation(0, 0);
bg.setLayout(null);
bg.setBackground(Color.black);
bg.setVisible(true);
btn1 = new JButton("open 1");
btn1.setSize(135, 30);
btn1.setLocation(10, 10);
btn1.addActionListener(this);
btn2 = new JButton("open 2");
btn2.setSize(135, 30);
btn2.setLocation(155, 10);
btn2.addActionListener(this);
bg.add(btn1);
bg.add(btn2);
f.add(bg);
}
public static void main(String[] args) {
new Frame();
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn1){
}
if (a.getSource() == btn2){
}
}
}
////////////////////// panel1
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class panel1 implements ActionListener {
public JButton btn3;
public panel1(){
JPanel a = new JPanel();
a.setSize(280, 110);
a.setLocation(155, 10);
a.setBackground(Color.red);
a.setVisible(true);
btn3 = new JButton("open bb");
btn3.setSize(100, 30);
btn3.setLocation(10, 10);
btn3.addActionListener(this);
a.add(btn3);
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn3){
}
}
}
//////////////////////////// panel2.java
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class panel2 implements ActionListener {
public JButton btn4;
public panel2(){
JPanel b = new JPanel();
b.setSize(280, 110);
b.setLocation(155, 10);
b.setBackground(Color.blue);
b.setVisible(true);
btn4 = new JButton("open");
btn4.setSize(100, 30);
btn4.setLocation(10, 10);
btn4.addActionListener(this);
b.add(btn4);
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn4){
}
}
}
You don't need to split your panels into different classes for something this simple. Try keeping everything together:
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame implements ActionListener {
public JPanel bg,panel1,panel2;
public static JButton btn1, btn2;
public Frame(){
JFrame f = new JFrame();
f.setSize(308, 205);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
bg = new JPanel();
bg.setSize(300, 200);
bg.setLocation(0, 0);
bg.setLayout(null);
bg.setBackground(Color.black);
bg.setVisible(true);
btn1 = new JButton("open 1");
btn1.setSize(135, 30);
btn1.setLocation(10, 10);
btn1.addActionListener(this);
btn2 = new JButton("open 2");
btn2.setSize(135, 30);
btn2.setLocation(155, 10);
btn2.addActionListener(this);
bg.add(btn1);
bg.add(btn2);
f.add(bg);
panel1 = new JPanel();
panel1.setSize(280, 110);
panel1.setLocation(155, 10);
panel1.setBackground(Color.red);
panel1.setVisible(false);
bg.add(panel1);
panel2 = new JPanel();
panel2.setSize(280, 110);
panel2.setLocation(155, 10);
panel2.setBackground(Color.blue);
panel2.setVisible(false);
bg.add(panel2);
}
public static void main(String[] args) {
new Frame();
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn1){
panel1.setVisible(true);panel2.setVisible(false);
}
if (a.getSource() == btn2){
panel1.setVisible(false);panel2.setVisible(true);
}
}
}

Why my textboxes not showing without maximizing GUI in java

I am trying to create small GUI with couple of textboxes. Shortest code is here:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MortgageCalculator implements ActionListener {
JTextField loanAmount, loanTerm;
JFrame jf;
public static void main(String[] args) {
// TODO Auto-generated method stub
mygui mg = new mygui();
mg.initUIPanel();
}
public void initUIPanel() {
jf = new JFrame();
jf.setTitle("my gui");
jf.setLocation(300, 400);
jf.setSize(400, 500);
jf.setVisible(true);
jf.setResizable(false);
jf.show();
JPanel panel = new JPanel();
panel.setLayout(null);
loanAmount = new JTextField(15);
loanAmount.setBounds(170, 20, 125, 20);
loanTerm = new JTextField(15);
loanTerm.setBounds(170, 60, 125, 20);
panel.add(loanAmount);
panel.add(loanTerm);
jf.add(panel, "Center");
}
}
The problem is it displays only the frame but not the txtboxes. I can see the boxes only after maximizing the frame once. If minimize it again, then still I can see them, but not at first. What am i doing wrong ?
Try to get rid of this, so JPanel will use default FlowLayout layout manager
panel.setLayout(null);
You can read more here -> layouts managers

Categories

Resources