When I run my program, it only shows a few lines, and then it shows gray under it. Can someone explain to me why this happens? I wanted the grid layout to have 8 rows, which should include the labels and text boxes. I am not sure why only a few of them appear.
public class Application extends JFrame {
private JPanel panel;
private JLabel label1, label2, label3, label4, label5, label6, label7,
label8;
private JTextField text1, text2, text3, text4, text5, text6, text7, text8;
public Application() {
JFrame gui = new JFrame();
gui.setLayout(new GridLayout(8, 2));
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Vacation Expenses");
gui.setSize(500, 500);
panel = new JPanel();
gui.add(panel);
label1 = new JLabel("Number of days on the trip");
label2 = new JLabel("Amount of airfare");
label3 = new JLabel("Amount of car rental fees");
label4 = new JLabel(
"Number of miles driven, if a private vehicle was used");
label5 = new JLabel("Amount of parking fees, if any");
label6 = new JLabel("Amount of taxi charges, if any");
label7 = new JLabel("Conference or seminar registration fees, if any");
label8 = new JLabel("Lodging charges, per night");
text1 = new JTextField("0", 10);
text2 = new JTextField("0", 10);
text3 = new JTextField("0", 10);
text4 = new JTextField("0", 10);
text5 = new JTextField("0", 10);
text6 = new JTextField("0", 10);
text7 = new JTextField("0", 10);
text8 = new JTextField("0", 10);
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(label3);
panel.add(text3);
panel.add(label4);
panel.add(text4);
panel.add(label5);
panel.add(text5);
// JButton button = new JButton("Button");
// panel.add(button);
gui.setVisible(true);
}
public static void main(String[] args) {
new Application();
}
}
You should be setting the GridLayout to your panel and not the frame. The panel is the container for the components, so should be the one with the GridLayout
Get rid of gui.setLayout(new GridLayout(8, 2));
And use panel = new JPanel(new GridLayout(8, 2));
Side Notes
Also note you haven't added all your components. You've only added five of each. You're forgetting to add the other three.
Also, your class is already a JFrame. There's no need to create another one. Choose one or the other. Either use the instance JFrame and don't extends JFrame or extend JFrame and don't use the extra instance. I'd go with the former.
Also, it's best to pack() your frame, instead of setSize(). The pack() should be done after adding all your components.
Also, Swing apps should be run from the Event Dispatch Thread. You can accomplish this by wrapping the main method content in a SwingUtilities.invokeLater(...). See more at Initial Threads
Related
I'm stuck with my application. Every time I run my code, my fields e.g. fromTextField once have width 180 other time my width private static final Integer widthField = 232.
Code:
package gui;
import javax.swing.*;
import java.awt.*;
public class MailGui extends JFrame {
private static final Integer widthField = 232;
private MailGui() {
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(5, 5));
JLabel fromLabel = new JLabel("From: ", SwingConstants.LEFT);
JLabel passwdLabel = new JLabel("Password: ", SwingConstants.LEFT);
JLabel toLabel = new JLabel("To: ", SwingConstants.LEFT);
JLabel subjectLabel = new JLabel("Subject: ", SwingConstants.LEFT);
JLabel textLabel = new JLabel("Content: ", SwingConstants.LEFT);
JTextField fromTextField = new JTextField();
JTextField toTextField = new JTextField();
JPasswordField passwdPasswordField = new JPasswordField();
JTextField subjectTextField = new JTextField();
JTextArea textArea = new JTextArea(8, 30);
JButton sendButton = new JButton("Send");
textArea.setLineWrap(true);
northPanel.add(fromLabel);
northPanel.add(fromTextField);
northPanel.add(passwdLabel);
northPanel.add(passwdPasswordField);
northPanel.add(toLabel);
northPanel.add(toTextField);
northPanel.add(subjectLabel);
northPanel.add(subjectTextField);
northPanel.add(textLabel);
northPanel.add(textArea);
this.add(northPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.add(sendButton);
add(southPanel, BorderLayout.SOUTH);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
fromTextField.setBounds(textArea.getX() + 100, 0, widthField, 19);
passwdPasswordField.setBounds(textArea.getX() + 100, 19, widthField, 19);
toTextField.setBounds(textArea.getX() + 100, 38, widthField, 19);
subjectTextField.setBounds(textArea.getX() + 100, 57, widthField, 19);
}
public static void main(String[] args) {
new MailGui();
}
}
What I have:
Or
What I except:
Thanks for every help. Q.
Invoking the setBounds() method does nothing. The layout manager will override the size/location based on the rules of the layout manager. In the case of the GridLayout all components will be sized to the preferred size of the largest component or as the frame size is changes each cell will adjust to fill the space available in the frame.
When you create a JTextField the code should be something like:
JTextField textField = new JTextField(15);
This will allow the text field to determine its own preferred size to display 15 "W" characters based on the font of the text field.
Then the layout manager can do a better job at determining the size of each component
If you want the widths of the labels and the text fields to be different, then you need to use a different layout manager. Probably a GridBagLayout. Read the Swing tutorial on How to Use GridBagLayout for more information and examples.
Note the tutorial examples show you how to create the GUI on the Event Dispatch Thread (EDT).
Call pack() at the end of the GUI composition in order to layout it in a definite way once.
The dependency of the geometry to textArea is unfortunate. Put it in the layout too.
There are nice GUI editors with more complex layout managers.
I am very new to Java and I'm trying to put together a simple time calculator.
How come the add() method only throws up the last thing I added? When I run the program it only shows "Days" instead of the textboxes and the years label.
import javax.swing.*;
public class TimeCalculator extends JFrame
{
public static void main(String[] args)
{
JOptionPaneMultiInput window = new JOptionPaneMultiInput();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,500);
window.setVisible(true);
}
public TimeCalculator()
{
super("Time Calculator");
JTextField yearsField = new JTextField(5);
JTextField daysField = new JTextField(5);
JTextField hoursField = new JTextField(5);
JTextField minutesField = new JTextField(5);
JTextField secondsField = new JTextField(5);
JLabel yearsLabel = new JLabel();
JLabel daysLabel = new JLabel();
JLabel hoursLabel = new JLabel();
JLabel minutesLabel = new JLabel();
JLabel secondsLabel = new JLabel();
JCheckBox yearsCheckbox = new JCheckBox();
JCheckBox daysCheckbox = new JCheckBox();
JCheckBox hoursCheckbox = new JCheckBox();
JCheckBox minutesCheckbox = new JCheckBox();
JCheckBox secondsCheckbox = new JCheckBox();
JLabel yearsCLabel = new JLabel();
JLabel daysCLabel = new JLabel();
JLabel hoursCLabel = new JLabel();
JLabel minutesCLabel = new JLabel();
JLabel secondsCLabel = new JLabel();
JButton convertButton = new JButton();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
yearsLabel.setText("Years");
daysLabel.setText("Days");
hoursLabel.setText("Hours");
minutesLabel.setText("Minutes");
secondsLabel.setText("Seconds");
yearsCLabel.setText("Yr");
daysCLabel.setText("D");
hoursCLabel.setText("Hr");
minutesCLabel.setText("Min");
secondsCLabel.setText("Sec");
convertButton.setText("Convert");
convertButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//doConvert(evt); this will be added later once i figure everything out
}
});
add(yearsField);
add(yearsLabel);
add(daysField);
add(daysLabel);
}
}
JOptionPaneMultiInput mentioned in main() is not part of the posted source code. Consider posting an SSCCE.
The answer to:
When I run the program it only shows "Days" instead of the textboxes
and the years label.
TimeCalculator that appears in the question extends JFrame. By default JFrame uses BorderLayout layout. When BorderLayout is used, add() method without constraints argument results in BorderLayout.CENTER constraint to add components. So you add your objects to the center of BorderLayout. Every subsequent add() replaces the previous component that was added. At the end, only daysLabel remains.
See How to Use BorderLayout for more details. Also see A Visual Guide to Layout Managers for other layout managers as you have many controls in your frame and it would be hard to lay it out without additional nesting panels.
I'm working with GUI in Java and I've made several JDialogs opening one above the other.
I tried to create a JTabbedPane and I have succeed. However, I have to make the JTabbedPane in a JFrame. I've tried but the JPanel opens all blank.
Second of all when I use JFrame (so the new JTabbedPane became operational) that same frame appears behind the previous one.
So my questions are:
How can I create the tabbed pane in a JDialog ?
How do I make the JTabbedPane appear in front of all other frames, if I use JFrame ?
Here's my code, this JFrame opened when I click on a JButton from a previous JDialog
public class AddComponents extends JDialog {
private String[] arr = {"House", "Microgrid", "CSP", "VPP"};
public AddComponents(JDialog pai, String titulo)
{
super(pai, titulo);
frame = new JFrame(titulo);
// Display the window.
frame.setSize(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set grid layout for the frame
frame.getContentPane().setLayout(new GridLayout(1, 1));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
pack();
for (int i = 0; i < arr.length; i++) {
String tmp = arr[i];
tabbedPane.addTab(tmp, makePanel(tmp));
}
frame.getContentPane().add(tabbedPane);
frame.setMinimumSize(new Dimension(getWidth(), getHeight()));
frame.setLocation(pai.getX() + 85, pai.getY() + 25);
frame.setEnabled(true);
}
private JPanel makePanel(String text) {
JPanel p = new JPanel();
//p.setLayout(new GridLayout(0,1));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
if(text.equals("House"))
{ //CADA UM DOS ifs chama a class correspondente para criar o interface
p1.setLayout(new GridLayout(4, 2));
idLabel = new JLabel("Component ID:");
idText = new JTextField("");
p1.add(idLabel);
p1.add(idText);
maxUsageLabel = new JLabel("Max usage per hour:");
maxUsageText = new JTextField("");
p1.add(maxUsageLabel);
p1.add(maxUsageText);
minUsageLabel = new JLabel("Min usage per hour:");
minUsageText = new JTextField("");
p1.add(minUsageLabel);
p1.add(minUsageText);
averageUsageLabel = new JLabel("Average usage per hour:");
averageUsageText = new JTextField("");
p1.add(averageUsageLabel);
p1.add(averageUsageText);
// emptyLabel = new JLabel("");
saveButton = new JButton("Save");
// p.add(emptyLabel);
p2.add(saveButton);
p.add(p1);
p.add(p2);
}
if(text.equals("Microgrid"))
{
p.setLayout(new GridLayout(5, 2));
outroLabel = new JLabel(" Microgrid");
p.add(outroLabel);
}
if(text.equals("VPP"))
{
p.setLayout(new GridLayout(5, 2));
outroLabel = new JLabel(" VPP");
p.add(outroLabel);
}
if(text.equals("CSP"))
{
p.setLayout(new GridLayout(5, 2));
outroLabel = new JLabel(" CSP");
p.add(outroLabel);
}
return p;
}
}
"How can I create the tabbed pane in a JDialog ?"
same as you would if you added it to a JFrame. There is essentially no difference here whatsoever.
"How do I make the JTabbedPane appear in front of all other frames, if I use JFrame ?"
you don't. You use a JDialog if you want to display a window above other windows.
For creating the JDialog use:
final JDialog dialog = new JDialog();
dialog.add(tabbedPane);
dialog.setVisible(true);
Java applications normally have only one JFrame, so nobody worries about the Z-order. If you like them, you can use JInternalFrame. Here is the tutorial. You can, however, use dialogs instead.
I'm having an issue where my JRadioButtons will not appear until moused over. I've looked up this issue before and it seems most people have solved it using layouts. However, I am not supposed to use them for my assignment, being completely new to graphics with Java I'm really struggling. Any ideas? Anything is appreciated.
import java.awt.GridLayout;
import javax.swing.*;
public class InsuarancePolicyApp {
public static void main(String[] args) {
//JFrame
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(800, 600);
f.setLayout(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Insurance Policy Application");
//JButtons
JButton addClient = new JButton("Add Client");
JButton openPolicy = new JButton("Open Policy");
f.getContentPane().add(addClient);
f.getContentPane().add(openPolicy);
openPolicy.setSize(300, 60);
addClient.setSize(380,60);
addClient.setLocation(30, 180);
openPolicy.setLocation(450, 180);
//JTextField
JTextField name = new JTextField("Name: ");
f.getContentPane().add(name);
name.setLocation(30,30);
name.setSize(380, 30);
//JList
String[] clientarray = {"Mark Mywords", "Jim Class", "Stan Dupp", "Mel Onhead", "Bob's Yoyo Shop", "Toys Aren't Us", "The Fish Rack"};
JList clients = new JList(clientarray);
f.getContentPane().add(clients);
clients.setLocation(30, 280);
clients.setSize(380, 250);
String[] policyarray = {"Policy 002354","Policy 005345", "Depreciable Policy 0789423", "Expirable Policy 009724"};
JList policies = new JList(policyarray);
f.getContentPane().add(policies);
policies.setLocation(450, 280);
policies.setSize(300, 250);
//JScrollPane
JScrollPane clientScroll = new JScrollPane(clients, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
f.getContentPane().add(clientScroll);
clientScroll.setLocation(30,280);
clientScroll.setSize(380,250);
JScrollPane policiesScroll = new JScrollPane(policies, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
f.getContentPane().add(policiesScroll);
policiesScroll.setLocation(450,280);
policiesScroll.setSize(300,250);
//JradioButons
JRadioButton b1 = new JRadioButton("Company",false);
JRadioButton b2 = new JRadioButton("Individual",false);
JRadioButton b3 = new JRadioButton("Standard",false);
JRadioButton b4 = new JRadioButton("Depreciable",false);
JRadioButton b5 = new JRadioButton("Expirable",false);
//ButtonGroups
ButtonGroup clientsGroup = new ButtonGroup();
b1.setLocation(120, 70);
b1.setSize(100,30);
b2.setLocation(260, 70);
b2.setSize(100,30);
f.getContentPane().add(b2);
f.getContentPane().add(b1);
clientsGroup.add(b1);
clientsGroup.add(b2);
ButtonGroup policiesGroup = new ButtonGroup();
b3.setLocation(600, 10);
b4.setLocation(600, 60);
b5.setLocation(600, 110);
b3.setSize(100,60);
b4.setSize(100,60);
b5.setSize(100,60);
f.getContentPane().add(b3);
f.getContentPane().add(b4);
f.getContentPane().add(b5);
policiesGroup.add(b3);
policiesGroup.add(b4);
policiesGroup.add(b5);
//Jlabel
JLabel label = new JLabel("Type:");
f.getContentPane().add(label);
label.setLocation(30, 55);
label.setSize(60,60);
JLabel label2 = new JLabel("Type:");
f.getContentPane().add(label2);
label2.setLocation(545, 10);
label2.setSize(60,60);
}
}
The problem is that the JRadioButtons are not being painted as the JFrame has already been displayed when they are added.
You need to call JFrame#setVisible after you add all the components to the container:
f.setVisible(true);
Aside: Don't use absolute positioning (null layout), use a layout manager instead. Using a layout manager removes the need for the setting component sizes & positions.
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