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 currently building GUI with Java Swing.
My current code produces this.
The JTextArea of Product List makes the GUI looks awkward, how can I make the JTextArea looks like this, where it seems to have an extra row:
The GroupLayout code I'm using is:
gr.setVerticalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(productName).addComponent(productText).addComponent(productList))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(amount).addComponent(amountText).addComponent(prodScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(description).addComponent(desScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(addButton).addComponent(remButton)));
gr.setHorizontalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(productName).addComponent(amount).addComponent(description).addComponent(addButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productText).addComponent(amountText).addComponent(desScroll).addComponent(remButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productList).addComponent(prodScroll)));
I think the minority of people would choose to use GridBagLayout. However, I dislike it (among with GroupLayout) since it is "hard to use". I use nested panels instead with various Layout Managers. Using only BorderLayout and GridLayout you can achieve something like the following example, which is totally resizable, giving emphasis to "interaction" components (I mean, there is no reason to resize a constant-texted JLabel, right?)
I did not add any comments in purpose, so you can experiment with constants (and layout constraints) and see their reason of existence while having the documentations opened.
Code:
public class NestedLayoutManagersExample extends JFrame {
private static final long serialVersionUID = -7042997375941726246L;
private static final int labelsWidth = 80;
private static final int textFieldColumns = 15;
private static final int spaceBetweenAllComponents = 10;
public NestedLayoutManagersExample() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 2, 50, 50));
contentPane.setBorder(BorderFactory.createEmptyBorder(spaceBetweenAllComponents, spaceBetweenAllComponents,
spaceBetweenAllComponents, spaceBetweenAllComponents));
setContentPane(contentPane);
add(createLeftPanel());
add(createRightPanel());
setLocationByPlatform(true);
pack();
}
private Component createRightPanel() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel productListLabel = new JLabel("Product list");
mainPanel.add(productListLabel, BorderLayout.PAGE_START);
JList<String> productList = new JList<>();
DefaultListModel<String> listModel = new DefaultListModel<>();
Arrays.asList("Small Chair", "Big Chair", "Flying Chair").forEach(listModel::addElement);
productList.setModel(listModel);
JScrollPane listScrollPane = new JScrollPane(productList);
mainPanel.add(listScrollPane, BorderLayout.CENTER);
return mainPanel;
}
private Component createLeftPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JPanel topPanel = new JPanel(new GridLayout(2, 1, spaceBetweenAllComponents, spaceBetweenAllComponents));
topPanel.add(createStraightPanel("Product Name"));
topPanel.add(createStraightPanel("Amount"));
mainPanel.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';> Description");
label.setVerticalAlignment(JLabel.TOP);
centerPanel.add(label, BorderLayout.LINE_START);
centerPanel.add(createTextAreaPanel());
mainPanel.add(centerPanel, BorderLayout.CENTER);
return mainPanel;
}
private JPanel createTextAreaPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JTextArea textArea = new JTextArea(1, textFieldColumns);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
mainPanel.add(textAreaScrollPane, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new BorderLayout());
JButton addButton = new JButton("Add");
buttonsPanel.add(addButton, BorderLayout.LINE_START);
JButton removeButton = new JButton("Remove");
buttonsPanel.add(removeButton, BorderLayout.LINE_END);
mainPanel.add(buttonsPanel, BorderLayout.PAGE_END);
return mainPanel;
}
private Component createStraightPanel(String labelText) {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';>" + labelText);
mainPanel.add(label, BorderLayout.LINE_START);
JTextField textField = new JTextField(textFieldColumns);
mainPanel.add(textField, BorderLayout.CENTER);
return mainPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NestedLayoutManagersExample().setVisible(true));
}
}
Preview:
In want to add a JScrollpane to my stopwatch program, so if the laptime become more and more the scrollpane should show up and allow the user to scroll.
I tried to add the textArea which I want to have in the scrollpane, but it doesn't show a scrollpane.
public class GUI_VA6 implements ActionListener {
private JPanel pan;
private JFrame frame;
private JScrollPane vertical;
private JButton Laptime;
private JButton Start;
private JButton Stop;
private JLabel label;
private JTextArea textArea;
SimpleStopwatch simple = new SimpleStopwatch();
SimpleStopwatch.StopwatchUpdateListener sss;
double ghz;
String lapTimeString;
int countLap=1;
public GUI_VA6() {
frame = new JFrame();
frame.setTitle("Stopwatch");
label = new JLabel("Current time:");
textArea = new JTextArea();
pan = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Laptime = new JButton("Laptime");
Laptime.setEnabled(false);
Start = new JButton("Start");
Stop = new JButton("Stop");
Stop.setVisible(false);
Start.setVisible(true);
Laptime.addActionListener(this);
Start.addActionListener(this);
Stop.addActionListener(this);
pan.add(Laptime);
pan.add(Stop);
pan.add(Start);
frame.add(pan);
vertical=new JScrollPane(textArea);
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.add(vertical);
Container c;
c = frame.getContentPane();
c.setLayout(new java.awt.BorderLayout()); // immer so
c.add(pan, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(label, BorderLayout.NORTH);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setSize(500, 500);
You are adding your scrollpane to the container (frame.add is equivalent to frame.getContentPane().add), THEN changing the layout manager of the container, which isn't a good idea.
Remove
frame.add(vertical);
And replace
c.add(textArea, BorderLayout.CENTER);
with
c.add(vertical, BorderLayout.CENTER);
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'm trying to create (hand-coded) a GUI similair to the GUI shown below, however, only an empty frame shows.
Mock GUI:
I've used various layouts and SWING/AWT components to create the GUI and 4 JPanels which contain:
mainPanel: Contains all the panels in it.
listPanel: Contains the JTables, JLabels and the two JButtons
infoPanel: Contains the JLabels, JCheckBox and JTextBoxes.
addPanel: Contains the JLists and JButton
This is what I coded so far:
import java.awt.*;
import javax.swing.*;
import javax.swing.JTable;
public class GUI extends JFrame {
public void buildGui() {
JFrame frame = new JFrame("Hotel TV Scheduler");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridLayout(3,3));
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new GridLayout(2,2));
JPanel addPanel = new JPanel();
addPanel.setLayout(new FlowLayout());
mainPanel.add(listPanel, BorderLayout.LINE_START);
mainPanel.add(infoPanel, BorderLayout.LINE_END);
mainPanel.add(addPanel, BorderLayout.PAGE_END);
JTable chOneTable = new JTable();
JTable chTwoTable = new JTable();
JTable listTable = new JTable();
JLabel ch1Label = new JLabel("Channel 1");
JLabel ch2Label = new JLabel("Channel 2");
JLabel listLabel = new JLabel("List");
JButton rmvChOneButton = new JButton("Remove Channel");
JButton rmvChTwoButton = new JButton("Remove Channel");
listPanel.add(ch1Label);
listPanel.add(ch2Label);
listPanel.add(listLabel);
listPanel.add(chOneTable);
listPanel.add(chTwoTable);
listPanel.add(listTable);
listPanel.add(rmvChOneButton);
listPanel.add(rmvChTwoButton);
JLabel titleLabel = new JLabel("Title");
JLabel genreLabel = new JLabel("Genre");
JLabel durationLabel = new JLabel("Duration");
JLabel actorLabel = new JLabel("Actor");
JLabel directorLabel = new JLabel("Director");
JLabel rentableLabel = new JLabel("Rentable");
JLabel synLabel = new JLabel("Synopsis");
JTextField txtTitle = new JTextField();
JTextField txtGenre = new JTextField();
JTextField txtDuration = new JTextField();
JTextField txtActor = new JTextField();
JTextField txtDirector = new JTextField();
JTextField txtSynopsis = new JTextField();
JCheckBox rentCB = new JCheckBox();
infoPanel.add(titleLabel);
infoPanel.add(txtTitle);
infoPanel.add(genreLabel);
infoPanel.add(txtGenre);
infoPanel.add(durationLabel);
infoPanel.add(txtDuration);
infoPanel.add(actorLabel);
infoPanel.add(txtActor);
infoPanel.add(directorLabel);
infoPanel.add(txtDirector);
infoPanel.add(rentableLabel);
infoPanel.add(rentCB);
infoPanel.add(synLabel);
infoPanel.add(txtSynopsis);
JButton btnAddProg = new JButton("Add Program");
JList channelList = new JList();
JList timeList = new JList();
addPanel.add(btnAddProg);
addPanel.add(channelList);
addPanel.add(timeList);
frame.setVisible(true);
}
}
Anyone can tell me why only an empty frame is showing up ?
Thanks and Regards,
Brian
Yep just checked, you'll see something if you actually add the mainPanel to the frame, (looks nothing like the mock though!)
frame.setContentPane(mainPanel);
frame.pack();
You've not added mainPanel to the frame