In my project, I use Swing controls. I had used a label together with a button group, but there is an unwanted line. Please help. There is a label associated with each radio button group. The unwanted line is there.how to add the labels and corresponding radio button group to the same panel
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new FlowLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
panlabels.add(aLabel, BorderLayout.WEST);
panlabels.add(bLabel, BorderLayout.CENTER);
panlabels.add(cLabel, BorderLayout.CENTER);
panlabels.add(dLabel, BorderLayout.CENTER);
panlabels.add(eLabel, BorderLayout.CENTER);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
pancontrols.add(choice[i], BorderLayout.WEST);
}
choice[4].setVisible(true);
panEast.add("West", panlabels);
panEast.add("West", pancontrols);
pa.add("Center", panEast);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
First, your naming convention for the choice labels is off. qLabel="questions", aLabel="questions", bLabel="a", cLabel="b", etc. I would suggest you fix that to eliminate confusion and make your code more readable (ie only have one label that is a question).
Second, your use of panEast.add("West",panlabels); and the other two statements is generally not suggested. Read up on BorderLayout to find the more accepted method of doing this:
http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
As for your problem, I have rewritten your code so things do line up, I will try to point out what I commented out to help:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
//JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 2, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new BorderLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
//pancontrols.add(new JLabel(""));
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
}
pancontrols.add(qLabel);
pancontrols.add(ques);
pancontrols.add(bLabel);
pancontrols.add(choice[1]);
pancontrols.add(cLabel);
pancontrols.add(choice[2]);
pancontrols.add(dLabel);
pancontrols.add(choice[3]);
pancontrols.add(eLabel);
pancontrols.add(choice[4]);
pancontrols.setSize(400,200);
choice[4].setVisible(true);
pa.add(pancontrols);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
Basically, I removed your unnecessary panels. the only panel you add stuff to now is the pancontrols panel. I changed it to new JPanel(new Gridlayout(0,2,0,60)). With the two column GridLayout you will always have things line up bound wise, due to GridLayout making everything the same size.
Lastly I pulled the adding of choices[] from the loop and did that along with the labels to make sure things line up. I removed all the panels being added except the pancontrols being added to pa, which I assume you want to add more question panels to pa in that case. That covers your question in particular, but there is quite a lot of stuff you should do (ie use choice[0] for example, eliminate unused labels and panels, etc.)
Related
this has seriously been the biggest issue in my code. I just want to create a simple pizza order taker using multiple panels. I want to be able to dictate the specific area each panel is located. Can someone please just pretend I'm a complete idiot and help me point this out?
I've attached my code as well as an image of how it looks so far. I want to be able to place individual segments like getting the user's information, choosing pizza size, then toppings, then a section where I will display the receipt with all of the order total.
I can do the calculations and take in values, I just need to figure out the appearance.
import javax.swing.*;
import java.awt.*;
public class PIZZA extends JFrame {
Container window = getContentPane();
ButtonGroup ordertype;
JRadioButton delivery, takeout;
JRadioButton small, medium, large;
JLabel fname, phonenum, zipcode;
JTextField ufname, uphonenum, uzipcode;
JPanel userinfoinput;
JPanel delivery_type;
JPanel userinfolabel;
JButton start;
BoxLayout userbox, labelbox, deliverybox;
ImageIcon starticon = new ImageIcon("start.png");
public PIZZA() {
}
public static void main(String[] args){
PIZZA frame = new PIZZA();
new PIZZA();
frame.setSize(new Dimension(600,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("KRUSTY KRAB PIZZA");
frame.deliverymethod();
frame.getuserinfo();
frame.userinfolabels();
frame.getpizzasize();
frame.toppings_meat();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
private void deliverymethod(){
delivery_type = new JPanel();
ordertype = new ButtonGroup();
delivery = new JRadioButton("Delivery (Currently Unavailable)");
delivery.setEnabled(false);
takeout = new JRadioButton("Take Out");
ordertype.add(takeout);
ordertype.add(delivery);
delivery_type.add(takeout);
delivery_type.add(delivery);
delivery_type.setSize(100,100);
window.add(delivery_type,BorderLayout.NORTH);
}
private void getuserinfo(){
userinfoinput = new JPanel();
//start = new JButton("Start", starticon);
//start.setLayout(null);
ufname = new JTextField(12);
uphonenum = new JTextField(12);
uzipcode = new JTextField(12);
userinfoinput.add(ufname);
userinfoinput.add(uphonenum);
userinfoinput.add(uzipcode);
//userinfoinput.add(start);
GridLayout lay = new GridLayout(3,1);
userinfoinput.setLayout(lay);
window.add(userinfoinput, BorderLayout.CENTER);
}
private void userinfolabels(){
userinfolabel = new JPanel();
fname = new JLabel("First Name");
phonenum = new JLabel("Phone Number");
zipcode = new JLabel("Zip Code");
userinfolabel.add(fname);
userinfolabel.add(zipcode);
userinfolabel.add(phonenum);
labelbox = new BoxLayout(userinfolabel, BoxLayout.Y_AXIS);
GridLayout label = new GridLayout(3,1);
userinfolabel.setLayout(label);
window.add(userinfolabel, BorderLayout.CENTER);
}
private void getpizzasize(){
JPanel pizzasize = new JPanel();
ButtonGroup size = new ButtonGroup();
small = new JRadioButton("Small");
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
size.add(small);
size.add(medium);
size.add(large);
pizzasize.add(small);
pizzasize.add(medium);
pizzasize.add(large);
pizzasize.setLayout(new FlowLayout());
pizzasize.setSize(100,100);
window.add(pizzasize, BorderLayout.SOUTH);
}
private void toppings_meat(){
JPanel meat = new JPanel();
meat.setLayout(new BoxLayout(meat, BoxLayout.Y_AXIS));
JCheckBox pepperoni = new JCheckBox("Pepperoni");
JCheckBox meatball = new JCheckBox("Meatball");
JCheckBox chicken = new JCheckBox("Grilled Chicken");
JCheckBox sausage = new JCheckBox("Italian Sausage");
JCheckBox bacon = new JCheckBox("Bacon");
meat.add(pepperoni);
meat.add(meatball);
meat.add(chicken);
meat.add(sausage);
meat.add(bacon);
window.add(meat);
}
}
This pizza GUI uses several Swing layout managers in different JPanels.
The main layout managers that I want to talk about are the JFrame BorderLayout and the input form GridBagLayout.
A BorderLayout is rather flexible in that you can put Swing components in various locations. The JPanels I created for this GUI are in the BEFORE_FIRST_LINE, CENTER, AFTER_LAST_LINE, and AFTER_LINE_ENDS positions of the BorderLayout.
The input form uses a GridBagLayout to position the JLabels and the input JTextFields in a column. The GridBagLayout is more flexible than a GridLayout because the grid cells don't have to be the same size in a GridBagLayout.
The Oracle Swing tutorial A Visual Guide to Layout Managers shows the different Swin layout managers, and how to use them.
Here's the code I used to create the pizza GUI. I created each subordinate JPanel in a separate method. All of the JFrame code is in the run method. Separating different parts of the GUI allows me to focus on one part of the GUI at a time. I can test each JPanel method separately.
I create the Swing components from left to right, top to bottom within a JPanel. This allows me to visually verify that I've included all the appropriate methods for a component. This also allows me to zero in on any component that isn't correct.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PizzaOrdering implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PizzaOrdering());
}
#Override
public void run() {
JFrame frame = new JFrame("KRUSTY KRAB PIZZA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getDeliveryMethodPanel(),
BorderLayout.BEFORE_FIRST_LINE);
frame.add(getUserInformationPanel(),
BorderLayout.CENTER);
frame.add(getPizzaSizePanel(),
BorderLayout.AFTER_LAST_LINE);
frame.add(getMeatToppingsPanel(),
BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getDeliveryMethodPanel() {
JPanel deliveryMethodPanel = new JPanel(new FlowLayout());
ButtonGroup orderTypeGroup = new ButtonGroup();
JRadioButton takeoutRadioButton =
new JRadioButton("Take Out");
orderTypeGroup.add(takeoutRadioButton);
deliveryMethodPanel.add(takeoutRadioButton);
JRadioButton deliveryRadioButton =
new JRadioButton("Delivery (Currently Unavailable)");
deliveryRadioButton.setEnabled(false);
orderTypeGroup.add(deliveryRadioButton);
deliveryMethodPanel.add(deliveryRadioButton);
return deliveryMethodPanel;
}
private JPanel getUserInformationPanel() {
JPanel userInformationPanel = new JPanel(new GridBagLayout());
userInformationPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1d;
JLabel nameLabel = new JLabel("First Name:");
userInformationPanel.add(nameLabel, gbc);
gbc.gridx++;
JTextField userNameField = new JTextField(20);
userInformationPanel.add(userNameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel phoneNumberLabel = new JLabel("Phone Number:");
userInformationPanel.add(phoneNumberLabel, gbc);
gbc.gridx++;
JTextField userPhoneNumberField = new JTextField(20);
userInformationPanel.add(userPhoneNumberField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel zipCodeLabel = new JLabel("Zip Code:");
userInformationPanel.add(zipCodeLabel, gbc);
gbc.gridx++;
JTextField userZipCodeField = new JTextField(20);
userInformationPanel.add(userZipCodeField, gbc);
return userInformationPanel;
}
private JPanel getPizzaSizePanel() {
JPanel pizzaSizePanel = new JPanel(new FlowLayout());
ButtonGroup sizeGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton("Small");
sizeGroup.add(smallRadioButton);
pizzaSizePanel.add(smallRadioButton);
JRadioButton mediumRadioButton = new JRadioButton("Medium");
sizeGroup.add(mediumRadioButton);
pizzaSizePanel.add(mediumRadioButton);
JRadioButton largeRadioButton = new JRadioButton("Large");
sizeGroup.add(largeRadioButton);
pizzaSizePanel.add(largeRadioButton);
return pizzaSizePanel;
}
private JPanel getMeatToppingsPanel() {
JPanel meatToppingsPanel = new JPanel();
meatToppingsPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
meatToppingsPanel.setLayout(new BoxLayout(
meatToppingsPanel, BoxLayout.Y_AXIS));
JCheckBox pepperoniCheckBox = new JCheckBox("Pepperoni");
meatToppingsPanel.add(pepperoniCheckBox);
JCheckBox meatballCheckBox = new JCheckBox("Meatball");
meatToppingsPanel.add(meatballCheckBox);
JCheckBox chickenCheckBox = new JCheckBox("Grilled Chicken");
meatToppingsPanel.add(chickenCheckBox);
JCheckBox sausageCheckBox = new JCheckBox("Italian Sausage");
meatToppingsPanel.add(sausageCheckBox);
JCheckBox baconCheckBox = new JCheckBox("Bacon");
meatToppingsPanel.add(baconCheckBox);
return meatToppingsPanel;
}
}
I have the GUI displaying properly for the most part, except for one thing. The TitledBorder("Numeric Type") does not display the entire title for the right JPanel. I believe it has something to do with the BorderLayout Manager. Instead of displaying "Numeric Type" within the border, just "Numeric..." displays. Any help will be greatly appreciated.
public class P3GUI extends JFrame {
private JLabel originalList;
private JTextField originalSort;
private JLabel sortedList;
private JTextField newSort;
private JPanel panel;
private JButton performSort;
private JRadioButton ascending;
private JRadioButton descending;
private ButtonGroup sort;
private JRadioButton integer;
private JRadioButton fraction;
private ButtonGroup numType;
private JPanel inputPanel, outputPanel, calculatePanel, radioPanel;
private JPanel left, right;
public P3GUI () {
super("Binary Search Tree Sort");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
originalList = new JLabel("Original List");
originalSort = new JTextField(20);
inputPanel = new JPanel();
inputPanel.add(originalList);
inputPanel.add(originalSort);
sortedList = new JLabel("Sorted List");
newSort = new JTextField(20);
newSort.setEditable(false);
outputPanel = new JPanel();
outputPanel.add(sortedList);
outputPanel.add(newSort);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(inputPanel);
panel.add(outputPanel);
add(panel, BorderLayout.NORTH);
performSort = new JButton("Perform Sort");
calculatePanel = new JPanel();
calculatePanel.add(performSort);
add(calculatePanel, BorderLayout.CENTER);
ascending = new JRadioButton("Ascending");
descending = new JRadioButton("Descending");
sort = new ButtonGroup();
sort.add(ascending);
sort.add(descending);
integer = new JRadioButton("Integer");
fraction = new JRadioButton("Fraction");
numType = new ButtonGroup();
numType.add(integer);
numType.add(fraction);
radioPanel = new JPanel();
radioPanel.setLayout(new FlowLayout());
left = new JPanel();
left.setLayout(new GridLayout(2,1));
left.setBorder(BorderFactory.createTitledBorder("Sort Order"));
left.add(ascending);
left.add(descending);
right = new JPanel();
right.setLayout(new GridLayout(2,1));
right.setBorder(BorderFactory.createTitledBorder("Numeric Type"));
right.add(integer);
right.add(fraction);
radioPanel.add(left);
radioPanel.add(right);
add(radioPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new P3GUI().setVisible(true);
}
});
}
}
The problem is that the right JPanel is too small to display the entire title, and so it gets truncated. I'd suggest placing the bottom two JPanels into another that uses GridLayout, and then place them in such a way that they expand to fit the bottom of your GUI. When spread out, the title has a much greater chance of being fully displayed (but not a guarantee, mind you!).
For example, if you make the main GUI use a BorderLayout, and add this GridLayout using JPanel into the BorderLayout.CENTER position, it will fill it completely. Then the top components, the TextFields and JButton can be added to another JPanel, say one that uses a GridBagLayout, and add that to the main JPanel's BorderLayout.PAGE_START position.
For example, the following code produces this GUI:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class P3GUI2 extends JPanel {
private static final int COLS = 20;
private JTextField originalSort = new JTextField(COLS);
private JTextField newSort = new JTextField(COLS);
private JButton performSort = new JButton("Perform Sort");
private JRadioButton ascending = new JRadioButton("Ascending");
private JRadioButton descending = new JRadioButton("Descending");
private ButtonGroup sort = new ButtonGroup();
private JRadioButton integer = new JRadioButton("Integer");
private JRadioButton fraction = new JRadioButton("Fraction");
private ButtonGroup numType = new ButtonGroup();
public P3GUI2() {
JPanel topPanel = new JPanel(new GridBagLayout());
topPanel.add(new JLabel("Original List:"), createGbc(0, 0));
topPanel.add(originalSort, createGbc(1, 0));
topPanel.add(new JLabel("Sorted List:"), createGbc(0, 1));
topPanel.add(newSort, createGbc(1, 1));
performSort.setMnemonic(KeyEvent.VK_P);
JPanel btnPanel = new JPanel();
btnPanel.add(performSort);
JPanel sortOrderPanel = createTitlePanel("Sort Order");
JPanel numericPanel = createTitlePanel("Numeric Type");
sortOrderPanel.add(ascending);
sortOrderPanel.add(descending);
sort.add(ascending);
sort.add(descending);
numericPanel.add(integer);
numericPanel.add(fraction);
numType.add(integer);
numType.add(fraction);
JPanel radioPanels = new JPanel(new GridLayout(1, 0, 3, 3));
radioPanels.add(sortOrderPanel);
radioPanels.add(numericPanel);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(topPanel, BorderLayout.PAGE_START);
add(btnPanel, BorderLayout.CENTER);
add(radioPanels, BorderLayout.PAGE_END);
}
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new GridLayout(0, 1, 3, 3));
panel.setBorder(BorderFactory.createTitledBorder(title));
return panel;
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
return gbc;
}
private static void createAndShowGui() {
P3GUI2 mainPanel = new P3GUI2();
JFrame frame = new JFrame("Binary Search Tree Sort");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Or you could place the above btnPanel into the main one BorderLayout.CENTER and then place the radioPanels into the main one BorderLayout.PAGE_END. This will display a GUI of the same appearance but it will expand differently if re-sized.
The preferred size of the panel (as determined by the layout manager) does not consider the size of the text in the TitledBorder so the title can get truncated.
Here is a custom JPanel that can be used with a TitleBorder. The getPreferredSize() method has been customized to use the maximum width of:
the default getPreferredSize() calculation
the width of the text in the TitledBorder
Here is a simple example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderPanel extends JPanel
{
/**
** The preferred width on the panel must consider the width of the text
** used on the TitledBorder
*/
#Override
public Dimension getPreferredSize()
{
Dimension preferredSize = super.getPreferredSize();
Border border = getBorder();
int borderWidth = 0;
if (border instanceof TitledBorder)
{
Insets insets = getInsets();
TitledBorder titledBorder = (TitledBorder)border;
borderWidth = titledBorder.getMinimumSize(this).width + insets.left + insets.right;
}
int preferredWidth = Math.max(preferredSize.width, borderWidth);
return new Dimension(preferredWidth, preferredSize.height);
}
private static void createAndShowGUI()
{
JPanel panel = new TitledBorderPanel();
panel.setBorder( BorderFactory.createTitledBorder("File Options Command List:") );
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS) );
panel.add( new JLabel("Open") );
panel.add( new JLabel("Close") );
// panel.add( new JLabel("A really wierd file option longer than border title") );
JFrame frame = new JFrame("TitledBorderPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
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:
this is my first time here.
I was writing a GUI-driven program which would allow me to perform Caesar's cipher on .txt files.
However, before I could add the ActionListeners and ChangeListeners I decided to test the GUI. Here is what I got:
Here is the code:
package implementation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Frame extends JFrame{
public Frame(){
super("Caesar[E]");
this.setVisible(true);
this.setLocationRelativeTo(null);
/*Adding the options to GUI*/
factor.setPreferredSize(new Dimension(30,30));
JToolBar toolbar = new JToolBar();
radio.add(encrypt);
radio.add(decrypt);
toolbar.add(encrypt);
toolbar.add(decrypt);
toolbar.add(factor);
toolbar.setFloatable(false);
/*Adding the JTextArea for input*/
Box inputBound = Box.createHorizontalBox();
Box inputBound_text = Box.createVerticalBox();
Box inputBound_buttons = Box.createVerticalBox();
inputScroll.add(input);
inputScroll.setEnabled(true);
input.setEditable(true);
inputScroll.setBorder(BorderFactory.createTitledBorder("Text/File for Encryption/" +
"Decryption"));
inputBound_text.add(inputScroll);
inputBound_buttons.add(openFile);
inputBound_buttons.add(cancelFileInput);
inputBound.add(inputBound_text);
inputBound.add(Box.createHorizontalStrut(25));
inputBound.add(inputBound_buttons);
/*Adding JTextArea for output*/
Box outputBound = Box.createHorizontalBox();
Box outputBound_text = Box.createVerticalBox();
Box outputBound_buttons = Box.createVerticalBox();
outputScroll.add(output);
output.setEditable(true);
outputScroll.setBorder(BorderFactory.createTitledBorder("Text After Encryption" +
"/Decryption"));
outputBound_text.add(outputScroll);
outputBound_buttons.add(saveFile);
outputBound_buttons.add(send);
outputBound.add(outputBound_text);
outputBound.add(Box.createHorizontalStrut(25));
outputBound.add(outputBound_buttons);
outputBound.setSize(150, 200);
/*Adding JButton for performing the action*/
this.add(performAction,BorderLayout.SOUTH);
/*Adding the components to the Frame*/
Box outerBox = Box.createVerticalBox();
outerBox.add(toolbar,BorderLayout.NORTH);
outerBox.add(inputBound);
outerBox.add(outputBound);
this.add(outerBox);
this.setSize(500, 700);
}
boolean isFileInput = false;
boolean isEncrypt = true;
JButton performAction = new JButton("Encrypt!");
JButton openFile = new JButton("Open a File");
JButton cancelFileInput = new JButton("Cancel File Input");
JButton saveFile = new JButton("Save File");
JButton send = new JButton("Send");
JTextArea input = new JTextArea();
JTextArea output = new JTextArea();
JFileChooser chooser = new JFileChooser();
JScrollPane inputScroll = new JScrollPane();
JScrollPane outputScroll = new JScrollPane();
ButtonGroup radio = new ButtonGroup();
JRadioButton encrypt = new JRadioButton("Encrypt",true);
JRadioButton decrypt = new JRadioButton("Decrypt",false);
JSpinner factor = new JSpinner(new SpinnerNumberModel(1,1,26,1));
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new Frame();
}
});
}
}
Can you please tell me how I can solve the problems as shown in the image?
I know I can use setPreferredSize() but how do I make sure that I enter the correct dimension without trial-and-error?
I like the SpringLayout, it is very flexible and there is very not a lot that it can't do. Especially you will not need to care about setPreferredSize anymore. Just search for it, there are enough resources out there.
SpringLayout allows you to define the size of elements relative to others - so for example, you can make sure the buttons will look the same.
I would recommend MiGLayout as LayoutManager. Things like that are easy in MiGLayout
Trial-and-error is never a good way to get the layout you want. Instead, use the JTextArea constructor that lets you say how many rows and columns you want.
JTextArea(int rows, int columns)
JTextArea will calculate a good preferred size for when you pack() the window, and you won't need setSize().
Edit: You said, "JTextArea is inactive. I can't enter text in it."
Instead of add(), use setViewportView():
inputScroll.setViewportView(input);
...
outputScroll.setViewportView(output);
...
In situations like these, I like to divide my application into areas of responsibility. This keeps the code clean and self contained, allowing me to replace sections of it if/and when required, without adversely effect the rest of the application.
It also means that you can focus on the individual requirements of each section.
With complex layout, it's always better (IMHO) to use compounding containers with separate layout managers, it reduces the complexity and potential for strange cross over behavior.
public class BadLayout07 {
public static void main(String[] args) {
new BadLayout07();
}
public BadLayout07() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
public MasterPane() {
EncryptSettings encryptSettings = new EncryptSettings();
InputPane inputPane = new InputPane();
OutputPane outputPane = new OutputPane();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(encryptSettings, gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
add(inputPane, gbc);
gbc.gridy++;
add(outputPane, gbc);
}
}
public class EncryptSettings extends JPanel {
private JRadioButton encrypt;
private JRadioButton decrypt;
private JSpinner factor;
public EncryptSettings() {
encrypt = new JRadioButton("Encrypt");
decrypt = new JRadioButton("Decrypt");
ButtonGroup bg = new ButtonGroup();
bg.add(encrypt);
bg.add(decrypt);
factor = new JSpinner(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1)));
setLayout(new FlowLayout(FlowLayout.LEFT));
add(encrypt);
add(decrypt);
add(factor);
}
}
public class InputPane extends JPanel {
private JTextArea input;
private JButton open;
private JButton close;
public InputPane() {
setBorder(new TitledBorder("Source Text"));
input = new JTextArea();
open = new JButton("Open");
close = new JButton("Close");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(open);
tb.add(close);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(input));
}
}
public class OutputPane extends JPanel {
private JTextArea output;
private JButton save;
private JButton send;
public OutputPane() {
setBorder(new TitledBorder("Encrypted Text"));
output = new JTextArea();
output.setEditable(false);
save = new JButton("Save");
send = new JButton("Send");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(save);
tb.add(send);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(output));
}
}
}
I've not interconnect any of the functionality, but it is a simple case of providing appropriate setters and getters as required, as well appropriate event listeners.
I'm making a program that asks for an integer from the user, it then should display a new window like this depending on how big the integer is.
This would be the layout if the user entered 2:
Enter test score: JTextField over here
Enter test score: JTextField over here
Reset Submit
For some reason I can't make the grid layout in java have only 2 columns per row.
Here is my code:
public void createAverageGUI()
{
averageFrame = new JFrame("Get All Test Scores");
txtAllAverages = new JTextField[testCount];
averageFrame.setLayout(new GridLayout(2, testCount));
for (int i = 0; i < testCount; i++)
{
averageFrame.add(new JLabel("Enter test score: "));
JTextField field = new JTextField(10);
averageFrame.add(field);
txtAllAverages[i] = field;
}
averageFrame.add(resetAverages);
averageFrame.add(submitAverages);
averageFrame.setSize(400, 600);
averageFrame.setVisible(true);
}
What this GUI really needs is an entirely different layout. Here is how your planned GUI would look.
Here is how it should probably be laid out.
ExcellentGUI.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class ExcellentGUI {
private JTextField[] txtAllAverages;
int testCount = 2;
public void createAverageGUI()
{
txtAllAverages = new JTextField[testCount];
JPanel inputControls = new JPanel(new BorderLayout(5,5));
JPanel inputControlsLabels = new JPanel(new GridLayout(0,1,3,3));
JPanel inputControlsFields = new JPanel(new GridLayout(0,1,3,3));
inputControls.add(inputControlsLabels, BorderLayout.WEST);
inputControls.add(inputControlsFields, BorderLayout.CENTER);
for (int i = 0; i < testCount; i++)
{
inputControlsLabels.add(new JLabel("Test score: "));
JTextField field = new JTextField(10);
inputControlsFields.add(field);
txtAllAverages[i] = field;
}
JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,2));
controls.add(new JButton("Reset"));
controls.add(new JButton("Submit"));
JPanel gui = new JPanel(new BorderLayout(10,10));
gui.setBorder(new TitledBorder("Averages"));
gui.add(inputControls, BorderLayout.CENTER);
gui.add(controls, BorderLayout.SOUTH);
JFrame averageFrame = new JFrame("Get All Test Scores");
averageFrame.setContentPane(gui);
// let the components assume the natural size
// averageFrame.setSize(400, 600);
averageFrame.pack();
averageFrame.setLocationByPlatform(true);
averageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
averageFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ExcellentGUI().createAverageGUI();
}
});
}
}
You understand that this new GridLayout(2, testCount) means two rows and testCount columns, which isn't what I think you want. I strongly urge you to read the GridLayout API to see exactly how this and the other constructors work.
You can simplify things greatly by making your layout new GridLayout(0, 2); which means any number of rows and always 2 columns.