I am trying to build a layout in Swing Java - java

I am trying to make an application in java, to start with i have problems in the GUI.
I have put Jpanel inside Jframe ,but i am gettingf problems when i use setMaximumSize and moreover i want to fix the size of the Jpanel, so that even if user tries to change the size of the window , jpanel remains at center.
i have tried this a solution at StackOverflow
How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?
Please guide me through.This is my first post, i dont have enough reputations to post an image .Thanks
import javax.swing.*;
import java.awt.*;
class App_Demo4 extends JFrame {
public App_Demo4()
{
JFrame frm=new JFrame("Application");
JPanel pane=new JPanel();
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(pane,BorderLayout.CENTER);
pane.setSize(400,400);
Dimension dim=new Dimension(400,400);
pane.setMinimumSize(dim);
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(pane);
box.add(Box.createVerticalGlue());
frm.add(box);
frm.setSize(500,500);
JButton dbtn1=new JButton("Download File");
pane.add(dbtn1);
JTextField txt1=new JTextField(20);
pane.add(txt1);
JButton bbtn1=new JButton("Browse");
pane.add(bbtn1);
JButton dbtn2=new JButton("Download Mail");
pane.add(dbtn2);
JTextField txt2=new JTextField(20);
pane.add(txt2);
JButton bbtn2=new JButton("Browse");
pane.add(bbtn2);
JButton cbtn1=new JButton("Compile File");
pane.add(cbtn1);
JTextField txt3=new JTextField(20);
pane.add(txt3);
JButton bbtn3=new JButton("Browse");
pane.add(bbtn3);
JButton cbtn2=new JButton("Cancel");
pane.add(cbtn2,BorderLayout.EAST);
}
public static void main(String[] args)
{
new App_Demo4();
}
}

Don't try to set the size of a panel. That is the job of the layout manager.
You need to change the layout manager of your panel. By default a JPanel uses a FlowLayout. In this case the components just flow to a new line depending on the width of the frame.
You might want to look at a GridBagLayout. See the section from the Swing tutorial on How to Use a GridBagLayout for more information and examples.
Also, make sure you add all the components to the frame BEFORE packing the frame and making the frame visible. So you basic code should be:
frame.add(....)l
frame.pack();
frame.setVisible(true);

Thats how you do it :
Hope it helps...
import javax.swing.*;
import java.awt.*;
public class App_Demo4 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public App_Demo4()
{
super("Application");
JPanel pane=new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(500,500));
GridBagLayout gl = new GridBagLayout();
pane.setLayout(gl);
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(6, 6, 6, 6);
c.gridx = 0;
c.gridy = 0;
JButton dbtn1=new JButton("Download File");
pane.add(dbtn1, c);
JTextField txt1=new JTextField(20);
c.gridx = 1;
pane.add(txt1, c);
JButton bbtn1=new JButton("Browse");
c.gridx = 2;
pane.add(bbtn1, c);
JButton dbtn2=new JButton("Download Mail");
c.gridy = 1;
c.gridx = 0;
pane.add(dbtn2, c);
JTextField txt2=new JTextField(20);
c.gridx = 1;
pane.add(txt2, c);
JButton bbtn2=new JButton("Browse");
c.gridx = 2;
pane.add(bbtn2, c);
c.gridy = 2;
c.gridx = 0;
JButton cbtn1=new JButton("Compile File");
pane.add(cbtn1, c);
JTextField txt3=new JTextField(20);
c.gridx = 1;
pane.add(txt3, c);
JButton bbtn3=new JButton("Browse");
c.gridx = 2;
pane.add(bbtn3, c);
c.gridy = 3;
c.gridx = 2;
JButton cbtn2=new JButton("Cancel");
pane.add(cbtn2,c);
this.add(pane);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new App_Demo4();
}
});
}
}

Related

GridBagLayout - GridBagConstraints not working

I'm trying to use GridBagLayout but the GridBagConstraints objects doesn't show any effect. I want a button to fill the horizontal space. Any Ideas?
static class Five extends JFrame {
public Five() {
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
JButton button = new JButton("Long-Named Button 4");
add(button, c);
setVisible(true);
}
This works, details in comments:
import java.awt.*;
import javax.swing.*;
public class Five extends JFrame {
public Five() {
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// best to do all important stuff in a panel added to the frame
JPanel gui = new JPanel(new GridBagLayout());
setContentPane(gui);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1d; // fixes the problem
JButton button = new JButton("Long-Named Button 4");
add(button, c);
pack(); // should always be done after all components are added
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new Five();
}
};
SwingUtilities.invokeLater(r);
}
}
Further tips:
There is no good case for extending JFrame in this case, just do the relevant additions etc. to an instance of a standard frame.
To make the button larger, set a large icon, large insets, or large font. To make the frame bigger, add an EmptyBorder around the gui panel.

Is it possible to build the same GridBagLayout interface but without using extra JPanel as a container?

I am using GridBagLayout to design the interface. The interface has one JTabbedPane set at north and fill both directions as I resize, and just below the JTabbedPane there are two JButtons.
What I want to achieve is putting these two buttons at east with using only GridBagLayout capabilities (without introducing an extra JPanel), but I failed to do so.
|-[tab]--------------------------|
|---------------------------------|
|---------------------------------|
|---------------------------------|
|---------------------------------|
|-------------[button][button]|
When I set the layout constraint for both buttons to WEST (not EAST). Both go west correctly!
c.anchor = GridBagConstraints.WEST;
But when I set the layout constraint for both buttons to east
c.anchor = GridBagConstraints.EAST;
One of them go to east and the other go to west!
To solve this issue I added a JPanel which hold both buttons and added this JPanel into the interface, and set its layout constraint to c.anchor = GridBagConstraints.EAST;. It works well.
But is it possible to build the same GridBagLayout interface without using an extra JPanel as a container?
The following two classes are in SSCCE format; the first one show the problem GridBagTest, and the other show the solution GridBagTest_solved that make use of extra JPanel
Problem class:
import javax.swing.*;
import java.awt.*;
public class GridBagTest extends JPanel {
JFrame frame;
JTabbedPane tabbedPane;
JPanel panel_tab;
JButton btn_previous;
JButton btn_next;
private void create_and_layout() {
this.setLayout(new GridBagLayout());
tabbedPane = new JTabbedPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 150);
}
};
panel_tab = new JPanel();
tabbedPane.addTab("Tab 1", panel_tab);
btn_previous = new JButton("previous");
btn_next = new JButton(" next ");
GridBagConstraints c;
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTH;
this.add(tabbedPane, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(2, 0, 2, 2);
this.add(btn_previous, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(2, 0, 2, 2);
this.add(btn_next, c);
}
private void initGUI() {
create_and_layout();
frame = new JFrame("GridBagTest");
frame.getContentPane().add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new GridBagTest()::initGUI);
}
}
Solution class:
import javax.swing.*;
import java.awt.*;
public class GridBagTest_solved extends JPanel {
JFrame frame;
JTabbedPane tabbedPane;
JPanel panel_tab;
JPanel panel_buttons;
JButton btn_previous;
JButton btn_next;
private void create_and_layout() {
this.setLayout(new GridBagLayout());
tabbedPane = new JTabbedPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 150);
}
};
panel_tab = new JPanel();
tabbedPane.addTab("Tab 1", panel_tab);
panel_buttons = new JPanel(new GridBagLayout());
btn_previous = new JButton("previous");
btn_next = new JButton(" next ");
GridBagConstraints c;
// Adding buttons to panel_buttons
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2, 0, 2, 2);
panel_buttons.add(btn_previous, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(2, 0, 2, 2);
panel_buttons.add(btn_next, c);
// Adding tabbedPane & panel_buttons to this (GridBagTest_solved)
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTH;
this.add(tabbedPane, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
this.add(panel_buttons, c);
}
private void initGUI() {
create_and_layout();
frame = new JFrame("GridBagTest_solved");
frame.getContentPane().add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new GridBagTest_solved()::initGUI);
}
}
If you only have the three components - the JTabbedPane and two JButtons, you should consider using a simpler layout than GridBag. Just use a BorderLayout for the main panel, placing the JTabbedPane in CENTER, and a JPanel in SOUTH that has a FlowLayout with alignment of TRAILING, then just add the two buttons to that JPanel.

How to change frame on button event Java

I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}

JScrollPane not properly stretching horizontal distance in GridBagLayout

I've seen other posts on this subject, but the solutions they found do not apply to me. I am setting a weighted value and using the c.fill = GridBagConstraints.BOTH constraints as well.
I'm including the whole GUI code I have, just in case my mistake is coming form something other than the GridBagLayout.
I want the scrollable text block on the right to expand the remaining space within the GUI and I have set all the variables that should be attributed to that and yet it still isn't working. What am I doing wrong?
My result:
import java.awt.*;
import javax.swing.*;
public class TestCode extends JFrame {
JTextArea textArea = new JTextArea ();
JComboBox <String> typeComboBox;
JTextField searchField;
JTextField fileField;
public TestCode(){
setTitle ("GUI Test");
setSize (600, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
JScrollPane scrollPane = new JScrollPane(textArea);
JButton readButton = new JButton("Read File");
JButton displayButton = new JButton("Display");
JButton searchButton = new JButton("Search");
searchField = new JTextField(10);
fileField = new JTextField(15);
typeComboBox = new JComboBox <String> ();
typeComboBox.addItem("Index");
typeComboBox.addItem("Type");
typeComboBox.addItem("Name");
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
container.setPreferredSize(new Dimension(250, 100));
JPanel filePanel = new JPanel();
filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.Y_AXIS));
filePanel.add(new JLabel("Source file", SwingConstants.LEFT));
JPanel filePanelTop = new JPanel();
filePanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));
filePanelTop.add(fileField);
JPanel filePanelBottom = new JPanel();
filePanelBottom.setLayout(new FlowLayout(FlowLayout.RIGHT));
filePanelBottom.add(readButton);
filePanelBottom.add(displayButton);
filePanel.add(filePanelTop);
filePanel.add(filePanelBottom);
filePanel.setMaximumSize(filePanel.getPreferredSize());
filePanel.setBorder(BorderFactory.createTitledBorder("Import File"));
JPanel searchPanel = new JPanel();
searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.Y_AXIS));
searchPanel.add(new JLabel("Search target", SwingConstants.LEFT));
JPanel searchPanelTop = new JPanel();
searchPanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));
searchPanelTop.add(searchField);
searchPanelTop.add(typeComboBox);
searchPanel.add(searchPanelTop);
searchPanel.add(searchButton);
searchPanel.setMaximumSize(searchPanel.getPreferredSize());
searchPanel.setBorder(BorderFactory.createTitledBorder("Search Objects"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
container.add(filePanel, c);
c.gridx = 0;
c.gridy = 1;
container.add(searchPanel, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
container.add(scrollPane, c);
add(container, BorderLayout.WEST);
validate();
} // end method toString
public static void main(String[] args){
TestCode run = new TestCode();
}
} // end class Treasure
//add(container, BorderLayout.WEST);
add(container);
The West contrains the components to their preferred width. The default is the CENTER which allows components to expand to fill the space available.
Also, the main structure of you code is wrong. You should be adding all the component to the frame first and then invoke:
frame.pack();
frame.setVisible(true);
Then there is no need for the validate().

(Java Newbie - Panel Transitions) How do I switch between panels in a frame

I have the following simple code and I don't know how to modify it so as to have 3 separate panels to switch to, one for each button:
package TouristLocations;
import javax.swing.*;
import java.awt.*;
public class buildApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setSize(400,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel title = new JLabel("Locations");
title.setFont(new Font("Serif", Font.BOLD, 40));
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
frame.add(title, c);
JButton b1 = new JButton("View Locations");
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
frame.add(b1, c);
JButton b2 = new JButton("Insert Locations");
c.gridx = 1;
c.gridy = 1;
frame.add(b2, c);
JButton b3 = new JButton("Help");
c.gridx = 2;
c.gridy = 1;
frame.add(b3, c);
TextArea text1 = new TextArea(15,40);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
frame.add(text1, c);
frame.pack();
}
}
thank you
Sounds like you should consider using JTabbedPane.
In addition to How to Use Tabbed Panes, you may want to look at CardLayout, mentioned here and here.
You should create a main container:
JPanel mainContainer = new JPanel();
//creation of each child
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
... so each button must add those panels into the main container and resize new panel size, something like this:
//for button1:
mainContainer.add(panel1);
panel1.setSize(mainContainer.getSize());
... for button2 action, you must follow the same way above.

Categories

Resources