Learning to use MigLayout. I am trying to make a very simple form that is two columns, a label, a text input, repeat, until a submit button on the bottom that should span both columns. However it does not seem to be working as expected. The text fields are not spreading and neither is the button. It looks like this
Here is my code -
package com.mypackage;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.miginfocom.swing.MigLayout;
public class DiceOddCalculator extends JFrame {
public DiceOddCalculator(String title) {
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setTitle(title);
//Layout and panel to house components
MigLayout layout = new MigLayout("wrap 2, debug");
JPanel panel = new JPanel(layout);
//Components
JLabel maxDiceLabel = new JLabel("Max value of die");
JTextField maxDiceInput = new JTextField();
JLabel protectionCriteriaLabel = new JLabel("Die protection Criteria:");
JTextField protectionCriteriaInput = new JTextField("");
JLabel numOfDiceLabel = new JLabel("Number of dice:");
JTextField numOfDiceInput = new JTextField("");
JButton addDice = new JButton("Add dice");
//add to panel
panel.add(maxDiceLabel);
panel.add(maxDiceInput);
panel.add(protectionCriteriaLabel);
panel.add(protectionCriteriaInput);
panel.add(numOfDiceLabel);
panel.add(numOfDiceInput);
panel.add(addDice, "span");
//Turn window on
this.setContentPane(panel);
this.setVisible(true);
}
public static void main(String[] args) {
DiceOddCalculator f = new DiceOddCalculator("Dice Odds Simulator");
}
}
What needs to change in my code so that the JTextField and Button are the appropriate widths?
I figured out it had to do with how I was constructing MigLayout. Using
MigLayout layout = new MigLayout("wrap 2, debug", "[fill, grow]", "") made the component stretch across its column as I was expecting.
Related
package View;
import javax.swing.*;
import javax.swing.plaf.synth.ColorType;
import modulo.PatenteTypes;
import java.awt.*;
public class FrameLogin extends JFrame {
private static final long serialVersionUID = 1L;
Color Arancione = new Color(255, 150, 0);
public FrameLogin(String ArrayClienti[] ){
this.setTitle("BiKar Prenotazioni");
this.setSize(new Dimension(1000,600));
this.setBackground(Color.black);
this.setForeground(Color.black);
JPanel Pannello = new JPanel();
this.setLayout(new BorderLayout());
Pannello.setLayout(new BorderLayout());
Pannello.setBackground(Color.black);
Pannello.setForeground(Color.orange);
this.add(Pannello);
JComboBox TipoCliente = new JComboBox(ArrayClienti);
TipoCliente.setPreferredSize(new Dimension(200,250));
TipoCliente.setMaximumSize(TipoCliente.getPreferredSize());
TipoCliente.setSize(200, TipoCliente.getPreferredSize().height);
JTextField Nome = new JTextField();
JTextField Cognome = new JTextField();
JTextField ID = new JTextField();
JTextField Eta = new JTextField();
JComboBox<PatenteTypes> TipoPatente= new JComboBox<PatenteTypes>(PatenteTypes.values());
this.setLayout(new BorderLayout());
Pannello.setLayout(new BorderLayout());
this.setBackground(Color.black);
this.setForeground(Color.black);
this.add(Pannello);
this.add(Nome);
this.add(Cognome);
this.add(ID,BorderLayout.WEST);
this.add(Eta, BorderLayout.EAST);
this.add(TipoPatente,BorderLayout.CENTER);
this.add(TipoCliente,BorderLayout.NORTH);
TipoCliente.setBackground(Arancione);
TipoCliente.setForeground(Arancione);
Nome.setBackground(Arancione);
Nome.setForeground(Arancione);
Cognome.setBackground(Arancione);
Cognome.setForeground(Arancione);
ID.setBackground(Arancione);
ID.setForeground(Arancione);
Eta.setBackground(Arancione);
Eta.setForeground(Arancione);
TipoPatente.setBackground(Arancione);
TipoPatente.setForeground(Arancione);
this.setVisible(true);
Pannello.setVisible(true);
TipoCliente.setVisible(true);
ID.setVisible(true);
Eta.setVisible(true);
TipoPatente.setVisible(true);
Nome.setVisible(false);
Cognome.setVisible(false);
}
}
Result:
As you can see in the image the output are 2 very big ComboBox and no TextAreas at all.
I should have gotten 2 small ComboBox. one at the north, the other at the center, and 2 text ares at sides of the combobox at the center. thanks for your help.
I would like to be able to set their dimensione and their position ( I don't want this to be resizable).
also at the border you can see 2 orange lines. I think those where supposed to be the text areas, but all of the space was taken by the JComboBox
Stupid question, but I cant seem to find answer, and when I do it doesn't work. So i want to add new JPanel on already existing JPanel. Sometimes when i add it it just opens a new window when I run it, other times nothing happens. Anyways here is the code:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
new Main().setVisible(true);
}
private Main()
{
super("Vending machine");
JPanel p = new JPanel();
JLabel title = new JLabel("Vending machine: ");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("5");
JLabel label1 = new JLabel("Enter code: ");
JTextField text1= new JTextField(3);
JButton ok= new JButton("OK");
JButton button4 = new JButton("Return change");
JLabel label2 = new JLabel("Result is: ");
JTextField text2= new JTextField(3);
JLabel label3 = new JLabel("Current: ");
JTextField text3= new JTextField(3);
title.setBounds(200,5,250,80);
title.setFont (title.getFont ().deriveFont (22.0f));
p.add(title);
p.setLayout(null);
button1.setBounds(530,46,120,60);
p.add(button1);
button2.setBounds(530,172,120,60);
p.add(button2);
button3.setBounds(530,298,120,60);
p.add(button3);
label1.setBounds(555,414,120,60);
p.add(label1);
text1.setBounds(530,454,120,30);
p.add(text1);
ok.setBounds(530,550,120,60);
p.add(ok);
button4.setBounds(360,550,120,60);
p.add(button4);
label2.setBounds(230,530,120,60);
p.add(label2);
text2.setBounds(200,575,120,30);
p.add(text2);
label3.setBounds(50,530,120,60);
p.add(label3);
text3.setBounds(38,575,120,30);
p.add(text3);
getContentPane().add(p);
setSize(700,700);
setVisible(true);
}
}
I want to add new JPanel on this place: vending machine:
Thank you!
Even if you could do this, it will give you harm for every time you want another changes on this frame.
Instead of locating a JPanel into another JPanel, use layouts.
You shouldnt use static variables and a null layout.
Use appropriate layout managers. Maybe the main panel uses a BorderLayout. Then you add your main component to the CENTER and a second panel to the EAST. The second panel can also use a BorderLayout. You can then add the two components to the NORTH, CENTER or SOUTH as you require.
So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:
I am trying to build an app that has some components such as buttons, labels, text fields, a menu bar and a picture (I didn't tackle the image problem yet so there is no code for that).
So I made a grid layout for my frame and constructed 6 panels with their respective components as explained in the code bellow. But when I run it it doesn't show anything at first, just a blank frame, unless I maximize the window. Because when I do that everything appears to be working fine. Except for 2 things.
I have setVgap() and setHgap() to zero but there are still gaps between the components. and the 2nd thing is that the BorderLayout.NORTH, (..).SOUTH etc don't seem to work either.
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
public Window() {
super("Image Application");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
requestFocus();
// Setting Layout
GridLayout grid = new GridLayout(6, 0, 0, 0);
//grid.setVgap(0);
//grid.setHgap(0);
this.setLayout(grid);
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JLabel b2 = new JLabel("Width: ");
JLabel b3 = new JLabel("Height: ");
JTextField box1 = new JTextField(25);
JTextField box2 = new JTextField(25);
// Resize Button
JPanel p4 = new JPanel();
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p2.add(b2);
p2.add(box1);
p3.add(b3);
p3.add(box2);
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
this.add(menupanel);
this.add(p1, BorderLayout.NORTH);
this.add(p2, BorderLayout.SOUTH);
this.add(p3, BorderLayout.WEST);
this.add(p4, BorderLayout.EAST);
this.setJMenuBar(menubar);
pack();
setVisible(true);
}
public static void main(String args[]) {
Window w = new Window();
}
}
Any ideas?
~EDIT1 changed according to first 2 comments, the pack(); seems to fix the problem that i needed to maximise the window to see the comp's ( -Thanks ), but the setVgap() problem remains.
~EDIT2 when I run it this window is shown:
While I want it to look more like this:
AGAIN Ignore the picture
~EDIT3 Well, I changed the value that was passed in the constructor for the Hgap and it does change accordingly for different values but it seems that zero Hgap is still ~10 pixels wide?! Also I noted that the gap doesn't change between the menubar and the first Jbuttons, but only for the ret of the components.
~EDIT4 It also works for negative int's..?! I am lost here..
please to compare, you should using second parameter for GridLayout, then setVgap() will works (frame.setLayout(new GridLayout(6, 0, 5, 5));), here is only zero value,
Window is reserved word in Java for awt.Window, don't to use this Object name as class name
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
private JFrame frame = new JFrame("Image Application");
public MyWindow() {
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
p2.setBackground(Color.ORANGE);
JLabel b2 = new JLabel("Width: ");
p2.add(b2);
JTextField box1 = new JTextField(25);
p2.add(box1);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
JLabel b3 = new JLabel("Height: ");
JTextField box2 = new JTextField(25);
p3.add(b3);
p3.add(box2);
// Resize Button
JPanel p4 = new JPanel();
p4.setBackground(Color.MAGENTA);
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
frame.setLayout(new GridLayout(6, 0, 5, 5));
frame.add(menupanel);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.add(p4);
frame.setJMenuBar(menubar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyWindow w = new MyWindow();
}
});
}
}
okay ... my question is rather straight forward so I doubt ill need to add any code but I will if need be.
Whenever I create a GUI frame and add a couple of panels to it and run my application, the contents are not displayed until I either re-size the window or minimize it on the toolbar then restore it. What could be the cause of that and how can I solve it?
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public final class Calculator extends JFrame
{
//initialise various variables for use within the program
//BUTTONS
private final JButton additionButton = new JButton("+");
private final JButton subtractionButton = new JButton("-");
private final JButton divisionButton = new JButton("/");
private final JButton multiplicationButton = new JButton("*");
//PANELS
private JPanel operatorPanel;
private JPanel operandPanel;
//LABELS
private JLabel operationLabel;
//constructor to initialise the frame and add components into it
public Calculator()
{
super("Clancy's Calculator");
setLayout(new BorderLayout(5, 10));
setSize(370, 200);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
//create a message label to display the operation that has just taken place
operationLabel = new JLabel("YOU HAVE PERFORMED SOME OPERATION",SwingConstants.CENTER);
add(getOperatorPanel(), BorderLayout.NORTH);
add(getOperandPanel(), BorderLayout.CENTER);
add(operationLabel, BorderLayout.SOUTH);
}
//setter method for the operator panel
public void setOperatorPanel()
{
operatorPanel = new JPanel();
operatorPanel.setLayout(new FlowLayout());
operatorPanel.add(additionButton);
operatorPanel.add(subtractionButton);
operatorPanel.add(multiplicationButton);
operatorPanel.add(divisionButton);
}
//getter method for the operator panel
public JPanel getOperatorPanel()
{
setOperatorPanel();
return operatorPanel;
}
//setter method for operands panel
public void setOperandPanel()
{
operandPanel = new JPanel();
operandPanel.setLayout(new GridLayout(3, 2, 5, 5));
//LABELS
JLabel operandOneLabel = new JLabel("Enter the first Operand: ");
JLabel operandTwoLabel = new JLabel("Enter the second Operand: ");
JLabel answerLabel = new JLabel("ANSWER: ");
//TEXT FIELDS
JTextField operandOneText = new JTextField(); //retrieves one operand
JTextField operandTwoText = new JTextField(); //retrieves another operand
JTextField answerText = new JTextField(); //displays answer
answerText.setEditable(false); //ensure the answer field is not editable
operandPanel.add(operandOneLabel);
operandPanel.add(operandOneText);
operandPanel.add(operandTwoLabel);
operandPanel.add(operandTwoText);
operandPanel.add(answerLabel);
operandPanel.add(answerText);
}
//getter method for operand panel
public JPanel getOperandPanel()
{
setOperandPanel();
return operandPanel;
}
/** main method */
public static void main(String[] args)
{
new Calculator();
}
}
I notice you're programatically setting a new layout manager. Whenever you add, remove or change a java gui, you need to call invalidate() or revalidate() to make java re-create the GUI. See if calling invalidate() before setVisible(true) fixes the problem