I tried to do this from stackoverflow:
adding multiple jPanels to jFrame
But that didn't seem to work out like in the example, could anyone tell me what im doing wrong?
Im trying to add multiple JPanels with each their own sizes to the JFrame. I was also hoping it was possible to give each JPanel specific sizes and ability to put them on the exact spot i want.
Picture of what i try to make:
This is my code so far:
public ReserveringenGUI(ReserveringController controller) {
this.controller = new ReserveringController();
makeFrame();
}
public void makeFrame() {
JFrame frame1 = new JFrame();
frame1.setTitle("Reserveringen");
frame1.setSize(800, 500);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
JPanel willekeurigPanel = new JPanel();
willekeurigPanel.setSize(400, 500);
willekeurigPanel.setBackground(Color.YELLOW);
willekeurigPanel.setVisible(true);
JPanel overzichtPanel = new JPanel();
overzichtPanel.setSize(400, 500);
overzichtPanel.setBackground(Color.red);
overzichtPanel.setVisible(true);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
DateFormatter df = new DateFormatter(format);
JFormattedTextField dateBeginField = new JFormattedTextField(df);
dateBeginField.setPreferredSize(new Dimension(250, 20));
dateBeginField.setValue(new Date());
JFormattedTextField dateEndField = new JFormattedTextField(df);
dateEndField.setPreferredSize(new Dimension(250, 20));
dateEndField.setValue(new Date());
JTextField klantnummer = new JTextField();
klantnummer.setPreferredSize(new Dimension(250, 20));
JTextField artikelnummer = new JTextField();
artikelnummer.setPreferredSize(new Dimension(250, 20));
JLabel dateBeginLabel = new JLabel("Begin Datum ");
JLabel dateEndLabel = new JLabel("Eind datum: ");
JLabel klantID = new JLabel("Klant nummer: ");
JLabel artikelID = new JLabel("Artikel nummer: ");
JButton voegReserveringToe = new JButton("Voeg toe");
voegReserveringToe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
voegReserveringToeActionPerformed(evt);
}
});
willekeurigPanel.add(dateBeginLabel);
willekeurigPanel.add(dateBeginField);
willekeurigPanel.add(dateEndLabel);
willekeurigPanel.add(dateEndField);
willekeurigPanel.add(klantID);
willekeurigPanel.add(klantnummer);
willekeurigPanel.add(artikelID);
willekeurigPanel.add(artikelnummer);
willekeurigPanel.add(voegReserveringToe);
container.add(willekeurigPanel);
container.add(overzichtPanel);
frame1.add(container);
frame1.setVisible(true);
}
As discussed here, don't set the size and position of components arbitrarily. Instead, let the layout do the work, nesting as required. Use the GroupLayout shown here for the labeled input fields. Add each to the CENTER of a panel having BorderLayout, with a button in the SOUTH on the left. Finally, add both panels to an enclosing panel having GridLayout(1, 0).
Related
As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);
I'm new to JTable, or GUI for that matter, but i had been given an assignment of building a receipt program inside a GUI. I manage to get the basic things work, but my table looks awful. I need help on how to display the table properly
public static void main (String[] args)
{
ArrayList <item> lol= new ArrayList <item>();
item ayam = new item("ayam",5678);
item kambing= new item("kambing",5014);
item buaya= new item("buaya",3000);
item bocoranquiz= new item("bocoranquiz",5000);
lol.add(ayam);
lol.add(kambing);
lol.add(buaya);
lol.add(bocoranquiz);
JFrame frame= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 0));
frame.setSize(1000, 1000);
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(new Date());
JComboBox combo1= new JComboBox();
combo1.setPreferredSize(new Dimension(10, 10));
combo1.addItem(ayam.getname());
combo1.addItem(kambing.getname());
combo1.addItem(buaya.getname());
combo1.addItem(bocoranquiz.getname());
JLabel label1= new JLabel("Invoice no: ");
JLabel label2= new JLabel("Invoice Date : " + date);
JLabel label3= new JLabel("Item name " );
JLabel label4= new JLabel("Item Price ");
JLabel label5= new JLabel("Item Quantity : ");
JPanel panel1= new JPanel ();
panel1.setLayout(new GridLayout(3,0));
panel1.add(label1);
panel1.add(label2);
class inputListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JComboBox<String> combo= (JComboBox<String>) event.getSource();
selected= (String) combo.getSelectedItem();
alpha=10;
if (selected.equals("ayam"))
{
alpha=5678;
}
else if (selected.equals("kambing"))
{
alpha=5014;
}
else if (selected.equals("buaya"))
{
alpha=3000;
}
else if (selected.equals("bocoranquiz"))
{
alpha=5000;
}
label3.setText("Item name " + selected);
label4.setText("Item quantity " + alpha);
}
}
ActionListener inputAct = new inputListener();
combo1.addActionListener(inputAct);
panel1.add(combo1);
JTextField tf = new JTextField();
JButton adda = new JButton("Add");
String[] columnNames= {"Name","Price","Quantity","Total"};
DefaultTableModel tablemodel= new DefaultTableModel(columnNames,0);
JTable table = new JTable(tablemodel);
JScrollPane scrollPanel = new JScrollPane(table);
class inputListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
quantity= Integer.parseInt(tf.getText());
double total= alpha * quantity;
Object[] data= {selected,alpha,quantity,total};
tablemodel.addRow(data);
}
ActionListener inputAct2 = new inputListener2();
adda.addActionListener(inputAct2);
JPanel panel2= new JPanel();
panel2.setLayout(new GridLayout(10,0));
panel2.add(label3);
panel2.add(label4);
panel2.add(label5);
panel2.add(tf);
panel2.add(adda);
panel2.add(scrollPanel);
frame.add(panel1);
frame.add(panel2);
frame.setVisible(true);
}
Your code is a bit of mess, but, the basic problem is your setting your GridLayout with to many rows, for example
frame.setLayout(new GridLayout(3, 0));
should be
frame.setLayout(new GridLayout(2, 0));
since you're only adding 2 components to the frame
Equally,
panel2.setLayout(new GridLayout(10, 0));
should probably be
panel2.setLayout(new GridLayout(6, 0));
Remember, a GridLayout will divide the container into equal sections, even if there is nothing contained within the row/column.
You may also want consider using a different layout manager, like GridBagLayout, or a combination of layouts depending on your basic needs.
See How to use GridBagLayout for more details.
I have an Interface class that extends JFrame. I am creating 3 JPanels and adding them to a Container (Border Layout) in different areas of the layout.
When I run the application, nothing shows but a blank window and a title. If I resize the application it will then show all the content and work as intended.
I'm not sure what I did differently this time, I've used this method before and it works in previous programs.
Any help is appreciated.
Here is my Interface Class Constructor code: http://pastebin.com/4UyEXsBr
Code:
public class Interface extends JFrame implements ActionListener {
private Container contentPane;
private JPanel buttonPanel, userPanel;
private JButton loginButton, createUserButton, logoutButton, withdrawButton, depositButton, switchToRegisterButton, switchToLoginButton;
private JLabel headerLabel, inputTopJTFLabel, inputPW1JPFLabel, toastLabel, inputPW2JPFLabel;
public JTextField inputTopJTF;
public JPasswordField inputPW1JPF, inputPW2JPF;
JRootPane rootPane;
public Interface(int width, int height, String title) {
//Setting up Interface
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100,100);
setVisible(true);
Font header = new Font("TimesRoman", Font.PLAIN, 50);
///////////////////////BUTTON PANEL///////////////////////
//Button Panel
buttonPanel = new JPanel();
//Buttons
//loginButton
loginButton = new JButton("Login");
loginButton.addActionListener(this);
loginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToRegisterButton
switchToRegisterButton = new JButton("New User?");
switchToRegisterButton.addActionListener(this);
switchToRegisterButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToLoginButton
switchToLoginButton = new JButton("Switch to Login");
switchToLoginButton.addActionListener(this);
switchToLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
switchToLoginButton.setVisible(false);
//createUserButton
createUserButton = new JButton("Register");
createUserButton.addActionListener(this);
createUserButton.setAlignmentX(Component.CENTER_ALIGNMENT);
createUserButton.setVisible(false);
//logoutButton
logoutButton = new JButton("Logout");
logoutButton.addActionListener(this);
logoutButton.setAlignmentX(Component.CENTER_ALIGNMENT);
logoutButton.setVisible(false);
//withdrawButton
withdrawButton = new JButton("Withdraw");
withdrawButton.addActionListener(this);
withdrawButton.setAlignmentX(Component.CENTER_ALIGNMENT);
withdrawButton.setVisible(false);
//depositButton
depositButton = new JButton("Deposit");
depositButton.addActionListener(this);
depositButton.setAlignmentX(Component.CENTER_ALIGNMENT);
depositButton.setVisible(false);
//Adding items to buttonPanel
buttonPanel.add(loginButton);
buttonPanel.add(switchToRegisterButton);
buttonPanel.add(switchToLoginButton);
buttonPanel.add(createUserButton);
buttonPanel.add(logoutButton);
buttonPanel.add(withdrawButton);
buttonPanel.add(depositButton);
///////////////BODY PANEL//////////////////////
//Body Panel
userPanel = new JPanel();
userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.PAGE_AXIS));
//JTextFields
//inputTopJTF
Dimension inputTopJTFDimension = new Dimension(100, 20);
inputTopJTF = new JTextField();
inputTopJTF.setMaximumSize(inputTopJTFDimension);
//inputPW1JPF
Dimension inputPW1JPFDimension = new Dimension(100, 20);
inputPW1JPF = new JPasswordField();
inputPW1JPF.setMaximumSize(inputPW1JPFDimension);
//inputPW2JPF
Dimension inputPW2JPFDimension = new Dimension(100, 20);
inputPW2JPF = new JPasswordField();
inputPW2JPF.setMaximumSize(inputPW2JPFDimension);
inputPW2JPF.setVisible(false);
//JLabels
//toastLabel
toastLabel = new JLabel("Please sign in or create new account.");
toastLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputTopJTFLabel
inputTopJTFLabel = new JLabel("Username:");
inputTopJTFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW1JPFLabel
inputPW1JPFLabel = new JLabel("Password:");
inputPW1JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW2JPFLabel
inputPW2JPFLabel = new JLabel("Confirm Password:");
inputPW2JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPW2JPFLabel.setVisible(false);
//Adding items to userPanel
userPanel.add(toastLabel);
userPanel.add(inputTopJTFLabel);
userPanel.add(inputTopJTF);
userPanel.add(inputPW1JPFLabel);
userPanel.add(inputPW1JPF);
userPanel.add(inputPW2JPFLabel);
userPanel.add(inputPW2JPF);
///////////////CONTENT PANE/////////////////////
//Content Pane
contentPane = getContentPane();
//JLabels
//headerLabel
headerLabel = new JLabel("Bank", SwingConstants.CENTER);
headerLabel.setFont(header);
//PAGE_START
contentPane.add(headerLabel, BorderLayout.PAGE_START);
//LINE_START
//CENTER
contentPane.add(userPanel, BorderLayout.CENTER);
//LINE_END
//PAGE_END
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
userPanel.setFocusable(true);
userPanel.requestFocus();
//Default Button
rootPane = getRootPane();
rootPane.setDefaultButton(loginButton);
}
call
setVisible(true);
in last line .because component added after line setvisible will not be shown until you call repaint(),revalidate().when you resize ,repaint() method get called and frame will visible correctly .so call setvisible after add all component
after line rootPane.setDefaultButton(loginButton); call setvisible
rootPane.setDefaultButton(loginButton);
setVisible(true);//after add all component to frame call setvisible method
this is full working code
So I'm trying to create a gui, I've tinkered with gui's before in java but I'm still new to them. So my issued here is that my JLabels (butLabel & cbLabel) are filled with buttons and checkboxes. Sadly my JFrame will only show whichever is set to the BorderLayout.CENTER. NORTH & SOUTH don't ever show, even if I only set the butLabel to SOUTH and don't even use the cbLabel. What am I overlooking?? It's much appreciated, thanks!
public class mainWindow
{
JFrame frame = new JFrame("Main Window");
JLabel butLabel = new JLabel();
JLabel cbLabel = new JLabel();
JButton showBut = new JButton("Show");
JButton exitBut = new JButton("Exit");
JButton addBut = new JButton("Add");
JButton remBut = new JButton("Remove");
JCheckBox aCB = new JCheckBox("Airplane");
JCheckBox bCB = new JCheckBox("Boat");
JCheckBox cCB = new JCheckBox("Clock");
public mainWindow()
{
frame.setLayout(new BorderLayout()); //I know this is set by default to BorderLayout but I just did it when I was out of options to try.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(360, 480));
butLabel.setLayout(new GridLayout(1,4));
cbLabel.setLayout(new GridLayout(2, 2));
butLabel.add(showBut);
butLabel.add(exitBut);
butLabel.add(addBut);
butLabel.add(remBut);
cbLabel.add(aCB);
cbLabel.add(bCB);
cbLabel.add(cCB);
frame.add(butLabel, BorderLayout.CENTER);
frame.add(cbLabel, BorderLayout.NORTH);
}
public void setVisible()
{
butLabel.setVisible(true);//Didn't think I needed butLabel.setVisible or the cbLabel.setVisible but
cbLabel.setVisible(true);//again I was trying things that I thought might make sense.
frame.setVisible(true);
}
}
do not use Label for grouping elements, use JPanel instead
I have tried replace all
Label
with
Panel
it works
I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.