How to align the jlabel text to left inside the jpanel - java

I am trying to align the Jlabel to left but i'm failing to do it let me know how can i tackle this problem any suggestions regarding this would be greatly appreciated
I have attempted with this slice of code yet it is not solving the problem
Jlabel=new JLabel("Label text",SwingConstants.LEFT);
Jlabel.setHorizontalAlignment(SwingConstants.LEFT);
here is my complete code
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyGui1 extends JPanel implements ActionListener {
/**
*
*/
static JScrollPane jsp;
protected JPanel panel;
protected JTextArea textarea;
static JFrame frame;
JLabel Jlabel=null;
public MyGui1() {
//to lay out the container's components in a rectangular grid
super(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
JButton jbutton=new JButton("button");
jbutton.setActionCommand("button");
jbutton.addActionListener(this);
add(jbutton,c);
c.gridy=1;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
setBackground(Color.cyan);
panel=new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
jsp=new JScrollPane(panel);
jsp.setPreferredSize(new Dimension(300,300));
jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
add(jsp, c);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
public void actionPerformed(ActionEvent evt) {
if("button".equals(evt.getActionCommand())){
execute();
}
}
synchronized public void execute(){
// to remove all the content of panel
panel.removeAll();
// to refresh the window
for(int i=0;i<20 ;i++){
Jlabel=new JLabel("Labe1l"+i,SwingConstants.LEFT);
// Jlabel.setAlignmentX(CENTER_ALIGNMENT);
// Jlabel.setAlignmentY(LEFT_ALIGNMENT);
textarea=new JTextArea();
textarea.setText("sample text");
if(i==2){
textarea.setText("sample text........................\nsample text.................. ");
}
if(i==5){
textarea.setText("sample text.\nsample text.sample text.\nsample text. ");
}
if(i==7){
textarea.setText("sample text.\nsample text.sample text.\nsample text sample text..\nsample text.sample text..\nsample text. ");
}
textarea.append("\n");
textarea.setEditable(false);
Jlabel.setLayout(new BorderLayout());
Jlabel.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(Jlabel);
// in order to wrap up the data in text area
textarea.setLineWrap(true);
panel.add(textarea);
Jlabel.setPreferredSize(new Dimension(240,30));
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// textarea.setPreferredSize(getMinimumSize());
// panel.setPreferredSize(getSize());
panel.revalidate();
panel.repaint();
jsp.getVerticalScrollBar().setValue(0);
jsp.validate();
}
});
}
jsp.revalidate();
jsp.repaint();
frame.repaint();
frame.revalidate();
}
#SuppressWarnings("static-access")
private static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("DesktopSearchEngine");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//adding window listener for exit operation
frame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(
frame,
"Are you sure you want to exit the application?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else if(result==JOptionPane.NO_OPTION){
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
//Add contents to the window GUI part and to perform all operations
frame.add(new MyGui1());
//Display the window.
frame.pack();
//to keep the frame visible
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

You could wrap the label in JPanel with FlowLayout.LEADING
JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEADING,0, 0));
wrapper.add(Jlabel);
panel.add(wrapper);
Also remember to follow Java naming convention. variables begin with lower case letters using camel casing: Jlabel → jLabel

Related

How to align vertically buttons of different sizes within a GridBagLayout?

I'm starting with swing, I have some questions about how to align elements within a GridBagLayout, I'm not sure either whether this is the correct approach, please advice.
I have the below code
import javax.swing.*;
import java.awt.*;
public class App {
public void start() {
JPanel mainPanel = new JPanel(new FlowLayout());
mainPanel.setBorder(BorderFactory.createLineBorder(Color.CYAN, 20));
//buttons for initial options
JButton button1 = new JButton("This is option A");
JButton button2 = new JButton("option B");
JButton button3 = new JButton("Another text");
JPanel second = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
second.setBackground(Color.GREEN);
second.add(button1, gbc);
second.add(button2, gbc);
second.add(button3, gbc);
mainPanel.add(second, BorderLayout.CENTER);
//frame configuration
JFrame frame = new JFrame();
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
SwingUtilities.invokeLater(() -> new App().start());
}
}
My goal is to produce the following output:
So far I have tried with BoxLayout with vertical alignment and it works but the problem is that it overwrites the preferred sized of the buttons and I want them all to be the same width.
Also, I tried with GridLayout and BorderLayout adding the elements to NORTH, CENTER, and SOUTH but the sizes of the buttons change.
What is the recommended way to center the elements but keeping their dimensions?
I would nest layouts:
A JPanel that holds the buttons and uses a new GridLayout(0, 1, 0, vGap) -- a grid that holds one column and variable number of rows, with a vGap gap between buttons.
Add that JPanel into another JPanel that uses GridBagLayout, and add it in a default way (no GridBagConstraints) which will center the first JPanel into the second. This would obviously have to somehow be the size desired. This can be achieved by either
overriding getPreferredSize() in a sensible way
Calling setPreferredSize(new Dimension(someWidth, someHeight)) -- this isn't quite as "clean"
Giving this a border, specifically a BorderFactor.EmptyBorder(gap, gap, gap, gap) where gap is the size of the border around the JPanel...
Done.
Test code that uses the GridBagLayout:
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class ButtonLayout extends JPanel {
public static final int MY_WIDTH = 750;
public static final int MY_HEIGHT = 500;
private static final float BTN_SIZE = 24f;
private String[] buttonTexts = {"This is Option A", "Option B",
"Something Else Entirely"};
public ButtonLayout() {
int colGap = 20;
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, colGap));
for (String btnText : buttonTexts) {
JButton button = new JButton(btnText);
// set first letter of text as mnemonic (alt-char shortcut)
int mnemonic = (int) btnText.charAt(0);
button.setMnemonic(mnemonic);
// make button bigger by increasing its font
button.setFont(button.getFont().deriveFont(BTN_SIZE));
// add to the GridLayout-using JPanel
buttonPanel.add(button);
}
// set layout of main panel to GridBag
setLayout(new GridBagLayout());
// add the button panel in a "default" manner (no constraints)
// which centers this panel
add(buttonPanel);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int width = Math.max(MY_WIDTH, superSize.width);
int height = Math.max(MY_HEIGHT, superSize.height);
return new Dimension(width, height);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ButtonLayout mainPanel = new ButtonLayout();
JFrame frame = new JFrame("ButtonLayout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Example 2 that uses EmptyBorder:
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class ButtonLayout extends JPanel {
public static final int MY_WIDTH = 750;
public static final int MY_HEIGHT = 500;
private static final float BTN_SIZE = 24f;
private String[] buttonTexts = {"This is Option A", "Option B",
"Something Else Entirely"};
public ButtonLayout() {
int colGap = 20;
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, colGap));
for (String btnText : buttonTexts) {
JButton button = new JButton(btnText);
// set first letter of text as mnemonic (alt-char shortcut)
int mnemonic = (int) btnText.charAt(0);
button.setMnemonic(mnemonic);
// make button bigger by increasing its font
button.setFont(button.getFont().deriveFont(BTN_SIZE));
// add to the GridLayout-using JPanel
buttonPanel.add(button);
}
add(buttonPanel);
int top = 60;
int left = top;
int bottom = 2 * top;
int right = left;
setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ButtonLayout mainPanel = new ButtonLayout();
JFrame frame = new JFrame("ButtonLayout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I'm not sure I completely understand the issue, but if you want to vertically align the buttons, BUT allow them to keep their preferred size, just don't provide any kind of fill constraint, for example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SoTest {
public static void main(String[] args) {
new SoTest();
}
public SoTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JButton("This is option A"), gbc);
add(new JButton("Option B"), gbc);
add(new JButton("Another button"), gbc);
}
}
}
Or, if you want them to have the same width, use a fill constraint
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SoTest {
public static void main(String[] args) {
new SoTest();
}
public SoTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.BOTH;
add(new JButton("This is option A"), gbc);
add(new JButton("Option B"), gbc);
add(new JButton("Another button"), gbc);
}
}
}
If you want to mix a more complex layout, then you should consider making use of compound layouts
But wait, there's no outline...
So, a number of ways you "might" be able to do this, for example, you could use a CompoundBorder....
setBorder(new CompoundBorder(new LineBorder(Color.CYAN, 16), new EmptyBorder(32, 32, 32, 32)));
But the devil is in the detail

List of Buttons one below other inside JScrollPane

I want to make list of JButtons (with fixed dimensions, one beneath another) inside JScrollPane, using Swing. My idea was to make JPanel with GridBagLayout and add buttons in their suiting rows, and then create JScrollPane with that JPanel. That looks fine when number of buttons is large, but when the number of buttons is 2 or 3, I can't manage to align buttons one right below the other.
Also later I will add option to add new button (thus the + sign).
Works fine with 10 buttons
I get this empty space between button 0 and button 1 when it's just 2 buttons (this is the problem)
The code (creates upper east panel)
private JPanel createLayerPanel() {
JPanel layerPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Label ------------------------------------------------
JLabel layersLabel = new JLabel("Buttons");
layersLabel.setHorizontalAlignment(SwingConstants.CENTER);
layersLabel.setFont(DEFAULT_FONT);
//layersLabel.setBorder(new LineBorder(Color.red, 3));
layersLabel.setBackground(new Color(0x22222));
layersLabel.setForeground(new Color(0xFFFFFF));
layersLabel.setOpaque(true);
c.gridx = c.gridy = 0;
c.ipadx = 180;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
layerPanel.add(layersLabel, c);
// Button ------------------------------------------------
JButton newLayerBtn = new JButton("+");
newLayerBtn.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 18));
newLayerBtn.setBackground(new Color(0x222222));
newLayerBtn.setForeground(Color.white);
newLayerBtn.setFocusable(false);
c.gridx = 1;
c.gridy = 0;
c.ipadx = 0;
c.weightx = 0;
layerPanel.add(newLayerBtn, c);
// ScrollPane ------------------------------------------------
//------------------------------------------------------------
//------------------------------------------------------------
JPanel layerListPanel = new JPanel(new GridBagLayout());
layerListPanel.setBackground(Color.BLACK);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1;
gbc.ipady = 40;
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.NORTH;
for (gbc.gridy = 0; gbc.gridy < 10; gbc.gridy++) {
JButton btn = new JButton("Button " + gbc.gridy);
layerListPanel.add(btn, gbc);
}
JScrollPane js = new JScrollPane(layerListPanel);
js.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// ...
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
layerPanel.add(js, c);
return layerPanel;
}
Do you absolutely need a GridBagLayout?
I just made a demo using a simple Box.
And please have a look at How to write an SSCCE.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class YY extends JFrame {
static String[] args;
public YY() {
setSize(160, 200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
int icnt= args.length==0 ? 5 : Integer.parseInt(args[0]);
Box box= Box.createVerticalBox();
for (int i=1; i<=icnt; i++) {
JButton btn= new JButton("Button "+i);
btn.setMaximumSize(new Dimension(150, 30));
box.add(btn);
}
JScrollPane scroll= new JScrollPane(box);
scroll.setPreferredSize(new Dimension(150, 100));
add(scroll);
setVisible(true);
}
public static void main(String... args) {
YY.args= args;
EventQueue.invokeLater(YY::new);
}
}
The below code initially displays a JFrame that contains a single JButton that displays the text Add. Each time you click the button a new JButton appears above it. The text on each newly created button is a three digit number with leading zeros that is incremented each time the Add button is clicked. And whenever a new button is added, the JFrame increases in height in order to display the newly added button.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class GridBttn implements ActionListener, Runnable {
private int counter;
private JFrame frame;
private JPanel gridPanel;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
addButtonToGridPanel();
}
private void addButtonToGridPanel() {
JButton button = new JButton(String.format("%03d", counter++));
gridPanel.add(button);
frame.pack();
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Add"));
return buttonsPanel;
}
private JPanel createGridPanel() {
gridPanel = new JPanel(new GridLayout(0, 1));
return gridPanel;
}
private void showGui() {
frame = new JFrame("Grid");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createGridPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GridBttn());
}
}
Note the parameters to GridLayout constructor. Zero rows and one column. This means that whenever a Component is added to the JPanel it will be placed directly beneath the last Component added. In other words all the components added will appear in a single column. Also note that I call method pack() (of class JFrame) after adding a new button. This causes the JFrame to recalculate its size in order to display all the buttons.
EDIT
Due to OP's comment slightly modified above code so as to be more suitable to his requirements.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
public class GridBttn implements ActionListener, Runnable {
private int counter;
private JFrame frame;
private JPanel gridPanel;
private JPanel gridPanel2;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
addButtonToGridPanel();
}
private void addButtonToGridPanel() {
JButton button = new JButton(String.format("%03d", counter++));
gridPanel2.add(button);
frame.pack();
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Add"));
return buttonsPanel;
}
private JPanel createMainPanel() {
gridPanel = new JPanel();
gridPanel.setPreferredSize(new Dimension(400, 300));
return gridPanel;
}
private JScrollPane createScrollPane() {
gridPanel2 = new JPanel();
BoxLayout layout = new BoxLayout(gridPanel2, BoxLayout.PAGE_AXIS);
gridPanel2.setLayout(layout);
JScrollPane scrollPane = new JScrollPane(gridPanel2,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new Dimension(70, 0));
return scrollPane;
}
private void showGui() {
frame = new JFrame("Grid");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createScrollPane(), BorderLayout.LINE_END);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GridBttn());
}
}

What's the best way to organize JPanels in a list?

I've found myself writing up quite a few programs recently which all need to display some collection of data. So far the best looking approach I've thought of is make small JPanels which contain data on each item in the collection and put them all in a big JPanel which I then put in a JScrollPane. It works and looks just as intended but there's one issue: I can't seem to get the smaller JPanels to start at the top of the bigger JPanel.
The problem is only apparent when I've got a small number of small JPanels (green) added into the bigger JPanel (red).
Described below is the method I used to produce the above and I'd like to know if there's a better way I could do it (where the list starts at the top like it should):
I created a class which extends JPanel and in it add all data I want to display. We'll call it "SmallPanel.java". I don't set the size of it (that comes later).
In my main window's class (which extends JFrame):
private JScrollPane scrollPane;
private JPanel panel;
...
scrollPane = new JScrollPane();
getContentPane().add(scrollPane);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
scrollPane.setViewportView(panel);
...
private void addPanel()
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = panel.getComponentCount(); //The new JPanel's place in the list
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START; //I thought this would do it
gbc.ipady = 130; //Set the panel's height, the width will get set to that of the container JPanel (which is what I want since I'd like my JFrames to be resizable)
gbc.insets = new Insets(2, 0, 2, 0); //Separation between JPanels in the list
gbc.weightx = 1.0;
SmallPanel smallPanel = new SmallPanel();
panel.add(smallPanel, gbc);
panel.revalidate();
panel.invalidate();
panel.repaint(); //Better safe than peeved
}
Call the addPanel() method every time I want to add a panel.
EDIT
Final solution (based on MadProgrammer's answer below):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.BevelBorder;
public class ListPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private JPanel fillerPanel;
private ArrayList<JPanel> panels;
public ListPanel(List<JPanel> panels, int height)
{
this(panels, height, new Insets(2, 0, 2, 0));
}
public ListPanel(List<JPanel> panels, int height, Insets insets)
{
this();
for (JPanel panel : panels)
addPanel(panel, height, insets);
}
public ListPanel()
{
super();
this.fillerPanel = new JPanel();
this.fillerPanel.setMinimumSize(new Dimension(0, 0));
this.panels = new ArrayList<JPanel>();
setLayout(new GridBagLayout());
}
public void addPanel(JPanel p, int height)
{
addPanel(p, height, new Insets(2, 0, 2, 0));
}
public void addPanel(JPanel p, int height, Insets insets)
{
super.remove(fillerPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = getComponentCount();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.ipady = height;
gbc.insets = insets;
gbc.weightx = 1.0;
panels.add(p);
add(p, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = getComponentCount();
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
add(fillerPanel, gbc);
revalidate();
invalidate();
repaint();
}
public void removePanel(JPanel p)
{
removePanel(panels.indexOf(p));
}
public void removePanel(int i)
{
super.remove(i);
panels.remove(i);
revalidate();
invalidate();
repaint();
}
public ArrayList<JPanel> getPanels()
{
return this.panels;
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(500, 500));
f.setLocationRelativeTo(null);
f.getContentPane().setLayout(new BorderLayout());
final ListPanel listPanel = new ListPanel();
for (int i = 1; i <= 10; i++)
listPanel.addPanel(getRandomJPanel(), new Random().nextInt(50) + 50);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent paramActionEvent)
{
listPanel.addPanel(getRandomJPanel(), new Random().nextInt(50) + 50);
}
});
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent paramActionEvent)
{
listPanel.removePanel(0);
}
});
f.getContentPane().add(btnRemove, BorderLayout.NORTH);
f.getContentPane().add(btnAdd, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setViewportView(listPanel);
f.getContentPane().add(scrollPane, BorderLayout.CENTER);
f.setVisible(true);
}
public static JPanel getRandomJPanel()
{
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.add(new JLabel("This is a randomly sized JPanel"));
panel.setBackground(new Color(new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat()));
return panel;
}
}
The best solution I've found is to use VerticalLayout from the SwingLabs SwingX (which can be downloaded from here) libraries.
You "could" use a GridBagLayout with an invisible component positioned at the end, whose weighty property is set to 1, but this is a lot more additional work to manage, as you need to keep updating the x/y positions of all the components to keep it in place...
Updated with GridBagLayout example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class VerticalLayoutExample {
public static void main(String[] args) {
new VerticalLayoutExample();
}
public VerticalLayoutExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final TestPane pane = new TestPane();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pane.addAnotherPane();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pane));
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel filler;
private int y = 0;
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
filler = new JPanel();
filler.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.gridy = 0;
add(filler, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
public void addAnotherPane() {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Hello"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = y++;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
add(panel, gbc);
GridBagLayout gbl = ((GridBagLayout)getLayout());
gbc = gbl.getConstraints(filler);
gbc.gridy = y++;
gbl.setConstraints(filler, gbc);
revalidate();
repaint();
}
}
}
This is just a concept. As camickr has pointed out, so long as you know the last component, you can adjust the GridBagConstraints of the component so that the last component which is in the list has the weighty of 1 instead...
As you can, you can override some of the things GridBagLayout does, for example, instead of using the preferred size of the panel, I've asked GridBagLayout to make it fill the HORIZONTAL width of the parent container...
You can use a vertical BoxLayout.
Just make sure the maximum size of the panel is equal to the preferred size so the panel doesn't grow.
Edit:
Since your class already has a custom panel all you need to do is override the getMaximumSize() method to return an appropriate value. Something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class VerticalLayoutExample2 {
public static void main(String[] args) {
new VerticalLayoutExample2();
}
public VerticalLayoutExample2() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final TestPane pane = new TestPane();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pane.addAnotherPane();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pane));
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel filler;
private int y = 0;
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder( new EmptyBorder(4, 4, 4, 4) );
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
public void addAnotherPane() {
SmallPanel panel = new SmallPanel();
panel.setLayout( new GridBagLayout() );
panel.add(new JLabel("Hello"));
add(panel);
add(Box.createVerticalStrut(4));
revalidate();
repaint();
}
}
static class SmallPanel extends JPanel
{
#Override
public Dimension getMaximumSize()
{
Dimension preferred = super.getPreferredSize();
Dimension maximum = super.getMaximumSize();
maximum.height = preferred.height;
return maximum;
}
}
}
I know you mentioned you don't want to use a lib, but you can also look at Relative Layout. It is only a single class. It can easily mimic a BoxLayout but is easier to use because you don't need to override the getMaximumSize() method or add a Box component to the panel to give the vertical spacing.
You would set it as the layout of your panel as follow:
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill( true ); // fills components horizontally
rl.setGap(4); // vertical gap between panels
yourPanel.setLayout(rl);
yourPanel.add( new SmallPanel(...) );
yourPanel.add( new SmallPanel(...) );

How to stop JTextFields from running off the Frame

I want to stop the text field from running off the GUI or print the text field on a new "line".
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame {
private JTextField TextField0;
private JTextField TextField1;
private JCheckBox CheckBox0;
private JPanel panel;
//CONSTRUCTOR
public Window() {
super("Checkbox");
setLayout(new FlowLayout());
panel = new JPanel();
add(panel, BorderLayout.CENTER);
TextField0 = new JTextField("Add field",15);
panel.add(TextField0);
TextField1 = new JTextField("Add field", 15);
CheckBox0 = new JCheckBox("");
HandlerClass handler = new HandlerClass();
TextField0.addActionListener(handler);
}
public class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource()==TextField0) {
CheckBox0.setText(String.format("%s",event.getActionCommand()));
panel.remove(TextField0);
panel.add(CheckBox0);
panel.add(TextField1);
panel.revalidate();
panel.repaint();
}
}
}
}
There's not really anything you can do...
JTextField will allow the text to overflow the viewable area of the textfield (trimming the text on the screen)
You could try using a JTextArea, which supports multi line text
You could also try packing the frame
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
String text = "This is a long piece of text that seems to go on and on and on and on an on....and some more...";
JTextField field = new JTextField(10);
JTextArea ta1 = new JTextArea(10, 2);
JTextArea ta2 = new JTextArea(10, 2);
field.setText(text);
ta1.setText(text);
ta2.setText(text);
configure(ta1);
configure(ta2);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.add(field, gbc);
frame.add(ta1, gbc);
frame.add(new JScrollPane(ta2), gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void configure(JTextArea ta) {
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
}
});
}
}
Set the layout of your panel to a Boxlayout instead of a Borderlayout. See the following link for the different layouts and how to use them:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

java - How would I dynamically add swing component to gui on click?

What I am looking to do is a similar principle to adding attachments to emails, you can click a button and a new browse box would open increasing the number of separate attachments you can have.
I'm fairly new so if someone could point me towards an example?
Sample code to add Buttons on the fly dynamically.
panel.add(new JButton("Button"));
validate();
Full code:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
public class AddComponentOnJFrameAtRuntime extends JFrame implements ActionListener {
JPanel panel;
public AddComponentOnJFrameAtRuntime() {
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
this.panel = new JPanel();
this.panel.setLayout(new FlowLayout());
add(panel, BorderLayout.CENTER);
JButton button = new JButton("CLICK HERE");
add(button, BorderLayout.SOUTH);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
this.panel.add(new JButton("Button"));
this.panel.revalidate();
validate();
}
public static void main(String[] args) {
AddComponentOnJFrameAtRuntime acojfar = new AddComponentOnJFrameAtRuntime();
}
}
Resource
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton(new AbstractAction("Click to add") {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new JLabel("Bla"));
frame.validate();
frame.repaint();
}
});
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
Component was not visible until setSize() was called:
component.setSize(100,200);
jPanel.add(component);
jPanel.revalidate();
jPanel.repaint();
panel.add(button);
panel.revalidate();
panel.repaint();
Java : Dynamically add swing components
for Example : count=3
//Java Swing: Add Component above method
public void dya_addcomp(int count)
{
//Dynamicaly Delete Image_icon
BufferedImage Drop_Tablefield = null;
try {
Drop_Tablefield = ImageIO.read(this.getClass().getResource("/images/drop.png"));
} catch (IOException ex) {
msg(" Error: drop and edit icon on Table, "+ex);
}
//count Items: 3 times for loop executed..
for(int i=0;i<count;i++)
{
//cnt++;
//lblcount.setText("Count : "+cnt);
JTextField txtcolnm=new JTextField("",20);
JComboBox cmbtype=new JComboBox();
JTextField txtcolsize=new JTextField("",20);
JButton Drop_Table_Field = new JButton(new ImageIcon(Drop_Tablefield));
cmbtype.addItem("INTEGER"); cmbtype.addItem("FLOAT");
cmbtype.addItem("STRING"); cmbtype.addItem("BOOLEAN");
colnamepanel.add(txtcolnm); colnamepanel.add(cmbtype);
colnamepanel.add(txtcolsize); colnamepanel.add(Drop_Table_Field);
colnamepanel.setAutoscrolls(true);
//refresh panel
colnamepanel.revalidate();
colnamepanel.repaint();
//set the layout on Jpanel
colnamepanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));
}//end for loop
}//end method

Categories

Resources