I am trying to print out a dynamically generated list of buttons with each button on a new line.
public void addComponentToPane(Container pane) {
JTabbedPane tabbedPane = new JTabbedPane();
//Create the "cards".
JPanel card1 = new JPanel() {
JPanel card1 = new JPanel()
...
int n = 10;
JButton[] jButtons = new JButton[10];
for(int i=0; i<n; i++){
jButtons[i] = new JButton("test" + i);
card1.add(jButtons[i]);
//card1.add("<br>");//<--this is wrong; but hopefully you get my point.
jButtons[i].addActionListener(this);
}
Put them into a box:
Box card1 = Box.createVerticalBox();
or, if you want all the buttons to have the same size, use GridLayout with one column:
JPanel card1 = new JPanel(new GridLayout(n, 1))
Here are two solutions using a constrained GridLayout and a BoxLayout
I prefer the GridLayout (on the left) since it normalizes the width of the buttons and makes it easy to add a small space between them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DynamicButtons {
public static void main(String[] args) {
final JPanel gui = new JPanel(new BorderLayout());
final JPanel gridButton = new JPanel(new GridLayout(0,1,2,2));
gridButton.add(new JButton("Button 1"));
JPanel gridConstrain = new JPanel(new BorderLayout());
gridConstrain.add(gridButton, BorderLayout.NORTH);
final Box boxButton = Box.createVerticalBox();
boxButton.add(new JButton("Button 1"));
JButton b = new JButton("Add Button");
b.addActionListener( new ActionListener() {
int count = 2;
public void actionPerformed(ActionEvent ae) {
gridButton.add(new JButton("Button " + count));
boxButton.add(new JButton("Button " + count));
count++;
gui.revalidate();
}
});
gui.add(b, BorderLayout.NORTH);
JSplitPane sp = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(gridConstrain),
new JScrollPane(boxButton));
gui.add(sp, BorderLayout.CENTER);
gui.setPreferredSize(new Dimension(250,150));
JOptionPane.showMessageDialog(null, gui);
}
}
Use GridBagLayout and set GridBagConstaints.gridy field.
I suppose you need something like this :
For this you require a Box Layout , see this for more details : How to Use BoxLayout
and if needed here is a demo : Java Tutorials Code Sample – BoxLayoutDemo.java
Related
As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);
i am having trouble with designing my button, ive created 13 and made it 5,3 but the last button does not stretch to the width of the 3 columns.
it is meant to look like this
example picture
here is my code, if anyone can offer any suggestions thatd be helpful, thank you.
import javax.swing.*;
public class Frame extends JFrame
{
public static void main(String[]args){
JFrame myFrame = new JFrame("MyFrame");
Panel myPanel = new Panel();
myFrame.add(myPanel);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,400);
myFrame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class Panel extends JPanel
{
JButton zero,one,two,three,four,five,six,seven,eight,nine,clear, negative,convert;
JRadioButton k2p,p2k;
JTextArea area;
ButtonGroup conversion;
public Panel() {
zero = new JButton("0");
one = new JButton("1");
two = new JButton("2");
three = new JButton("3");
four = new JButton("4");
five = new JButton("5");
six = new JButton("6");
seven = new JButton("7");
eight = new JButton("8");
nine = new JButton("9");
clear = new JButton("C");
negative = new JButton("-");
convert = new JButton("Convert");
area = new JTextArea();
conversion = new ButtonGroup();
conversion.add(k2p= new JRadioButton("Kilograms to Pounds"));
conversion.add(p2k= new JRadioButton("Pounds to Kilograms"));
setLayout(new BorderLayout());
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(5,3));
westPanel.add(zero);
westPanel.add(one);
westPanel.add(two);
westPanel.add(three);
westPanel.add(four);
westPanel.add(five);
westPanel.add(six);
westPanel.add(seven);
westPanel.add(eight);
westPanel.add(nine);
westPanel.add(negative);
westPanel.add(clear);
westPanel.add(convert);
add(westPanel,BorderLayout.CENTER);
}
}
GridLayout divides its space equally amongst all of its compoenents:
The GridLayout class is a layout manager that lays out a container's components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
(emphasis mine) Your alternatives are other layout managers, like GridBagLayout, GroupLayout or using a composite layout, which means nesting layout managers one inside the other.
Here I'll be using composite layouts by nesting the GridLayout inside a BorderLayout in the CENTER position and the convert button is in the PAGE_END position:
class Panel extends JPanel {
JButton[] numberButtons = new JButton[10];
JButton nine, clear, negative, convert;
public Panel() {
for (int i = 0; i < numberButtons.length; i++)
numberButtons[i] = new JButton(String.valueOf(i));
clear = new JButton("C");
negative = new JButton("-");
convert = new JButton("Convert");
setLayout(new BorderLayout());
JPanel westPanel = new JPanel(new BorderLayout());
JPanel buttonsPanel = new JPanel(new GridLayout(4, 3));
for (int i = 0; i < numberButtons.length; i++)
buttonsPanel.add(numberButtons[i]);
buttonsPanel.add(negative);
buttonsPanel.add(clear);
westPanel.add(buttonsPanel);
westPanel.add(convert, BorderLayout.PAGE_END);
add(westPanel, BorderLayout.CENTER);
}
}
I also created a JButton[] for the numbered buttons, it's usually a better choice. You can add the other buttons there too, but I think it will only be detrimental.
hello goodevening to all i have a problem on my program with the ScrollPane in my JList i cant put an JScrollPane in my list because i am using a panel instead of Container this is my code so far its all runnable the problem is if you enter a high number in the number of times the some output will not be able to see because of the size of my list . so this is the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultCen extends JFrame implements ActionListener
{
public static void main(String args [])
{
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.setSize(300,450);
}
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JList list = new JList();
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen()
{
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
l.setBounds(10,10,130,30);
l1.setBounds(10,40,130,30);
t1.setBounds(140,10,130,25);
t2.setBounds(140,40,130,25);
b.setBounds(60,90,75,30);
c.setBounds(150,90,75,30);
list.setBounds(30,140,220,220);
panel.add(t1);
panel.add(t2);
panel.add(l);
panel.add(l1);
panel.add(list);
panel.add(b);
panel.add(c);
getContentPane().add(panel);
b.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
int t3 = Integer.parseInt(t1.getText());
int t4 = Integer.parseInt(t2.getText());
m.addElement("The multiplication Table of "+t3);
for (int cc =1 ; cc <=t4; cc++ )
{
lab.setText(t3+"*"+cc+" = "+(t3*cc));
m.addElement(lab.getText());
list.setModel(m);
}
}
if(e.getSource() == c)
{
t1.setText("");
t2.setText("");
m.removeAllElements();
}
}
}
JScrollPane does not work with null Layout. Use BoxLayout or any other resizeable layout instead. This is the limitation of setLayout(null).
Use Layout managers. You've asked a lot of questions here and I'm sure a few you have been advised not to use null layout. Again here is the tutorial Laying out components Within a container. Learn to use them so you don't run into the million possible problems on the road ahead. This kind of problem being one of them.
here's an example of how you could achieve the same thing with layout managers, and some empty borders for white space.
With Layout Manager
Without Layout Manger
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MultCen extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.pack();
}
});
}
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen() {
JPanel topPanel = new JPanel(new GridLayout(2, 2, 0, 5));
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
topPanel.add(l);
topPanel.add(t1);
topPanel.add(l1);
topPanel.add(t2);
JPanel buttonPanel = new JPanel();
buttonPanel.add(b);
buttonPanel.add(c);
buttonPanel.setBorder(new EmptyBorder(10, 0, 10, 0));
JList list = new JList();
JScrollPane scroll = new JScrollPane(list);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(300, 300));
JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(scroll, BorderLayout.SOUTH);
panel.setBorder(new EmptyBorder(10, 15, 10, 15));
getContentPane().add(panel);
}
}
Side Notes
Run Swing apps from the Event Dispatch Thread. See Initial Threads
When you do decide to use layout managers, just pack() your frame instead of setSize()
Use better variable names.
See Extends JFrame vs. creating it inside the the program
I really didn't now how to form the question i have a gridlayout with 4 buttons. When the user press Add module i want under the buttons a form instead of a new windows if this is possible.
frame = new JFrame("ModuleViewer");
makeMenu(frame);
Container contentPane = frame.getContentPane();
// Specify the layout manager with nice spacing
contentPane.setLayout(new GridLayout(0, 2));
addModule = new JButton("Toevoegen Module");
contentPane.add(addModule);
overview = new JButton("Overzicht Modules");
contentPane.add(overview);
addSchoolweeks = new JButton("Aapassen schoolweken");
contentPane.add(addSchoolweeks);
weekheavy = new JButton("Weekbelasting");
contentPane.add(weekheavy);
frame.pack();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);
I know that i first need to add een action method for the buttons i know how to do that so that isn't important. I only want to know how i could create a layout under the buttons so when a user clicks the layout will be draw.
Each panel can only have one layout, but you can use multiple panels for the desired effect: a top panel using GridLayout to hold your buttons, and a bottom panel using CardLayout to hold multiple other panels, one for each button click. Each of these panels can use whatever layout you want, depending on its contents.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Red";
final static String CARD2 = "Green";
final static String CARD3 = "Blue";
JPanel cards;
CardLayout cardLayout;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}
public void run()
{
JButton btnRed = createButton("Red");
JButton btnGreen = createButton("Green");
JButton btnBlue = createButton("Blue");
JPanel buttons = new JPanel(new GridLayout(1,3));
buttons.add(btnRed);
buttons.add(btnGreen);
buttons.add(btnBlue);
JPanel card1 = new JPanel();
card1.setBackground(Color.RED);
JPanel card2 = new JPanel();
card2.setBackground(Color.GREEN);
JPanel card3 = new JPanel();
card3.setBackground(Color.BLUE);
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttons, BorderLayout.NORTH);
f.add(cards, BorderLayout.CENTER);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JButton createButton(final String name)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(cards, name);
}
});
return button;
}
}
I am using swing to build a GUI with 4 JPanels inside a JPanel using the BorderLayout manager:
A row of labels
A column of JButtons
A display area (it is a class that extends JPanel and has nothing added to it and is used as a drawing area)
Another column of buttons
My code looks like this:
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
middle.add(midLabels,BorderLayout.NORTH);
middle.add(pickupButtons,BorderLayout.WEST);
middle.add(simulation,BorderLayout.CENTER);
middle.add(dropButtons,BorderLayout.EAST);
The simulation panel is just an extended JPanel that overrides paintComponent to draw an image. The problem is, the simulation area is on the left and not in the middle:
What I actually want is:
Edit, here is an example, do I need to use a different layout manager to get the empty JPanel positioned correctly?:
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
final static int MAXFLOORS = 8;
public Test() {
setLayout(new BorderLayout());
setTitle("Simulator");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
JPanel simulation = new JPanel();
JPanel dropButtons = new JPanel();
JPanel pickupButtons = new JPanel();
pickupButtons.setLayout(new GridLayout(MAXFLOORS, 1));
dropButtons.setLayout(new GridLayout(MAXFLOORS, 1));
setLayout(new BorderLayout());
add(simulation,BorderLayout.CENTER);
add(dropButtons,BorderLayout.EAST);
add(pickupButtons,BorderLayout.WEST);
for (int i = MAXFLOORS; i != 0; i--) {
JButton pb = new JButton("F" + i);
dropButtons.add(pb);
JButton db = new JButton("F" + i);
dropButtons.add(db);
}
repaint();
}
public static void main(String[] args) {
new Test();
}
}
Look at your code:
for (int i = MAXFLOORS; i != 0; i--) {
final JButton pb = new JButton("F" + i);
dropButtons.add(pb);
final JButton db = new JButton("F" + i);
dropButtons.add(db);
}
You're adding onto dropButtons twice, instead of pickupButtons.