Related
I'm trying to learn swing and work through the task we have been given. I can't see why the code doesn't display the JButtons in the SOUTH section as there is no issue when displaying the textfields, combobox and labels in the CENTER section.
I used the same format to add components to my CENTER section as I did in the SOUTH and EAST but only the center displays anything.
public class ProductListGUI{
JMenu menu;
JMenuItem about,importData,inventory,export;
ProductListGUI(){
JFrame f = new JFrame("Assignment 2");
JPanel p1 = new JPanel();
JList<String> list = new JList<>();
list.setBounds(600,0,200,600);
JScrollPane scrollPane = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel p3 = new JPanel();
p1.setLayout(null);
p1.setBounds(0,0,600,500);
p1.setBackground(new Color(230,230,230));
scrollPane.setLayout(null);
scrollPane.setBounds(600,0,200,500);
p3.setLayout(null);
p3.setBounds(0,500,800,100);
p3.setBackground(new Color(230,230,230));
JLabel l1,l2,l3,l4;
JTextField t1,t2,t3;
l1=new JLabel("ProductID");
l1.setBounds(10,100,200,30);
t1=new JTextField();
t1.setBounds(100,100,200,30);
l2=new JLabel("Name");
l2.setBounds(10,150,200,30);
t2=new JTextField();
t2.setBounds(100,150,200,30);
l3=new JLabel("Quantity");
l3.setBounds(10,250,200,30);
t3=new JTextField();
t3.setBounds(100,250,200,30);
p1.setBorder(BorderFactory.createTitledBorder("Product Details"));
JCheckBox checkBox = new JCheckBox("Available for Next Day Delivery");
checkBox.setBounds(10,300,250,50);
l4 = new JLabel("Item Type");
l4.setBounds(10,200,200,30);
String[] itemType = {"Select type","Homeware","Hobby","Garden"};
JComboBox dropdown = new JComboBox(itemType);
dropdown.setBounds(100,200,120,20);
p1.add(t1);p1.add(l1);p1.add(t2);p1.add(l2);p1.add(t3);p1.add(l3);p1.add(l4);p1.add(dropdown);p1.add(checkBox);
JButton b1 = new JButton("New Item");
b1.setBounds(200,550,80,20);
JButton b2 = new JButton("Save");
b2.setBounds(300,550,80,20);
JButton b3 = new JButton("Delete Selected");
b3.setBounds(600,550,80,20);
b3.setEnabled(false);
p3.add(b1);p3.add(b2);p3.add(b3);
JMenuBar mb = new JMenuBar();
menu = new JMenu("Actions");
about = new JMenuItem("About");
importData = new JMenuItem("Import Data");
inventory = new JMenuItem("Inventory");
export = new JMenuItem("Export to CSV");
menu.add(about);menu.add(importData);menu.add(inventory);menu.add(export);
mb.add(menu);
f.getContentPane().add(p1,BorderLayout.CENTER);
f.getContentPane().add(scrollPane,BorderLayout.EAST);
f.getContentPane().add(p3,BorderLayout.SOUTH);
f.setJMenuBar(mb);
f.setSize(800,600);
f.setLayout(new BorderLayout());
f.setVisible(true);
}
These code changes should help at least a little bit.
Things that had to change:
Each JPanel should have a layout. Setting the layout to null (as per TG's comment) is not good.
The setBounds() methods for the buttons were removed.
The f.setLayout(new BorderLayout()); was moved to the top of the code where Components were being added to the JFrame before the layout was set.
import javax.swing.*;
import java.awt.*;
public class ProductListGUI {
JMenu menu;
JMenuItem about,importData,inventory,export;
ProductListGUI(){
JFrame f = new JFrame("Assignment 2");
JPanel panel1 = new JPanel();
JList<String> list = new JList<>();
list.setBounds(600,0,200,600);
JScrollPane scrollPane = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel panel3 = new JPanel();
panel1.setBounds(0,0,600,500);
panel1.setBackground(new Color(230,230,230));
scrollPane.setBounds(600,0,200,500);
panel3.setBounds(0,0,800,100);
panel3.setBackground(new Color(230,230,230));
JLabel l1,l2,l3,l4;
JTextField t1,t2,t3;
l1=new JLabel("ProductID");
l1.setBounds(10,100,200,30);
t1=new JTextField();
t1.setBounds(100,100,200,30);
l2=new JLabel("Name");
l2.setBounds(10,150,200,30);
t2=new JTextField();
t2.setBounds(100,150,200,30);
l3=new JLabel("Quantity");
l3.setBounds(10,250,200,30);
t3=new JTextField();
t3.setBounds(100,250,200,30);
panel1.setBorder(BorderFactory.createTitledBorder("Product Details"));
JCheckBox checkBox = new JCheckBox("Available for Next Day Delivery");
checkBox.setBounds(10,300,250,50);
l4 = new JLabel("Item Type");
l4.setBounds(10,200,200,30);
String[] itemType = {"Select type","Homeware","Hobby","Garden"};
JComboBox dropdown = new JComboBox(itemType);
dropdown.setBounds(100,200,120,20);
panel1.add(t1);
panel1.add(l1);
panel1.add(t2);
panel1.add(l2);
panel1.add(t3);
panel1.add(l3);
panel1.add(l4);
panel1.add(dropdown);
panel1.add(checkBox);
JButton b1 = new JButton("New Item");
JButton b2 = new JButton("Save");
JButton b3 = new JButton("Delete Selected");
b3.setEnabled(false);
panel3.add(b1);
panel3.add(b2);
panel3.add(b3);
JMenuBar mb = new JMenuBar();
menu = new JMenu("Actions");
about = new JMenuItem("About");
importData = new JMenuItem("Import Data");
inventory = new JMenuItem("Inventory");
export = new JMenuItem("Export to CSV");
menu.add(about);
menu.add(importData);
menu.add(inventory);
menu.add(export);
mb.add(menu);
f.setLayout(new BorderLayout());
f.getContentPane().add(panel1,BorderLayout.CENTER);
f.getContentPane().add(scrollPane,BorderLayout.EAST);
f.getContentPane().add(panel3,BorderLayout.SOUTH);
f.setJMenuBar(mb);
f.setSize(800,600);
f.setVisible(true);
}
public static void main(String[] args) {
ProductListGUI gui = new ProductListGUI();
}
}
Here is a very simple BorderLayout example that might help in the future, or not.
import javax.swing.*;
import java.awt.*;
public class TestGui {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setLayout(new BorderLayout());
frame.setSize(800,600);
frame.getContentPane().add(createJPanel("CENTER", Color.RED), BorderLayout.CENTER);
frame.getContentPane().add(createJPanel("NORTH", Color.CYAN), BorderLayout.NORTH);
frame.getContentPane().add(createJPanel("EAST", Color.LIGHT_GRAY), BorderLayout.EAST);
frame.getContentPane().add(createJPanel("SOUTH", Color.GREEN), BorderLayout.SOUTH);
frame.getContentPane().add(createJPanel("WEST", Color.YELLOW), BorderLayout.WEST);
frame.setVisible(true);
}
private static JPanel createJPanel(String title, Color color) {
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
jPanel.add(new JLabel(title), BorderLayout.CENTER);
jPanel.setBackground(color);
return jPanel;
}
}
I'm creating a simple UI using GUI objects to input data but whenever I add the center panel to the contentPane, my JLabels disappear. Additionally, the JTextFields, JComboBoxs and JButtons don't respond to clicking or entering keystrokes. If I don't add the centerPanel, or add it and start the applet with width and height parameters of 1 and 1, everything works perfectly.
When I stretch out the screen, after adding the center panel to a normal run configuration, the objects will appear outside of the initial window. I've defined all of the objects as private instance variables before the listed code, so that isn't the issue. Please help, I'm baffled!
Here's my code:
public void begin() {
// creates the GUI Objects for the northPanel
northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 4));
searchBox = new JTextField();
searchBoxLabel = new JLabel("Search ID #:");
search = new JButton("Search");
search.addActionListener(this);
northPanel.add(searchBoxLabel);
northPanel.add(searchBox);
northPanel.add(search);
// creates the GUI OBjects for the southPanel
southDivider = new JPanel();
southDivider.setLayout(new GridLayout(2, 1));
southPanel = new JPanel();
southPanel.setLayout(new GridLayout(1, 3));
enter = new JButton("Enter");
incrementInfo = new JButton("Increment ID");
setCurrentTimeDate = new JButton("Current Time/Date");
findRate = new JButton("Find Yield Rate");
findRate.addActionListener(this);
enter.addActionListener(this);
incrementInfo.addActionListener(this);
setCurrentTimeDate.addActionListener(this);
southPanel.add(findRate);
southPanel.add(setCurrentTimeDate);
southPanel.add(incrementInfo);
southPanel.add(enter);
messageLabel = new JLabel("Welcome to the Stringer Application");
southDivider.add(southPanel);
southDivider.add(messageLabel);
// create the GUI objects on the eastPanel
eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(5, 2));
cellType = new JComboBox();
cellType.addItem("Rect");
cellType.addItem("Cham");
cellTypeLabel = new JLabel("Cell Type:");
ecaCode = new JComboBox();
ecaCode.addItem("A");
ecaCode.addItem("B");
ecaCodeLabel = new JLabel("ECA Code:");
ecaSyringeNum = new JTextField();
ecaSyringeNumLabel = new JLabel("Eca Syringe #:");
passFail = new JComboBox();
passFail.addItem("Pass");
passFail.addItem("Fail");
passFailLabel = new JLabel("Pass/Fail:");
operator = new JTextField();
operatorLabel = new JLabel("Operator:");
cellType.addActionListener(this);
ecaCode.addActionListener(this);
passFail.addActionListener(this);
eastPanel.add(operatorLabel);
eastPanel.add(operator);
eastPanel.add(cellTypeLabel);
eastPanel.add(cellType);
eastPanel.add(ecaCodeLabel);
eastPanel.add(ecaCode);
eastPanel.add(ecaSyringeNumLabel);
eastPanel.add(ecaSyringeNum);
eastPanel.add(passFailLabel);
eastPanel.add(passFail);
// create the GUI objects on the westPanel
westPanel = new JPanel();
westPanel.setLayout(new GridLayout(6, 2));
yieldLabel = new JLabel("Current Yield:");
yieldValueLabel = new JLabel("Select Date/Times");
yieldAfterDate = new JTextField();
yieldAfterTime = new JTextField();
yieldBeforeDate = new JTextField();
yieldBeforeTime = new JTextField();
yieldAfterDateLabel = new JLabel("After Date:");
yieldAfterTimeLabel = new JLabel("After Time:");
yieldBeforeDateLabel = new JLabel("Before Date:");
yieldBeforeTimeLabel = new JLabel("Before Time:");
setBeforeToCurrentLabel = new JLabel("<html>'Set to Current' for <br> Current Date/Time</html>");
fillBeforeWithCurrent = new JButton("Set to Current");
fillBeforeWithCurrent.addActionListener(this);
westPanel.add(yieldLabel);
westPanel.add(yieldValueLabel);
westPanel.add(yieldAfterDateLabel);
westPanel.add(yieldAfterDate);
westPanel.add(yieldAfterTimeLabel);
westPanel.add(yieldAfterTime);
westPanel.add(yieldBeforeDateLabel);
westPanel.add(yieldBeforeDate);
westPanel.add(yieldBeforeTimeLabel);
westPanel.add(yieldBeforeTime);
westPanel.add(setBeforeToCurrentLabel);
westPanel.add(fillBeforeWithCurrent);
// create the GUI objects for the centerPanel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 4));
date = new JTextField(getCurrentDate());
dateLabel = new JLabel("Date:");
time = new JTextField(getCurrentTime());
timeLabel = new JLabel("Time:");
stringID = new JTextField();
stringIDLabel = new JLabel("String ID:");
cellLot = new JTextField();
cellLotLabel = new JLabel("Cell Lot #:");
cellEff = new JTextField();
cellEffLabel = new JLabel("Cell Eff:");
comments = new JTextField();
commentsLabel = new JLabel("Comments:");
centerPanel.add(dateLabel);
centerPanel.add(date);
centerPanel.add(timeLabel);
centerPanel.add(time);
centerPanel.add(stringIDLabel);
centerPanel.add(stringID);
centerPanel.add(cellLotLabel);
centerPanel.add(cellLot);
centerPanel.add(cellEffLabel);
centerPanel.add(cellEff);
centerPanel.add(commentsLabel);
centerPanel.add(comments);
// add the panel's to the contentPane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(northPanel, BorderLayout.NORTH);
contentPane.add(southDivider, BorderLayout.SOUTH);
contentPane.add(eastPanel, BorderLayout.EAST);
contentPane.add(westPanel, BorderLayout.WEST);
contentPane.validate();
}
I have tested your code and it is working with no problems.
Most likely you are adding components some where else to the container, and by default any added components goes to center, which cause the old center panel to be removed , and the the swing frame to draw dirty area.
EDIT:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test2 extends JFrame {
public Test2() {
begin();
}
public void begin() {
// creates the GUI Objects for the northPanel
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 4));
JTextField searchBox = new JTextField();
JLabel searchBoxLabel = new JLabel("Search ID #:");
JButton search = new JButton("Search");
northPanel.add(searchBoxLabel);
northPanel.add(searchBox);
northPanel.add(search);
// creates the GUI OBjects for the southPanel
JPanel southDivider = new JPanel();
southDivider.setLayout(new GridLayout(2, 1));
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(1, 3));
JButton enter = new JButton("Enter");
JButton incrementInfo = new JButton("Increment ID");
JButton setCurrentTimeDate = new JButton("Current Time/Date");
JButton findRate = new JButton("Find Yield Rate");
southPanel.add(findRate);
southPanel.add(setCurrentTimeDate);
southPanel.add(incrementInfo);
southPanel.add(enter);
JLabel messageLabel = new JLabel("Welcome to the Stringer Application");
southDivider.add(southPanel);
southDivider.add(messageLabel);
// create the GUI objects on the eastPanel
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(5, 2));
JComboBox cellType = new JComboBox();
cellType.addItem("Rect");
cellType.addItem("Cham");
JLabel cellTypeLabel = new JLabel("Cell Type:");
JComboBox ecaCode = new JComboBox();
ecaCode.addItem("A");
ecaCode.addItem("B");
JLabel ecaCodeLabel = new JLabel("ECA Code:");
JTextField ecaSyringeNum = new JTextField();
JLabel ecaSyringeNumLabel = new JLabel("Eca Syringe #:");
JComboBox passFail = new JComboBox();
passFail.addItem("Pass");
passFail.addItem("Fail");
JLabel passFailLabel = new JLabel("Pass/Fail:");
JTextField operator = new JTextField();
JLabel operatorLabel = new JLabel("Operator:");
eastPanel.add(operatorLabel);
eastPanel.add(operator);
eastPanel.add(cellTypeLabel);
eastPanel.add(cellType);
eastPanel.add(ecaCodeLabel);
eastPanel.add(ecaCode);
eastPanel.add(ecaSyringeNumLabel);
eastPanel.add(ecaSyringeNum);
eastPanel.add(passFailLabel);
eastPanel.add(passFail);
// create the GUI objects on the westPanel
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(6, 2));
JLabel yieldLabel = new JLabel("Current Yield:");
JLabel yieldValueLabel = new JLabel("Select Date/Times");
JTextField yieldAfterDate = new JTextField();
JTextField yieldAfterTime = new JTextField();
JTextField yieldBeforeDate = new JTextField();
JTextField yieldBeforeTime = new JTextField();
JLabel yieldAfterDateLabel = new JLabel("After Date:");
JLabel yieldAfterTimeLabel = new JLabel("After Time:");
JLabel yieldBeforeDateLabel = new JLabel("Before Date:");
JLabel yieldBeforeTimeLabel = new JLabel("Before Time:");
JLabel setBeforeToCurrentLabel = new JLabel("<html>'Set to Current' for <br> Current Date/Time</html>");
JButton fillBeforeWithCurrent = new JButton("Set to Current");
westPanel.add(yieldLabel);
westPanel.add(yieldValueLabel);
westPanel.add(yieldAfterDateLabel);
westPanel.add(yieldAfterDate);
westPanel.add(yieldAfterTimeLabel);
westPanel.add(yieldAfterTime);
westPanel.add(yieldBeforeDateLabel);
westPanel.add(yieldBeforeDate);
westPanel.add(yieldBeforeTimeLabel);
westPanel.add(yieldBeforeTime);
westPanel.add(setBeforeToCurrentLabel);
westPanel.add(fillBeforeWithCurrent);
// create the GUI objects for the centerPanel
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 4));
JTextField date = new JTextField();
JLabel dateLabel = new JLabel("Date:");
JTextField time = new JTextField();
JLabel timeLabel = new JLabel("Time:");
JTextField stringID = new JTextField();
JLabel stringIDLabel = new JLabel("String ID:");
JTextField cellLot = new JTextField();
JLabel cellLotLabel = new JLabel("Cell Lot #:");
JTextField cellEff = new JTextField();
JLabel cellEffLabel = new JLabel("Cell Eff:");
JTextField comments = new JTextField();
JLabel commentsLabel = new JLabel("Comments:");
centerPanel.add(dateLabel);
centerPanel.add(date);
centerPanel.add(timeLabel);
centerPanel.add(time);
centerPanel.add(stringIDLabel);
centerPanel.add(stringID);
centerPanel.add(cellLotLabel);
centerPanel.add(cellLot);
centerPanel.add(cellEffLabel);
centerPanel.add(cellEff);
centerPanel.add(commentsLabel);
centerPanel.add(comments);
// add the panel's to the contentPane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(northPanel, BorderLayout.NORTH);
contentPane.add(southDivider, BorderLayout.SOUTH);
contentPane.add(eastPanel, BorderLayout.EAST);
contentPane.add(westPanel, BorderLayout.WEST);
// contentPane.validate();
setSize(812, 514);
}
public static void main(String[] args) {
Test2 t=new Test2();
// t.begin();
t.setVisible(true);
}
}
I am making a better version of an application that was given to me. I still need to have the same components as the program that was given to me, I just need to reorganize it. I was also told not to copy any of the original code and do it from scratch. The first screenshot shows the textfield I need to add to my program from the original program. The second screenshot is my program. I am not sure if a JTextField would be best for this. My code is below. I have tried to add a JTextField with a JLabel and center it but when I run the program it covers everything else in the program and only shows a little white box.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
JLabel input = new JLabel();
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.add(input);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// Make all necessary buttons
JButton next = new JButton("Next");
JButton save = new JButton("Save");
JButton save2 = new JButton("Save");
JButton save3 = new JButton("Save");
JButton save4 = new JButton("Save");
JButton aok = new JButton("OK");
JButton bok = new JButton("OK");
JButton cok = new JButton("OK");
JButton acancel = new JButton("Cancel");
JButton bcancel = new JButton("Cancel");
JButton ccancel = new JButton("Cancel");
JButton dcancel = new JButton("Cancel");
JButton ecancel = new JButton("Cancel");
JButton fcancel = new JButton("Cancel");
JButton gcancel = new JButton("Cancel");
JButton hcancel = new JButton("Cancel");
//Make the drop down lists
String[] baudrates = {"57600", "115200", "128000", "256000"};
JComboBox baudlist = new JComboBox(baudrates);
String[] baudrates2 = {"57600", "115200", "128000", "256000"};
JComboBox baudlist2 = new JComboBox(baudrates2);
String[] bytesizes = {"7", "8"};
JComboBox bytelist = new JComboBox(bytesizes);
String[] bytesizes2 = {"7", "8"};
JComboBox bytelist2 = new JComboBox(bytesizes2);
String[] stopbit = {"1", "2"};
JComboBox stoplist = new JComboBox(stopbit);
String[] stopbit2 = {"1", "2"};
JComboBox stoplist2 = new JComboBox(stopbit2);
String[] flows = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist = new JComboBox(flows);
String[] flows2 = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist2 = new JComboBox(flows2);
String[] paritys = {"None", "Even", "Odd"};
JComboBox paritylist = new JComboBox(paritys);
String[] paritys2 = {"None", "Even", "Odd"};
JComboBox paritylist2 = new JComboBox(paritys2);
//Make all necessary labels
JLabel cardLabel = new JLabel("Card Number: ");
JLabel expLabel = new JLabel("Exp. Date (MM/YY): ");
JLabel cvvLabel = new JLabel("CVV: ");
JLabel ipLabel = new JLabel("IP Address: ");
JLabel connectLabel = new JLabel("Connect Time: ");
JLabel sendLabel = new JLabel("Send Time Out: ");
JLabel receiveLabel = new JLabel("Receive Time Out: ");
JLabel portLabel = new JLabel("Port: ");
JLabel baudrate = new JLabel("Baud Rate: ");
JLabel bytesize = new JLabel("Byte Size: ");
JLabel stopbits = new JLabel("Stop Bits: ");
JLabel flow = new JLabel("Flow Con..: ");
JLabel parity = new JLabel("Parity: ");
JLabel stoLabel = new JLabel("Send Time Out: ");
JLabel rtoLabel = new JLabel("Receive Time Out: ");
JLabel portLabel2 = new JLabel("Port: ");
JLabel baudrate2 = new JLabel("Baud Rate: ");
JLabel bytesize2 = new JLabel("Byte Size: ");
JLabel stopbits2 = new JLabel("Stop Bits: ");
JLabel flow2 = new JLabel("Flow Con..: ");
JLabel parity2 = new JLabel("Parity: ");
JLabel stoLabel2 = new JLabel("Send Time Out: ");
JLabel rtoLabel2 = new JLabel("Receive Time Out: ");
JLabel portLabel3 = new JLabel("Port: ");
JLabel vendor = new JLabel("Vendor ID: ");
JLabel product = new JLabel("Product ID: ");
JLabel stoLabel3 = new JLabel("Send Time Out: ");
JLabel rtoLabel3 = new JLabel("Receive Time Out: ");
JLabel amountLabel = new JLabel("Amount: ");
JLabel textLabel = new JLabel("Display Text: ");
//Make all necessary TextFields
JTextField card = new JTextField(10);
JTextField expDate = new JTextField(10);
JTextField cvv = new JTextField(10);
JTextField ip = new JTextField(10);
JTextField ct = new JTextField(10);
JTextField rto = new JTextField(10);
JTextField sto = new JTextField(10);
JTextField port = new JTextField(10);
JTextField sendto = new JTextField(10);
JTextField reto = new JTextField(10);
JTextField comport = new JTextField(10);
JTextField sendto2 = new JTextField(10);
JTextField reto2 = new JTextField(10);
JTextField comport2 = new JTextField(10);
JTextField vendorid = new JTextField(10);
JTextField productid = new JTextField(10);
JTextField sendtime = new JTextField(10);
JTextField receiveto = new JTextField(10);
JTextField amountbox = new JTextField(10);
JTextField textBox = new JTextField(10);
//Add components to the panels
final JPanel ethernetSettings = new JPanel();
ethernetSettings.setLayout(new GridLayout(6, 2));
ethernetSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
ethernetSettings.add(ipLabel);
ethernetSettings.add(ip);
ethernetSettings.add(connectLabel);
ethernetSettings.add(ct);
ethernetSettings.add(receiveLabel);
ethernetSettings.add(rto);
ethernetSettings.add(sendLabel);
ethernetSettings.add(sto);
ethernetSettings.add(portLabel);
ethernetSettings.add(port);
ethernetSettings.add(save);
ethernetSettings.add(ecancel);
final JPanel usbHIDSettings = new JPanel();
usbHIDSettings.setLayout(new GridLayout(5, 2));
usbHIDSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbHIDSettings.add(vendor);
usbHIDSettings.add(vendorid);
usbHIDSettings.add(product);
usbHIDSettings.add(productid);
usbHIDSettings.add(stoLabel3);
usbHIDSettings.add(sendtime);
usbHIDSettings.add(rtoLabel3);
usbHIDSettings.add(receiveto);
usbHIDSettings.add(save4);
usbHIDSettings.add(hcancel);
final JPanel usbCDCSettings = new JPanel();
usbCDCSettings.setLayout(new GridLayout(9, 2));
usbCDCSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbCDCSettings.add(baudrate2);
usbCDCSettings.add(baudlist);
usbCDCSettings.add(bytesize2);
usbCDCSettings.add(bytelist);
usbCDCSettings.add(stopbits2);
usbCDCSettings.add(stoplist);
usbCDCSettings.add(flow2);
usbCDCSettings.add(flowlist);
usbCDCSettings.add(parity2);
usbCDCSettings.add(paritylist);
usbCDCSettings.add(stoLabel2);
usbCDCSettings.add(sendto2);
usbCDCSettings.add(rtoLabel2);
usbCDCSettings.add(reto2);
usbCDCSettings.add(portLabel3);
usbCDCSettings.add(comport2);
usbCDCSettings.add(save3);
usbCDCSettings.add(gcancel);
final JPanel rsSettings = new JPanel();
rsSettings.setLayout(new GridLayout(9, 2));
rsSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
rsSettings.add(baudrate);
rsSettings.add(baudlist2);
rsSettings.add(bytesize);
rsSettings.add(bytelist2);
rsSettings.add(stopbits);
rsSettings.add(stoplist2);
rsSettings.add(flow);
rsSettings.add(flowlist2);
rsSettings.add(parity);
rsSettings.add(paritylist2);
rsSettings.add(stoLabel);
rsSettings.add(sendto);
rsSettings.add(rtoLabel);
rsSettings.add(reto);
rsSettings.add(portLabel2);
rsSettings.add(comport);
rsSettings.add(save2);
rsSettings.add(fcancel);
JRadioButton ethernet = new JRadioButton("Ethernet");
ethernet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog esettings = new JDialog(frame);
esettings.setTitle("Ethernet Settings");
esettings.add(ethernetSettings);
esettings.setSize(400, 400);
esettings.pack();
esettings.setVisible(true);
}
});
JRadioButton rs = new JRadioButton("RS232");
rs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog rsettings = new JDialog(frame);
rsettings.setTitle("RS232 Settings");
rsettings.add(rsSettings);
rsettings.pack();
rsettings.setVisible(true);
}
});
JRadioButton usbcdc = new JRadioButton("USB_CDC");
usbcdc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbc = new JDialog(frame);
usbc.setTitle("USB_CDC Settings");
usbc.add(usbCDCSettings);
usbc.setSize(400, 400);
usbc.pack();
usbc.setVisible(true);
}
});
JRadioButton usbhid = new JRadioButton("USB_HID");
usbhid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbh = new JDialog(frame);
usbh.setTitle("USB_HID Settings");
usbh.add(usbHIDSettings);
usbh.setSize(400, 400);
usbh.pack();
usbh.setVisible(true);
}
});
final JPanel PortSettings = new JPanel();
PortSettings.setLayout(new GridLayout(3, 4));
PortSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
PortSettings.add(ethernet);
PortSettings.add(rs);
PortSettings.add(usbcdc);
PortSettings.add(usbhid);
PortSettings.add(next);
PortSettings.add(bcancel);
final JPanel accountPanel = new JPanel();
accountPanel.setLayout(new GridLayout(4, 2));
accountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
accountPanel.add(cardLabel);
accountPanel.add(card);
accountPanel.add(expLabel);
accountPanel.add(expDate);
accountPanel.add(cvvLabel);
accountPanel.add(cvv);
accountPanel.add(bok);
accountPanel.add(ccancel);
JRadioButton apprve = new JRadioButton("Approve");
JRadioButton decline = new JRadioButton("Decline");
final JPanel apprvordecl = new JPanel();
apprvordecl.setLayout(new GridLayout(3, 2));
apprvordecl.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
apprvordecl.add(apprve);
apprvordecl.add(decline);
apprvordecl.add(textLabel);
apprvordecl.add(textBox);
apprvordecl.add(aok);
apprvordecl.add(acancel);
final JPanel amountPanel = new JPanel();
amountPanel.setLayout(new GridLayout(2, 2));
amountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
amountPanel.add(amountLabel);
amountPanel.add(amountbox);
amountPanel.add(cok);
amountPanel.add(dcancel);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
portsettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog port = new JDialog(frame);
port.setTitle("Port Settings");
port.setSize(400, 400);
port.add(PortSettings);
port.pack();
port.setVisible(true);
}
});
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
account.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog accountDialog = new JDialog(frame);
accountDialog.setTitle("Account");
accountDialog.setSize(400, 400);
accountDialog.add(accountPanel);
accountDialog.pack();
accountDialog.setVisible(true);
}
});
JButton amount = new JButton("Amount");
amount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog amount2 = new JDialog(frame);
amount2.setTitle("Amount");
amount2.setSize(400, 400);
amount2.add(amountPanel);
amount2.pack();
amount2.setVisible(true);
}
});
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
approvordecl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog apprv = new JDialog(frame);
apprv.setTitle("Approve / Decline");
apprv.setSize(400, 400);
apprv.add(apprvordecl);
apprv.pack();
apprv.setVisible(true);
}
});
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
ButtonGroup group = new ButtonGroup();
group.add(usbhid);
group.add(usbcdc);
group.add(ethernet);
group.add(rs);
ButtonGroup approvegroup = new ButtonGroup();
approvegroup.add(apprve);
approvegroup.add(decline);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
go for JTextArea
A JTextArea is a multi-line area that displays plain text.
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JTextArea.html
For required layout refer Layout Manager by Oracle
I'm trying to set the size of a gridlayout jpanel. Here is the code:
JFrame myFrame = new JFrame();
myFrame.setLayout(new FlowLayout());
myFrame.setLocation(400, 100);
myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel jlMins = new JLabel("Number of minutes for tutoring session (should be a positive decimal number): 0.0");
JLabel jlEarnings = new JLabel("Earnings in dollars and cents received (should be positive decimal number): 0.0");
jtfMins = new JTextField(20);
jtfEarnings = new JTextField(20);
JPanel jpMins = new JPanel(new BorderLayout());
JPanel jpEarnings = new JPanel(new BorderLayout());
jpMins.setPreferredSize(new Dimension(300,50));
jpEarnings.setPreferredSize(new Dimension(300,50));
jpMins.add(jlMins,BorderLayout.NORTH);
jpMins.add(jtfMins,BorderLayout.CENTER);
jpEarnings.add(jlEarnings,BorderLayout.NORTH);
jpEarnings.add(jtfEarnings,BorderLayout.CENTER);
JButton jbQuit = new JButton("Quit");
JButton jbEnter = new JButton("Enter");
JButton jbReport = new JButton("Run Report");
jbQuit.setActionCommand("quit");
jbEnter.setActionCommand("enter");
jbReport.setActionCommand("report");
jbQuit.addActionListener(this);
jbEnter.addActionListener(this);
jbReport.addActionListener(this);
JPanel jpButtons = new JPanel(new GridLayout(4,1,0,20));
jpButtons.setSize(new Dimension(50,150));
jpButtons.add(jbEnter);
jpButtons.add(jbReport);
jpButtons.add(jbQuit);
JPanel jpNorth = new JPanel(new BorderLayout());
jpNorth.add(jpMins,BorderLayout.NORTH);
jpNorth.add(jpEarnings,BorderLayout.CENTER);
jpNorth.add(jpButtons,BorderLayout.SOUTH);
jtaReports = new JTextArea();
jtaReports.setColumns(40);
jtaReports.setRows(10);
jtaReports.setLineWrap(true);
JScrollPane jspReports = new JScrollPane(jtaReports);
jspReports.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel jpSouth = new JPanel();
jpSouth.setPreferredSize(new Dimension(350,200));
jpSouth.add(jspReports);
JPanel jpMain = new JPanel(new BorderLayout());
jpMain.add(jpNorth,BorderLayout.NORTH);
jpMain.add(jpSouth,BorderLayout.SOUTH);
jpMain.setPreferredSize(new Dimension(500,500));
myFrame.setContentPane(jpMain);
myFrame.pack();
myFrame.setVisible(true);
The panel name is jpButtons. Of the above code I'm talking mainly about this section:
JButton jbQuit = new JButton("Quit");
JButton jbEnter = new JButton("Enter");
JButton jbReport = new JButton("Run Report");
jbQuit.setActionCommand("quit");
jbEnter.setActionCommand("enter");
jbReport.setActionCommand("report");
jbQuit.addActionListener(this);
jbEnter.addActionListener(this);
jbReport.addActionListener(this);
JPanel jpButtons = new JPanel(new GridLayout(4,1,0,20));
jpButtons.setSize(new Dimension(50,150));
jpButtons.add(jbEnter);
jpButtons.add(jbReport);
jpButtons.add(jbQuit);
How exactly does setSize, and setPreferredSize work or how to get them to work properly on jpanel, components, etc.
scaling and positioning is handled by the layout manager; let it do its job.
I am trying to align several elements in a Java Applet, I am not able to do it. Please help me. Here is my code:
public class User extends JApplet implements ActionListener,ItemListener {
public int sentp,recievedp,corruptedp;
public String stetus;
public double energi,nodeid,en;
TextField name,time,initene,ampco,acttran;
Button rsbt,vlbt,insd ;
Choice ch,ch2;
public String patrn;
public void init() {
this.setSize(800,600);
Label namep= new Label("\n\nEnter the No. of Nodes: ", Label.CENTER);
name = new TextField(5);
Label timep = new Label("\n\nEnter time of Simulation: ",Label.CENTER);
time = new TextField(5);
Label initen = new Label("\n\nInitial Energy Of Each Sensor Node:");
initene = new TextField("10^-4 Joules");
initene.setEditable(false);
Label ampcon = new Label("\n\nAmplifier Constant:");
ampco = new TextField("10^-12 Joules");
ampco.setEditable(false);
Label acttrans = new Label("\n\nEnergy Required To Activate Transmitter/Reciever:");
acttran = new TextField("50 ^ -9 Joules");
acttran.setEditable(false);
Label chp = new Label("\n\nSelect Radio Model:",Label.CENTER);
rsbt = new Button("Run The Simulation");
ch= new Choice();
ch.add("");
ch.add("Gaussian RadioModel");
ch.add("Rayleigh RadioModel");
Label pat= new Label("\n\nDistribution Pattern");
ch2= new Choice();
ch2.add("");
ch2.add("Rectangular Pattern");
ch2.add("Linear Pattern");
ch2.add("Random Pattern");
vlbt=new Button("ViewLog");
insd=new Button("Details of node");
JPanel cp = new JPanel();
this.add(cp);
GridBagLayout gridb = new GridBagLayout();
Container cont = getContentPane();
cont.setLayout(gridb);
add(cp);
GroupLayout layout = new GroupLayout(cp);
cp.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(namep)
.addComponent(name)
.addComponent(rsbt))
.addGroup(layout.createSequentialGroup()
.addComponent(timep)
.addComponent(time)
.addComponent(vlbt))
.addGroup(layout.createSequentialGroup()
.addComponent(chp)
.addComponent(ch))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pat)
.addComponent(ch2))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(initen)
.addComponent(initene))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(ampcon)
.addComponent(ampco))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(acttrans)
.addComponent(acttran))
);
rsbt.addActionListener(this);
vlbt.addActionListener(this);
insd.addActionListener(this);
ch.addItemListener(this);
ch2.addItemListener(this);
}
Try this, is this good for you :
import java.awt.*;
import javax.swing.*;
public class AppletLayout extends JApplet
{
private JTextField noNodeField;
private JTextField timeSimField;
private JTextField iniEngField;
private JTextField ampConsField;
private JTextField engReqField;
private JComboBox selModeCombo;
private JComboBox distPattCombo;
private JButton runSimButton;
private JButton logButton;
private JButton detailNodeButton;
private String[] selectionModelString = {"", "Gaussian RadioModel"
, "Rayleigh RadioModel"};
private String[] distPatternString = {"", "Rectangular Pattern"
, "Linear Pattern"
, "Random Pattern"};
public void init()
{
try
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndDisplayGUI();
}
});
}
catch(Exception e)
{
System.err.println("Unable to Create and Display GUI : " + e.getMessage());
e.printStackTrace();
}
}
private void createAndDisplayGUI()
{
JLabel noNodeLabel = new JLabel("Enter the No. of Nodes :", JLabel.LEFT);
noNodeField = new JTextField(5);
JLabel timeSimLabel = new JLabel("Enter time of Simulation :", JLabel.LEFT);
timeSimField = new JTextField(5);
JLabel iniEngLabel = new JLabel("Initial Energy Of Each Sensor Node :", JLabel.LEFT);
iniEngField = new JTextField("10^-4 Joules");
JLabel ampConsLabel = new JLabel("Amplifier Constant :", JLabel.LEFT);
ampConsField = new JTextField("10^-12 Joules");
JLabel engReqLabel = new JLabel("Energy Required To Activate Transmitter/Reciever :", JLabel.LEFT);
engReqField = new JTextField("50 ^ -9 Joules");
JLabel selModeLabel = new JLabel("Select Radio Model :", JLabel.LEFT);
selModeCombo = new JComboBox(selectionModelString);
JLabel distPattLabel = new JLabel("Distribution Pattern :", JLabel.LEFT);
distPattCombo = new JComboBox(selectionModelString);
runSimButton = new JButton("Run Simulation");
logButton = new JButton("View Log");
detailNodeButton = new JButton("Details of Node");
JComponent contentPane = (JComponent) getContentPane();
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
topPanel.setLayout(new GridLayout(0, 2));
topPanel.add(noNodeLabel);
topPanel.add(noNodeField);
topPanel.add(timeSimLabel);
topPanel.add(timeSimField);
topPanel.add(iniEngLabel);
topPanel.add(iniEngField);
topPanel.add(ampConsLabel);
topPanel.add(ampConsField);
topPanel.add(engReqLabel);
topPanel.add(engReqField);
topPanel.add(selModeLabel);
topPanel.add(selModeCombo);
topPanel.add(distPattLabel);
topPanel.add(distPattCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
//buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setLayout(new GridLayout(0, 1, 5, 5));
buttonPanel.add(runSimButton);
buttonPanel.add(logButton);
buttonPanel.add(detailNodeButton);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(topPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.LINE_END);
contentPane.add(mainPanel, BorderLayout.PAGE_START);
setSize(1000, 600);
}
}
Here is the output :
Your current code looks pretty much like you are using some sort of GUI builder tool to generate the final layout.
For maximum control, build the component and add them to the panel. If you are looking to use GridBagLayout as shown in your code then follow the sequence construct as shown below
JPanel p1 = new JPanel(new GridBagLayout());
GridBagConstraints cs = new GridBagConstraints();
cs.fill = GridBagConstraints.HORIZONTAL;
lblUsername = new JLabel("Name: ");
cs.gridx = 0;
cs.gridy = 0;
cs.gridwidth = 1;
p1.add(lblUsername, cs);
txtUsername = new JTextField("", 20);
cs.gridx = 1;
cs.gridy = 0;
cs.gridwidth = 2;
p1.add(txtUsername, cs);
...
add(cp);
Or alternatively use BorderLayout or FlowLayout to hold the components on your panel:
JPanel p1 = new JPanel(new BorderLayout());
p1.add(lblUsername, BorderLaout.EAST);
...
When you say this
JPanel cp = new JPanel();
it means you're going to get a FlowLayout automatically. You probably want a different one.
Edit: OK, I can see where you're giving cp a GroupLayout, but I don't see where you pack() the window that cp is in or call setVisible().
Edit: But that doesn't matter for an applet.