GUI becomes untidy - java

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.

Related

How to control where in my window or JFrame panels appear

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;
}
}

How can I get the contents of my GUI to look a certain way? (Java)

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:

Java Swing - JPanel centering issue

Basically, this is the structure of my Window.
The actual window looks like this:
My problem is that I want the MainPanel with the ComboBox and and the rest to fit the JFrame window. Stretch horizontally and stick to the top. But I've tried all kinds of layouts (Box, GridBag, Grid). It just remains centered. How do I achieve this?
Here is the MVCC:
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class simplelayout{
JFrame mainFrame;
JPanel mainPanel;
JPanel innerPanel;
JPanel createDomainPanel;
JPanel listDomainPanel = new JPanel(new GridBagLayout());
String comboBoxItems[]={"Create Domain","List Domains"};
#SuppressWarnings("rawtypes")
JComboBox listCombo;
JButton goBtn;
CardLayout layout;
JTextField domainName = new JTextField();
JLabel successMessage = new JLabel("");
public simplelayout(){
initialize();
setCardLayout();
}
#SuppressWarnings({ "rawtypes", "unchecked" })
private void setCardLayout() {
innerPanel = new JPanel();
//innerPanel.setSize(600, 400);
layout = new CardLayout(10,10);
innerPanel.setLayout(layout);
//Default Panel
JPanel defaultPanel = new JPanel(new FlowLayout());
defaultPanel.add(new JLabel("Welcome to Amazon Simple DB"));
//Create Domain Panel
createDomainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//createDomainPanel.setSize(600, 300);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=0;
createDomainPanel.add(new JLabel("Enter the name of the domain"), gbc);
gbc.gridx=0;
gbc.gridy=1;
createDomainPanel.add(domainName, gbc);
JPanel result = new JPanel(new FlowLayout());
result.add(successMessage);
gbc.anchor=GridBagConstraints.LAST_LINE_START;
gbc.gridx=0;
gbc.gridy=2;
createDomainPanel.add(result, gbc);
//List Domain Panel
listDomainPanel.add(new JLabel("List of Domains"), gbc);
//Add to innerPanel
innerPanel.add(defaultPanel, "Default");
innerPanel.add(createDomainPanel, "Create Domain");
innerPanel.add(listDomainPanel, "List Domain");
layout.show(innerPanel, "Default");
DefaultComboBoxModel panelName = new DefaultComboBoxModel();
panelName.addElement("Create Domain");
panelName.addElement("List Domain");
listCombo = new JComboBox(panelName);
listCombo.setSelectedIndex(0);
JScrollPane listComboScroll = new JScrollPane(listCombo);
goBtn = new JButton("Go");
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.fill=GridBagConstraints.HORIZONTAL;
gbc1.anchor=GridBagConstraints.FIRST_LINE_START;
gbc1.gridx = 0;
gbc1.gridx = 0;
mainPanel.add(listComboScroll, gbc1);
gbc1.gridy = 1;
mainPanel.add(goBtn, gbc1);
gbc1.gridy = 2;
mainPanel.add(innerPanel, gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.fill=GridBagConstraints.HORIZONTAL;
gbc2.anchor=GridBagConstraints.FIRST_LINE_START;
JScrollPane scr = new JScrollPane(mainPanel);
mainPanel.setSize(mainFrame.getPreferredSize());
mainFrame.add(scr, gbc);
mainFrame.setVisible(true);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
private void initialize() {
mainFrame = new JFrame("Amazon Simple DB");
mainFrame.setSize(700, 500);
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
//mainPanel.setLayout(new GridLayout(8,1));
mainFrame.setVisible(true);
}
public static void main(String[] args) {
try {
//UIManager.put("nimbusBase", new Color(178,56,249));
//UIManager.put("nimbusBlueGrey", new Color(102,212,199));
//UIManager.put("control", new Color(212,133,102));
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new simplelayout();
}
});
}
}
It sounds like you want to use the application frame's default BorderLayout, placing the combobox & button components in a nested panel in the BorderLayout.PAGE_START location with the innerPanel in the CENTER position.
Try to add a mainFrame.pack(); in the initialize() and the setCardLayout()methods, Remove all mainFrame.setSize() and mainPanel.setSize() methods.

Unwanted line between labels and radio group in Java

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.)

Creating Java dialogs

What would be the easiest way for creating a dialog:
in one window I'm giving data for envelope addressing, also set font type from list of sizes
when clicked OK, in the same window or in next window I get preview of how the envelope would look like with the given names, and used selected font size
It should look similarly to:
alt text http://img15.imageshack.us/img15/7355/lab10aa.gif
Should I use Jdialog? Or will JOptionPane will be enough? The next step will be to choose color of font and background so I must keep that in mind.
This should get you going.
class TestDialog extends JDialog {
private JButton okButton = new JButton(new AbstractAction("ok") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked ok");
// SHOW THE PREVIEW...
setVisible(false);
}
});
private JButton cancelButton = new JButton(new AbstractAction("cancel") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked cancel");
setVisible(false);
}
});
private JTextField nameField = new JTextField(20);
private JTextField surnameField = new JTextField();
private JTextField addr1Field = new JTextField();
private JTextField addr2Field = new JTextField();
private JComboBox sizes = new JComboBox(new String[] { "small", "large" });
public TestDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, "Envelope addressing", modal);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
JPanel buttons = new JPanel(new FlowLayout());
buttons.add(okButton);
buttons.add(cancelButton);
mainPanel.add(buttons);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
public String getAddr1() {
return addr1Field.getText();
}
// ...
}
Result:
If you need to use JOptionPane :
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
private static JTextField nameField = new JTextField(20);
private static JTextField surnameField = new JTextField();
private static JTextField addr1Field = new JTextField();
private static JTextField addr2Field = new JTextField();
private static JComboBox sizes = new JComboBox(new String[] { "small", "medium", "large", "extra-large" });
public Main(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
String[] buttons = { "OK", "Cancel"};
int c = JOptionPane.showOptionDialog(
null,
mainPanel,
"My Panel",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
buttons,
buttons[0]
);
if(c ==0){
new Envelope(nameField.getText(), surnameField.getText(), addr1Field.getText()
, addr2Field.getText(), sizes.getSelectedIndex());
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
You will need to use JDialog. No point messing about with JOptoinPane - it's not meant for gathering more than a simple string. Additionally, use either MigLayout, TableLayout, or JGoodies forms - it will help you get a nice layout that's easy to code.
If it is allowed to use a GUI builder I would recommend you IntelliJ IDEA's
You can create something like that in about 5 - 10 mins.
If that's not possible ( maybe you want to practice-learn-or-something-else ) I would use a JFrame instead ) with CardLayout
Shouldn't be that hard to do.
You can use JOptionPane. You can add any Swing component to it.
Create a panel with all the components you need except for the buttons and then add the panel to the option pane. The only problem with this approach is that focus will be on the buttons by default. To solve this problem see the solution presented by Dialog Focus.

Categories

Resources