The app does not resize its component - java

I have this app, but, when I resize the window, the element JTextArea inside, it doesn't resize with the window. Why?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleGUI {
private JTextArea text_area;
private JScrollPane scroll_bar;
private JFrame frame;
private JPanel panel;
public ExampleGUI(){
frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_area = new JTextArea();
scroll_bar = new JScrollPane(text_area);
panel = new JPanel();
panel.add(scroll_bar);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){public void run(){new ExampleGUI();}});
}
}

You need to set your GridBagConstraint x and y weights (weightx and weighty -- the 5th and 6th parameters in the GridBagConstraint constructor) to a positive value other than 0.0. You should read tutorials on GridBagLayout if you're going to use it as it is fairly complex. Some have had great success nesting simpler layouts or using 3rd party layouts such as MigLayout.

Your frame layout is a FlowLayout. This does not resize children. From the docs:
A flow layout lets each component assume its natural (preferred) size.
You will be better off using a BorderLayout and putting the pane in the CENTER.
Replace this:
frame.setLayout(new FlowLayout());
frame.add(pane);
with this:
frame.setLayout(new BorderLayout());
frame.add(pane, BorderLayout.CENTER);
Also, as Hovercraft points out, if you need the individual components to resize when the pane resizes, then you need to have non-zero weights in the GridBagConstraints.

This takes into account the advice of Hovercraft Full Of Eels & Ted Hopp with a few other tweaks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Collection;
public class AziendaGUI implements ActionListener {
private JButton view_list;
private JButton save_list;
private JTextArea text_area;
private JScrollPane scrollpane;
private JPanel pane;
private JFrame frame;
private GridBagLayout grid;
public AziendaGUI() {
frame = new JFrame("Immobiliari s.p.a");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
view_list = new JButton("View Property");
view_list.setActionCommand("view_list");
view_list.addActionListener(this);
save_list = new JButton("Save List");
save_list.setActionCommand("save_list");
save_list.addActionListener(this);
text_area = new JTextArea(10,22);
text_area.setEditable(false);
scrollpane = new JScrollPane(text_area);
grid = new GridBagLayout();
pane = new JPanel();
pane.setLayout(grid);
/* Set Constraints view_list button */
grid.setConstraints(view_list, new GridBagConstraints(0,0,1,1,0.0,0.0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(view_list);
/* Set Constraints save_list button */
grid.setConstraints(save_list,new GridBagConstraints(1,0,1,1,0.1,0.1,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(save_list);
frame.add(scrollpane);
frame.add(pane, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
private void store(){
String file_name = JOptionPane.showInputDialog("Inserisci il nome del file");
}
#Override
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("view_list")){
}
if(s.equals("save_list")){
store();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){#Override
public void run(){new AziendaGUI();}});
}
}

Related

Dynamically changing the size of JFrame when exposed to different screen resolutions

So for a school project I made a grade book in java. When creating the gui I used hardcoded values in the setBounds() methods. Now this worked when I had a 1024×768 screen resolution it looked alright, but when I got a new laptop and it had a 4k screen it looked super small when I ran the program.
So my question would be is there a way to dynamically change the size of the Jframe and all of the associated objects on the frame so it matches the resolution of the screen?
I know that you can get the screen resolution from this
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
but I do not know what would be the best way to do this.
Taking your approach as example and taking this answer and this tutorial as base, here you have the clues:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
public class Q1 extends JFrame {
public static void main(String[] args) {
Q1 frame = new Q1();
frame.setSize(300, 300);
frame.setMinimumSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public Q1() {
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
#Override
public void validate() {
resize();
super.validate();
};
private void resize() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
System.out.println(width + "," + height);
}
}
This will print the size of the screen when your resize the frame, so you just need to add an if/else in the resize method to make frame bigger
OUTPUT
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized
A layout manager is an object that implements the LayoutManager
interface* and determines the size and position of the components
within a container. Although components can provide size and alignment
hints, a container's layout manager has the final say on the size and
position of the components within the container.
See the example I found using layout managers.Hope you get some idea.THe original author is here Set a layout manager like BorderLayout and then define more specifically, where your panel should go: like
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.See below example for full usage:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLayoutManagers {
private JPanel northFlowLayoutPanel;
private JPanel southBorderLayoutPanel;
private JPanel centerGridBagLayoutPanel;
private JPanel westBoxLayoutPanel;
private JPanel eastGridLayoutPanel;
private final JButton northButton = new JButton("North Button");
private final JButton southButton = new JButton("South Button");
private final JButton centerButton = new JButton("Center Button");
private final JButton eastButton = new JButton("East Button");
private final JButton westButton = new JButton("West Button");
public TestLayoutManagers() {
northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
southBorderLayoutPanel = new JPanel(new BorderLayout());
centerGridBagLayoutPanel = new JPanel(new GridBagLayout());
eastGridLayoutPanel = new JPanel(new GridLayout(1, 1));
Box box = Box.createHorizontalBox();
westBoxLayoutPanel = new JPanel();
northFlowLayoutPanel.add(northButton);
northFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Flow Layout"));
southBorderLayoutPanel.add(southButton);
southBorderLayoutPanel.setBorder(BorderFactory.createTitledBorder("Border Layout"));
centerGridBagLayoutPanel.add(centerButton);
centerGridBagLayoutPanel.setBorder(BorderFactory.createTitledBorder("GridBag Layout"));
eastGridLayoutPanel.add(eastButton);
eastGridLayoutPanel.setBorder(BorderFactory.createTitledBorder("Grid Layout"));
box.add(westButton);
westBoxLayoutPanel.add(box);
westBoxLayoutPanel.setBorder(BorderFactory.createTitledBorder("Box Layout"));
JFrame frame = new JFrame("Test Layout Managers");
frame.setLayout(new BorderLayout()); // This is the deafault layout
frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
frame.add(southBorderLayoutPanel, BorderLayout.PAGE_END);
frame.add(centerGridBagLayoutPanel, BorderLayout.CENTER);
frame.add(eastGridLayoutPanel, BorderLayout.LINE_END);
frame.add(westBoxLayoutPanel, BorderLayout.LINE_START);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestLayoutManagers testLayoutManagers
= new TestLayoutManagers();
}
});
}
}

How to add panels in a JFrame using Swing

Components are not displayed in my JFrame using Swing.
Actually my aim is:
Add Frame
In the frame add panel
Panel cantains 3 buttons
But it didn't show.
Here is my code
public class Panels
{
JFrame frame;
JPanel panel;
private JButton addButton;
private JButton modifyButton;
private JButton deleteButton;
Panels()
{
initGUI();
launchFrame();
}
public void initGUI()
{
frame = new JFrame();
panel = new JPanel();
addButton = new JButton("Add");
modifyButton = new JButton("Modify");
deleteButton = new JButton("Delete");
}
public void launchFrame()
{
addButton.setBounds(130,50,225,25);
addButton.setBounds(150,50,225,25);
addButton.setBounds(170,50,225,25);
addButton.setBounds(190,50,225,25);
panel.add(addButton);
panel.add(modifyButton);
panel.add(deleteButton);
panel.setLayout(null);
panel.setBackground(Color.RED);
frame.add(panel);
frame.setTitle("My Frame with Panel");
frame.setSize(600,400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here is main for calling Panels class
When run on main function Frame is shown without controllers (ie 3 buttons not shown)
public class Main
{
public static void main(String[] args)
{
Panels obj_panel=new Panels();
}
}
This is the main problem
frame.setLayout(null);
When you set the layout to null, that means that all of its components must have boundaries set. You try to add the panel, without any boundaries. You only set the boundaries for the buttons in the panel. If you remove the above line, it works.
Other Issues I'd really take a look at:
Don't use null layouts at all. Instead make use of layout managers, and let them handle the sizing and positioning for you. This results in a a much more manageable and flexible UI. Please take some time to learn the different layout managers. Start at Laying out Components Within a Container
All Swing apps should run on a special thread known as the Event Dispatch Thread (EDT). Please take some time to read Initial Threads to learn how you can accomplish this.
Here is a refactor (fixing the "Other issues") with no null layout, just using layout managers, margins, and borders, and the code in the main shows how to run the program on the Event Dispatch Thread
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
Panels obj_panel = new Panels();
}
});
}
}
class Panels {
private JFrame frame;
private JPanel panel;
private JButton addButton;
private JButton modifyButton;
private JButton deleteButton;
Panels() {
initGUI();
launchFrame();
}
private void initGUI() {
frame = new JFrame(); // default layout manager is BorderLayout
panel = new JPanel(); // default layout manager is FlowLayout
addButton = new JButton("Add");
modifyButton = new JButton("Modify");
deleteButton = new JButton("Delete");
}
private void launchFrame() {
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 10, 10));
buttonPanel.setBackground(Color.RED);
buttonPanel.add(addButton);
buttonPanel.add(modifyButton);
// add margin to left and right of delete button
// other buttons will follow suit because of GridLayout
deleteButton.setMargin(new Insets(0, 50, 0, 50));
buttonPanel.add(deleteButton);
// create some space at the top for the buttonPanel
buttonPanel.setBorder(new EmptyBorder(20, 0, 0, 0));
panel.add(buttonPanel);
panel.setBackground(Color.RED);
frame.add(panel);
frame.setTitle("My Frame with Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

location and size of jtextarea in jscrollpane is not set

I am working on the editor. I am using Java swing for it. I have embedded a JTextArea with JScrollPane. i want to position the jtextarea of particular size at the middle of JScrollPane. To do this I used setLocation function. But this is not working?
public class ScrollPaneTest extends JFrame {
private Container myCP;
private JTextArea resultsTA;
private JScrollPane scrollPane;
private JPanel jpanel;
public ScrollPaneTest() {
resultsTA = new JTextArea(50,50);
resultsTA.setLocation(100,100);
jpanel=new JPanel(new BorderLayout());
jpanel.add(resultsTA,BorderLayout.CENTER);
scrollPane = new JScrollPane(jpanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(800, 800));
scrollPane.setBounds(0, 0, 800, 800);
setSize(800, 800);
setLocation(0, 0);
myCP = this.getContentPane();
myCP.setLayout(new BorderLayout());
myCP.add(scrollPane);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new ScrollPaneTest();
}
}
You simply have to add the JTextArea to the JScrollPane, and add it to the CENTER of the JPanel having BorderLayout.
Don't use AbsolutePositioning. Add a proper LayoutManager, and let LayoutManager do the rest for positioning and sizing your components on the screen.
In order to use the setBounds(...) method you have to use a null Layout for your component, which is not worth using, provided the perspective, as mentioned in the first paragraph of the AbsolutePositioning. Though in the code example provided by you, you are doing both the thingies together i.e. using Layout and using AbsolutePositioning, which is wrong in every way. My advice STOP DOING IT :-)
In the example provided the ROWS and COLUMNS provided by you are sufficient to size the JTextArea by the Layout concern.
Code Example :
import java.awt.*;
import javax.swing.*;
public class Example
{
private JTextArea tarea;
private void displayGUI()
{
JFrame frame = new JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane textScroller = new JScrollPane();
tarea = new JTextArea(30, 30);
textScroller.setViewportView(tarea);
contentPane.add(textScroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Example().displayGUI();
}
});
}
}

Centering Panel in Java

For some reason i am having problems centering my panel vertically that is located inside another panel. I do exactly as the examples i studied but still no luck.
Down there is my code. Despite using setAlignmentY(0.5f) on my container panel, it still wont center when i resize the window.
Also the components inside container panel wont center either, despite setAligenmentX(0.5f).
I wonder if there is a solution for this, I pretty much tried everything out there but couldnt find a solution.
JLabel idLabel;
JLabel passLabel;
JTextField id;
JTextField pass;
JButton enter;
JPanel container;
public JournalLogin()
{
//setLayout(new FlowLayout());
//setPreferredSize(new Dimension(500, 500));
//setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
container = new JPanel();
container.setLayout(new MigLayout());
container.setAlignmentX(0.5f);
container.setAlignmentY(0.5f);
container.setPreferredSize(new Dimension(300, 300));
container.setBorder(BorderFactory.createTitledBorder("Login"));
add(container);
idLabel = new JLabel("ID:");
idLabel.setAlignmentX(0.5f);
container.add(idLabel);
id = new JTextField();
id.setText("id");
id.setAlignmentX(0.5f);
id.setPreferredSize(new Dimension(80, 20));
container.add(id, "wrap");
setAlignmentX and Y are not the way to go about doing this. One way to center a component in a container is to have the container use GridBagLayout and to add the component without using any GridBagConstraints, a so-called default addition. There are other ways as well.
For example to alter Nick Rippe's example (1+ to him):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
public class UpdatePane2 extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 200;
public UpdatePane2() {
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BorderLayout());
innerPanel.add(new JLabel("Hi Mom", SwingConstants.CENTER),
BorderLayout.NORTH);
innerPanel.add(new JButton("Click Me"), BorderLayout.CENTER);
setLayout(new GridBagLayout());
add(innerPanel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("UpdatePane2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new UpdatePane2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Alignments tend to be pretty picky in Swing - they do [usually] work... but if all you're looking for is a panel that's centered, I'd recommend using Boxes in the BoxLayout (My personal favorite LayoutManager). Here's an example to get you started:
import java.awt.Dimension;
import javax.swing.*;
public class UpdatePane extends JPanel{
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
//Create Buffers
Box verticalBuffer = Box.createVerticalBox();
Box horizontalBuffer = Box.createHorizontalBox();
verticalBuffer.add(Box.createVerticalGlue()); //Top vertical buffer
verticalBuffer.add(horizontalBuffer);
horizontalBuffer.add(Box.createHorizontalGlue()); //Left horizontal buffer
//Add all your content here
Box mainContent = Box.createVerticalBox();
mainContent.add(new JLabel("Hi Mom!"));
mainContent.add(new JButton("Click me"));
horizontalBuffer.add(mainContent);
horizontalBuffer.add(Box.createHorizontalGlue()); //Right horizontal buffer
verticalBuffer.add(Box.createVerticalGlue()); //Bottom vertical buffer
// Other stuff for making the GUI
verticalBuffer.setPreferredSize(new Dimension(300,200));
JFrame frame = new JFrame();
frame.add(verticalBuffer);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
You will need to get the LayoutManager to center the layout for you. Currently it looks like the implementation of "MigLayout" does not honor the Alignment. Try changing it or creating a subclass.

BoxLayout program not working

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class File
{
private JFrame frame1;
private JPanel panel1;
private JPanel panel2;
private JLabel labelWeight;
private JLabel labelHeight;
File()
{
frame1 = new JFrame();
panel1 = new JPanel();
panel2 = new JPanel();
labelWeight = new JLabel("Weight :");
labelHeight = new JLabel("Height :");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
panel1.setLayout(new FlowLayout());
panel1.add(labelWeight);
panel2.setLayout(new FlowLayout());
panel2.add(labelHeight);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
frame1.setLayout(new BoxLayout(frame1,BoxLayout.X_AXIS));
panel1.setAlignmentY(0);
panel2.setAlignmentY(0);
frame1.add(panel1);
frame1.add(panel2);
frame1.setSize(400, 200);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
public static void main (String args[])
{
new File();
}
}
It gives BoxLayout Sharing error at runtime
Generally, LayoutManagers are set on a JPanel. I guess JFrame implements this method to forward it to the content pane of the frame. I would suggest you try:
Container contentPane = frame1.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.X_AXIS));
If you still have problems take a look at the Swing tutorial on How to Use Box Layout for working examples.
Swing components should be created in the Event Dispatch Thread. Try this in your main():
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new File();
}
});
But your problem may be the same as this question.

Categories

Resources