I'm attempting use flow layout to make a menu screen that orients with a single column, but whenever I add a button, it adds it to a single row.
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Proj
{
JPanel card1,card2;
ActionListener listener;
JFrame menu;
JFrame catagories;
JButton menu1,addOrTake,cata,payd,showd;
//JButton
public Proj(){
card2=new JPanel();
menu = new JFrame("Card Layout");
catagories = new JFrame();
//final Container contentPane = menu.getContentPane();
final CardLayout layout = new CardLayout();
menu.setLayout(layout);
card1=new JPanel();
menu1 = new JButton("");
menu1.setIcon(new ImageIcon("C:/Users/sabar/Menu.jpg"));
menu1.setSize(60,600);
menu1.setVisible(true);
addOrTake = new JButton();
addOrTake.setIcon(new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg"));
cata = new JButton("");
cata.setIcon(new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg"));
showd = new JButton("");
showd.setIcon(new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg"));
payd = new JButton("");
payd.setSize(60, 600);
payd.setIcon(new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg"));
payd.setVisible(true);
card1.add(menu1);
card1.add(addOrTake);
card1.add(cata);
card1.add(showd);
card1.add(payd);
menu1.addActionListener(listener);
addOrTake.addActionListener(listener);
cata.addActionListener(listener);
showd.addActionListener(listener);
payd.addActionListener(listener);
listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {}};
// TODO Auto-generated method stub
menu.setSize(60, 600);
menu.setVisible(true);
JButton poo=new JButton("Poo");
poo.setSize(60,600);
card2.add((poo));
card2.add(new JButton("Pee"));
card2.add(new JButton("Per"));
card2.add(new JButton("POt"));
card2.setVisible(false);
menu.add(card2);
menu.add(card1);
catagories.pack();
menu.pack();
card1.setVisible(false);
}
public static void main(String[]args)
{
Proj poop =new Proj();
}
}
Problems:
You're adding components to menu, the CardLayout-using container, without use of a 2nd parameter String constant. Without this, it might be hard to easily swap "cards" (components).
If you want a single column type of layout, you need to use a layout manager that allows this, and the JPanel default layout isn't it. Better options:
GridLayout(0, 1) for variable number of rows, one column
BoxLayout(Container, BoxLayout.PAGE_AXIS)
GridBagLayout with the right GridBagConstraint gridx and gridy attributes.
Start by using a layout manager which is capable of achiving your results.
Start by taking a look at Laying Out Components Within a Container, How to Use GridLayout and How to Use GridBagLayout for some ideas.
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Proj {
JPanel card1, card2;
ActionListener listener;
JButton menu1, addOrTake, cata, payd, showd;
//JButton
JFrame menu;
public Proj() {
menu = new JFrame("Card Layout");
//final Container contentPane = menu.getContentPane();
final CardLayout layout = new CardLayout();
menu.setLayout(layout);
card1 = new JPanel(new GridBagLayout());
card2 = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
menu1 = new JButton("Mneu");
menu1.setVisible(true);
addOrTake = new JButton("Add or take");
cata = new JButton("Cata");
showd = new JButton("ShowD");
payd = new JButton("payd");
card1.add(menu1, gbc);
card1.add(addOrTake, gbc);
card1.add(cata, gbc);
card1.add(showd, gbc);
card1.add(payd, gbc);
menu1.addActionListener(listener);
addOrTake.addActionListener(listener);
cata.addActionListener(listener);
showd.addActionListener(listener);
payd.addActionListener(listener);
listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
};
// TODO Auto-generated method stub
JButton poo = new JButton("Poo");
card2.add((poo), gbc);
card2.add(new JButton("Pee"), gbc);
card2.add(new JButton("Per"), gbc);
card2.add(new JButton("POt"), gbc);
menu.add(card2, "Card2");
menu.add(card1, "Card1");
layout.show(menu.getContentPane(), "Card1");
menu.pack();
menu.setLocationRelativeTo(null);
menu.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Proj poop = new Proj();
}
});
}
}
I'd also have a closer look at How to Use CardLayout for more details about how it works, because you're using it wrong
Related
So I'm creating a GUI that represents a vending machine. I'm just running into some problems trying to get the layout to work the way I want it. My thought was to insert an image into a JLabel, and then overlay that image with transparent JButtons in specific locations so that when you click on the image in certain locations, it will trigger the JButton. I haven't gotten to the transparency yet as I'm currently stuck on how to get the JButtons precisely where they need to be.
I've tried setLocation and setBounds with no luck. Any help on how to exactly position the jbuttons over the possible vending machine choices would be great.
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class vendMachine extends JFrame
{
//Frame Dimensions
private static final int FRAME_HEIGHT = 800;
private static final int FRAME_WIDTH = 800;
private JPanel totalGUI, imagePanel, coinPanel;
public vendMachine()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Vending Machine");
}
private void createComponents()
{
try
{
BufferedImage machineImg = ImageIO.read(new File("images/pepsivend.jpg"));
JLabel machineImgLabel = new JLabel(new ImageIcon(machineImg));
machineImgLabel.setLayout(new FlowLayout());
JButton test = new JButton("TEST BUTTON");
machineImgLabel.add(test);
//test.setBounds(0,0,0,0);
ImageIcon pennyIcon = new ImageIcon("images/coins/penny.jpg");
JButton pennyButton = new JButton(pennyIcon);
ImageIcon nickelIcon = new ImageIcon("images/coins/nickel.jpg");
JButton nickelButton = new JButton(nickelIcon);
ImageIcon dimeIcon = new ImageIcon("images/coins/dime.jpg");
JButton dimeButton = new JButton(dimeIcon);
ImageIcon quarterIcon = new ImageIcon("images/coins/quarter.jpg");
JButton quarterButton = new JButton(quarterIcon);
coinPanel = new JPanel();
coinPanel.setLayout(new GridLayout(4,1));
coinPanel.add(pennyButton);
coinPanel.add(nickelButton);
coinPanel.add(dimeButton);
coinPanel.add(quarterButton);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(machineImgLabel, BorderLayout.CENTER);
totalGUI.add(coinPanel, BorderLayout.EAST);
}
catch (IOException e)
{
e.printStackTrace();
}
add(totalGUI);
}
}
In the above Image I would like some help on how to get the test button, to overlay on top of the pepsi selection. From there I can go about making it transparent and removing the borders and text.
Edited to add: none of the buttons do anything yet. Simply trying to get the layout going before adding in anything else
It's unclear as to what your actually problem, however, I'll start with the layout...
No single layout will ever do everything you want, some times, you'll need to use multiple layouts and compound them. This example uses a BorderLayout and a GridBagLayout to set up the basic layout...
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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new VendingMachinePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class VendingMachinePane extends JPanel {
public VendingMachinePane() {
setLayout(new BorderLayout());
JLabel label = new JLabel("Cover");
// Demonstration purpose only
label.setPreferredSize(new Dimension(200, 400));
label.setOpaque(true);
label.setBackground(Color.BLUE);
add(label);
JPanel optionsPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTH;
optionsPane.setBackground(Color.DARK_GRAY);
optionsPane.add(new JLabel("Coin Slot"), gbc);
optionsPane.add(makeButton("Pepsi"), gbc);
optionsPane.add(makeButton("Diet Pepsi"), gbc);
optionsPane.add(makeButton("Slice"), gbc);
optionsPane.add(makeButton("Dr Pepper"), gbc);
optionsPane.add(makeButton("Lipton"), gbc);
optionsPane.add(makeButton("Mountain Dew"), gbc);
optionsPane.add(makeButton("Schweppes"), gbc);
gbc.weighty = 1;
optionsPane.add(makeButton("Pepsi"), gbc);
add(optionsPane, BorderLayout.LINE_END);
}
protected JButton makeButton(String text) {
JButton btn = new JButton(text);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setMargin(new Insets(4, 4, 4, 4));
btn.setOpaque(false);
return btn;
}
}
}
As to your "overlay buttons" issue, to me, that doesn't make sense, since a JButton has a icon property, why not just use a JButton to start with?
You make buttons transparent simply by changing their borderPainted contentAreaFilled and opaque properties
// You can pass a `Icon` instead of a `String` to the constructor
JButton btn = new JButton(text);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setMargin(new Insets(4, 4, 4, 4));
btn.setOpaque(false);
Don't forget to setup an ActionListener ;)
Updated, based on the updated requirements...
You Could...
Break the image down in segments, making each element it's own image and simply applying those to the buttons, using a similar approach above
You Could...
Map hot spots on the image, and using a MouseListener monitor where the mouseClicked events occur - you do lose the advantage of keyboard input though
You Could...
Map out the hot spots of the image and using a GridBagLayout or custom layout manager, map the buttons onto the image.
I feel as beginner I may have bitten off too much in regards to application building. That said, I am working on developing an application for a friend that will have prompts where each JPanel will provide fields to create an object to be used later. What I would like to have happen is that when the panel loads, it displays one object creation panel and a button to dynamically add a new panel if the user wants to make multiples (the plus button would add the new panel).
I have drawn up something in paint to illustrate this:
By my very limited understanding, I can create a panel to hold these sub-panels, and then add a action listener to the '+' button to create new panels. The only way I could think to implement this is to create a constructor for the panel I want to add. Is this possible? Let me show you what I have:
package com.company;
import java.awt.*;
import javax.swing.*;
/**
* Created by Travis on 3/1/2015.
*/
public class MainSnakeGui extends JFrame{
protected int panelCount;
//row 1
JPanel row1 = new JPanel();
JLabel splitSnakeLabel = new JLabel("Create a Split Snake", JLabel.CENTER);
//row 2
JPanel row2 = new JPanel();
JButton addButton = new JButton("+");
public MainSnakeGui() {
super("Snake Channels");
setSize(550, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(5, 1, 10, 10);
setLayout(layout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(layout1);
row1.add(splitSnakeLabel);
add(row1);
GridLayout layout2 = new GridLayout(1, 2, 10, 10);
row2.setLayout(layout2);
row2.add(addButton);
MainSnakeConstructor snakePanel = new MainSnakeConstructor();
row2.add(snakePanel);
add(row2);
setVisible(true);
}
public static void setLookAndFeel () {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
}
public static void main(String[] arg) {
MainSnakeGui.setLookAndFeel();
MainSnakeGui frame = new MainSnakeGui();
}
}
Here is the constructor:
package com.company;
import javax.swing.*;
import java.awt.*;
/**
* Created by Travis on 3/1/2015.
*/
public class MainSnakeConstructor extends JFrame {
public MainSnakeConstructor () {
JPanel splitSnakeRow = new JPanel();
JLabel snakeNameLabel = new JLabel("Snake Name");
JLabel channelCountLabel = new JLabel("Channel Count");
JCheckBox artistSuppliedCheckBox = new JCheckBox("Artist Supplied?");
JTextField snakeNameTextField = new JTextField(30);
JTextField channelCountTextField = new JTextField(3);
GridLayout layout = new GridLayout(3,2,10,10);
splitSnakeRow.setLayout(layout);
splitSnakeRow.add(snakeNameLabel);
splitSnakeRow.add(channelCountLabel);
splitSnakeRow.add(artistSuppliedCheckBox);
splitSnakeRow.add(snakeNameTextField);
splitSnakeRow.add(channelCountTextField);
add(splitSnakeRow);
}
}
Think about it differently. You want a button that allows you to add new panels, so you really only need a single button.
From there, you need some kind common panel which provides the functionality you want to the user (the creation panel). Then, when the user clicks the add button, you create a new creation panel and add it to the container been used to display them, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JButton btnAdd = new JButton("+");
setLayout(new BorderLayout());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttons.add(btnAdd);
add(buttons, BorderLayout.NORTH);
JPanel content = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
content.add(new JPanel(), gbc);
add(new JScrollPane(content));
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CreationPane pane = new CreationPane();
int insertAt = Math.max(0, content.getComponentCount() - 1);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
content.add(pane, gbc, insertAt);
content.revalidate();
content.repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public static class CreationPane extends JPanel {
private static int count;
public CreationPane() {
setLayout(new GridBagLayout());
add(new JLabel("Make it so " + (count++)));
setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
}
}
}
Now having done all that, I prefer the VerticalLayout manager from SwingLabs, SwingX library, which basically does the same thing...
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
I created simple app with Border Layout and added into it two buttons and JTable. I use JSplitPane between button2 and JTable. I would like redefine default size of block where is situated button1. How can I to solve this task?
Here is my code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class Sample {
public Sample() {
JFrame app = new JFrame("Sample");
app.setSize(new Dimension(800,600));
JPanel panel = new JPanel();
app.add(panel);
BorderLayout borderlayout = new BorderLayout();
panel.setLayout(borderlayout);
JButton but1 = new JButton("1");
JButton but2 = new JButton("2");
but2.setMinimumSize(new Dimension(250,0));
String[] colNames = {"Name","Number","Scores"};
Object[][] data = {
{ "Mark",11,12},
{"Tommy",23,34},
{"John",34,45}
};
JTable table = new JTable(data, colNames);
JScrollPane scrollpane = new JScrollPane(table);
JSplitPane jsplitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,but2,scrollpane);
panel.add(but1,BorderLayout.NORTH);
panel.add(jsplitpane,BorderLayout.CENTER);
app.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Sample();
}
});
}
}
Components in the BorderLayout.PAGE_START location have the height of their preferred sizes respected. Therefore, you can override the preferred size of JButton but1
JButton but1 = new JButton("1") {
public Dimension getPreferredSize() {
return new Dimension(100, 80);
};
};
If you are willing to use GridBagLayout for the said purpose, then I guess this Layout and do this job for you, as stated in the below pasted code example :-)
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class Sample {
public Sample() {
JFrame app = new JFrame("Sample");
app.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
app.setSize(new Dimension(800,600));
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
JButton but1 = new JButton("1");
JButton but2 = new JButton("2");
but2.setMinimumSize(new Dimension(250,0));
String[] colNames = {"Name","Number","Scores"};
Object[][] data = {
{ "Mark",11,12},
{"Tommy",23,34},
{"John",34,45}
};
JTable table = new JTable(data, colNames);
JScrollPane scrollpane = new JScrollPane(table);
JSplitPane jsplitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,but2,scrollpane);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.3;
centerPanel.add(but1, gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 1;
gbc.weighty = 0.7;
centerPanel.add(jsplitpane, gbc);
panel.add(centerPanel, BorderLayout.CENTER);
app.add(panel);
app.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Sample();
}
});
}
}
Here is the output of the same :
I want to add textfields dynamically on the click of a button but the value to be fetched and the button are in one class and the panel where i want to add the textboxes and sliders adjacent to the are in a different class. Code is -
public class TipSplitting extends JPanel
JLabel lblNoOfGuests = new JLabel("No. Of guests");
lblNoOfGuests.setBounds(10, 26, 95, 14);
add(lblNoOfGuests);
private JTextField noofguests = new JTextField();
noofguests.setBounds(179, 23, 86, 20);
add(noofguests);
noofguests.setColumns(10);
JButton btnTiptailoring = new JButton("TipTailoring");
btnTiptailoring.setBounds(117, 286, 89, 23);
add(btnTiptailoring);
public class TipTailoring extends JPanel {}
In this class I need to create the text fields dynamically according to the no. entered. In the variable noofguests and the click of the button in the previous class.
I can't really see what the problem, but here some simple demo code of what you describe.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestDynamicallyAddedTextFields {
private void initUI() {
JFrame frame = new JFrame(TestDynamicallyAddedTextFields.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel textfieldContainerPanel = new JPanel();
textfieldContainerPanel.setLayout(new GridBagLayout());
JLabel nrOfGuests = new JLabel("Nr. of guests");
final JFormattedTextField textfield = new JFormattedTextField();
textfield.setValue(Integer.valueOf(1));
textfield.setColumns(10);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textfield.getValue() != null) {
addTextFieldsToPanel((Integer) textfield.getValue(), textfieldContainerPanel);
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
panel.add(nrOfGuests);
panel.add(textfield);
panel.add(add);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textfieldContainerPanel));
frame.setSize(300, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void addTextFieldsToPanel(Integer value, JPanel textfieldContainerPanel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
for (int i = 0; i < value; i++) {
textfieldContainerPanel.add(new JTextField(20), gbc);
}
textfieldContainerPanel.revalidate();
textfieldContainerPanel.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestDynamicallyAddedTextFields().initUI();
}
});
}
}
And the result: