MiG Layout bad behavior - java

I'm sorry if this is stupid question, but I couldn't find the answer to this. I am trying to make simple login page to my java program. It contains JLayeredPane settings and login. Also there is one JSplitPane which contains two JSrollpane consolepanel and changelogpanel. So the problem is that I have added JSplitPane and Settings layeredpane but when I am adding login layeredpane it goes same line as settingspanel as it belongs to, but it also goes next to splitpane so it looks like this:
[----]
[-]...[-]
and it's supposed to be:
[----]
[-][-]
Here is screenshot
Main.java
package Main;
import javax.swing.JFrame;
import Development.Version;
import GameEngine.GameEngine;
public class Main {
private static String title = "2D SquareWorld 0.";
private static JFrame window;
public static void main(String[] args) {
GameEngine game = new GameEngine();
window = new JFrame();
window.setTitle("2D SquareWorld 0." + Version.newVersion());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.add(game);
window.add(new GUI());
window.pack();
window.setSize(1000, 720);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
GUI.java
package Main;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import net.miginfocom.swing.MigLayout;
public class GUI extends JPanel {
private static final long serialVersionUID = 1L;
private JSplitPane Splitpanel;
private JScrollPane consolepanel, changelogpanel;
private JPasswordField password;
private JLabel usernametext, passwordtext;
private JButton update, register, login;
private JCheckBox keepLogged;
private JTextField username, server;
private JTextPane console, changelog;
private JLayeredPane loginlayer, settingslayer;
public GUI() {
setLayout(new MigLayout());
settingslayer = new JLayeredPane();
settingslayer.setBorder(BorderFactory.createTitledBorder(""));
loginlayer = new JLayeredPane();
loginlayer.setBorder(BorderFactory.createTitledBorder(""));
username = new JTextField();
password = new JPasswordField();
usernametext = new JLabel("Username:");
passwordtext = new JLabel("Password:");
update = new JButton("Update");
register = new JButton("Register");
login = new JButton("Login");
keepLogged = new JCheckBox("Keep me logged in");
server = new JTextField();
server.setEditable(false);
server.setText("jdbc:mysql://sql4.freemysqlhosting.net");
loginlayer.add(server);
loginlayer.add(keepLogged);
loginlayer.add(login);
loginlayer.add(update);
loginlayer.add(register);
loginlayer.add(usernametext);
loginlayer.add(passwordtext);
loginlayer.add(username);
loginlayer.add(password);
console = new JTextPane();
console.setContentType("text/html");
console.setEditable(false);
console.setText("<center><h1><u>Console:</u></h1></center>");
changelog = new JTextPane();
changelog.setContentType("text/html");
changelog.setEditable(false);
changelog.setText("<center><h1><u>Changelog:</u></h1></center>");
consolepanel = new JScrollPane(console);
consolepanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
consolepanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
changelogpanel = new JScrollPane(changelog);
changelogpanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
changelogpanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Splitpanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, consolepanel, changelogpanel);
Splitpanel.setOneTouchExpandable(true);
Splitpanel.setDividerLocation(480);
add(Splitpanel, "w 100%, h 80%, wrap");
add(settingslayer, "w 50%, h 20%");
add(loginlayer, "w 50%, h 20%");
}
}
I'm sorry for my bad english. This is my first question in stackoverflow so just tell me if I did something wrong. Thanks for help!

add(Splitpanel, "w 100%, h 80%, wrap");
should be
add(Splitpanel, "w 100%, h 80%, spanx, wrap");

Related

MigLayout: reference component width by id

I would like to layout my components as shown in this picture.
In short:
aTextField must have a fixed size of 250px;
bButton has a fixed size that dependes on the text label;
bTextField should grow so that it's width plus bButton width reach
250px.
This is my code:
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutIdReference extends JFrame {
private final MigLayout migLayout = new MigLayout("debug", "", "");
private final JLabel aLabel = new JLabel("Label A");
private final JTextField aTextField = new JTextField();
private final JLabel bLabel = new JLabel("Label B");
private final JTextField bTextField = new JTextField();
private final JButton bButton = new JButton("B Button");
public MigLayoutIdReference() {
Container container = getContentPane();
container.setLayout(migLayout);
add(aLabel, "");
add(aTextField, "id aTextField, w 250!, wrap");
add(bLabel, "");
add(bTextField, "width aTextField.w-bButton.w");
add(bButton, "id bButton, wrap");
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MigLayoutIdReference();
}
}
Unfortunately it seems that MigLayout does not allow to calculate width based on other components that you recall by id.
When running my code I get:
Caused by: java.lang.IllegalArgumentException: Size may not contain links
Am I missing something? Apart from referencing components by id, how could I achieve the desired result?
I changed the MigLayout constructor invocation and added row constraints and column constraints.
I made aTextField span two columns.
I gave bTextField the growx constraint.
Now the width of bTextField will adjust so that together with the width of bButton it will match the width of aTextField.
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutIdReference extends JFrame {
private final MigLayout migLayout = new MigLayout("debug", "[][grow][]", "[][]");
private final JLabel aLabel = new JLabel("Label A");
private final JTextField aTextField = new JTextField();
private final JLabel bLabel = new JLabel("Label B");
private final JTextField bTextField = new JTextField();
private final JButton bButton = new JButton("B Button");
public MigLayoutIdReference() {
Container container = getContentPane();
container.setLayout(migLayout);
add(aLabel, "");
add(aTextField, "id aTextField, w 250!, wrap, span 2");
add(bLabel, "");
add(bTextField, "growx");
add(bButton, "id bButton,wrap");
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MigLayoutIdReference();
}
}
Here is a screen capture:

How can I draw multiple JLabels in different places? (icons don't show up)

I am trying to draw multiple icons in many different locations using for loop. For some reason they just don't show up. I don't know what I'm missing – only clue I found was about setting layout to null, but IntelliJ overwrites it.
Icons should show up in "mapa" panel. I tried adding them manually, but nothing changed.
My code:
package okna;
import logistyka.Walker;
import logistyka.errand.Errand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class WalkerGUI extends JFrame{
private JPanel mainPanel;
private JLabel walkerName;
private JTextField walkerNameField;
private JLabel walkerAddress;
private JTextField walkerAddressField;
private JButton searchErrandsButton;
private JComboBox errandsComboBox;
private JLabel errandsList;
private JTextField walletValue;
private JLabel Wallet;
private JRadioButton archivalErrandsRadioButton;
private JRadioButton currentErrandsRadioButton;
private JButton payOutButton;
private JButton seeProfileButton;
private JPanel mapa;
ArrayList<Errand> masterErrandList = new ArrayList<>();
public WalkerGUI(Walker w, ArrayList<Errand> masterErrandList) {
setContentPane(mainPanel);
ArrayList<JLabel> errandsLabels = new ArrayList<>();
ImageIcon x = new ImageIcon(System.getProperty("user.dir") + "\\src\\x.png");
this.masterErrandList = masterErrandList;
for (Errand errand: masterErrandList) {
JLabel label = new JLabel("whtvr");
label.setIcon(x);
label.setLocation((int)errand.getAddress().getX(),(int)errand.getAddress().getY());
label.setMinimumSize(new Dimension(20,20));
label.setPreferredSize(new Dimension(20,20));
label.setVisible(true);
errandsLabels.add(label);
}
walkerNameField.setText(w.getDescription().getName());
walkerAddressField.setText(w.getDescription().getHomeRegion().getCurrentAddress().toString());
walletValue.setText(String.valueOf(w.getWalletSatus()));
seeProfileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new ProfileGUI(w);
frame.pack();
frame.setVisible(true);
}
});
payOutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
w.setWalletSatus(0);
walletValue.setText(String.valueOf(w.getWalletSatus()));
}
});
}
}
You can use SpringLayout (rather than null layout). Method Errand.getAddress().getX() will return the distance of the left edge of the JLabel from the left edge of its container while Errand.getAddress().getY() will return the distance of the top edge of the JLabel from the top edge of its container.
The code in your question is not a minimal, reproducible example so the below code should be considered as a proof of concept.
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class SprinGui {
private void createAndDisplayGui() {
JFrame frame = new JFrame("Spring");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
Point[] points = new Point[]{new Point(5, 5),
new Point(5, 100),
new Point(225, 150),
new Point(250, 210)};
Class<?> meClass = getClass();
Icon[] icons = new Icon[4];
icons[0] = new ImageIcon(meClass.getResource("coffee.png"));
icons[1] = new ImageIcon(meClass.getResource("dollar.png"));
icons[2] = new ImageIcon(meClass.getResource("dynamite.png"));
icons[3] = new ImageIcon(meClass.getResource("soccer-player.png"));
for (int i = 0; i < 4; i++) {
JLabel label = new JLabel(icons[i]);
contentPane.add(label);
layout.putConstraint(SpringLayout.WEST,
label,
points[i].x,
SpringLayout.WEST,
contentPane);
layout.putConstraint(SpringLayout.NORTH,
label,
points[i].y,
SpringLayout.NORTH,
contentPane);
}
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SprinGui instance = new SprinGui();
EventQueue.invokeLater(() -> instance.createAndDisplayGui());
}
}
This is how the GUI looks.
Note that How to Use Icons may also be helpful.

JAVA - How to access parent frame component in action listener?

this is my code
This code gives me a frame with text displayed inside it.
I may need to modify the text as necessary, and then there are two buttons. One pushes the code further, the other one closes the application.
What I want to do is add listener to okButt, within the createOverviewButtonsPanel method, that would retrieve the value of txtMenuOverview in order to pass it further is this even possible?
MenuOverviewFrame class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class MenuOverviewFrame extends JFrame{
private static final long serialVersionUID = -5908534022988507381L;
private static final Font FONT = new Font("Courier", Font.BOLD, 16);
private static final Font MENU_FONT = new Font(Font.MONOSPACED,Font.BOLD,14);
private static final Color BLUE_STEEL = new Color(70, 107, 176);
private static final Dimension INITIAL_SIZE = new Dimension(500, 300);
private static final Dimension MINIMUM_SIZE = new Dimension(275, 150);
public static void main(String[] args) {
System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
SwingUtilities.invokeLater(() -> {
MenuOverviewFrame frame = new MenuOverviewFrame("Test test\ntest\ntest");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public MenuOverviewFrame(String menuOutput) {
super("Daily Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
getContentPane().setBackground(Color.WHITE);
setSize(INITIAL_SIZE); // The initial frame size
setMinimumSize(MINIMUM_SIZE);
JTextArea txtMenuOverview = new JTextArea(menuOutput);
txtMenuOverview.setFont(MENU_FONT);
JScrollPane taScroll = new JScrollPane(txtMenuOverview);
add(taScroll);
JPanel overviewButtonsPanel = createOverviewButtonsPanel();
overviewButtonsPanel.setPreferredSize(new Dimension(overviewButtonsPanel.getPreferredSize().width, overviewButtonsPanel.getPreferredSize().height + 30));
getContentPane().add(overviewButtonsPanel, BorderLayout.SOUTH); // at the center
}
private JPanel createOverviewButtonsPanel() {
JPanel panel = new JPanel();
//panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 1));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0,0,0,20);
panel.setBackground(BLUE_STEEL);
JButton okButt = new JButton("Send menu");
JButton koButt = new JButton("Abort mission");
panel.add(okButt,gbc);
panel.add(koButt);
okButt.setVerticalAlignment(SwingConstants.CENTER);
return panel;
}
}
Thank you

How do I change the size of my JButton?

I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?
This is the code to my class referencing to another class in the project containing the grid:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Scoreboard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
public Scoreboard (int score){
setLayout(new BorderLayout());
setSize(490,400);
setPreferredSize(getSize());
setBackground(Color.BLUE);
title = new JLabel();
title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
title.setSize(200,200);
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
coord.setSize(200,400);
coord.setBackground(Color.RED);
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
}
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class Scoreboard extends JPanel{
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
private final int W = 490;
private final int H = 400;
public Scoreboard (int score){
setLayout(new BorderLayout());
setPreferredSize(new Dimension(W, H));
setBackground(Color.BLUE);
title = new JLabel("My Title");
//if you use images in your SO posted code use web links
//title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
//title.setSize(200,200); run the code without it and see it has no effect
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
//this is directly related to your question. You can't add 2 components
//to the center.
//instead add a JPanel to the center, apply a layout manager to it,
//and add scorelabel and quit button to that JPanel
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
//coord.setSize(200,400); run the code without it and see it has no effect
coord.setBackground(Color.RED);
coord.setOpaque(true); //if you want the color show
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
//no need to set bounds. That is what the layout manager does
//quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
//add main to your questions to make it runnable
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new Scoreboard(50);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

How can I properly align my labels?

More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.
I've uploaded an image of the current program running :
As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.
Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.
Thanks for taking the time to read this!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
//Bottom Panel
JPanel GradePanel = new JPanel();
GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
GradePanel.setOpaque(false);
GradePanel.setPreferredSize(new Dimension(0 , 100));
GradePanel.add(resultField);
resultField.setAlignmentX(LEFT_ALIGNMENT);
GradePanel.add(nameResult);
GradePanel.add(gradeResult);
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(GradePanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and then the driver class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
Take time to read this the most flexible Layout Manager that commonly used by programmer :)
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read.
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
myBottomPanel mybottompanel = new myBottomPanel();//Object
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(mybottompanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class myBottomPanel extends JPanel{
public myBottomPanel()
{
this.setLayout(new GridBagLayout());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Constraints
GridBagConstraints nameResultConstraints = new GridBagConstraints();
GridBagConstraints gradeResultConstraints = new GridBagConstraints();
//Bottom Panel
setBorder(BorderFactory.createTitledBorder("Students/Results"));
setOpaque(false);
setPreferredSize(new Dimension(0 , 100));
nameResultConstraints.anchor = GridBagConstraints.LINE_START;
nameResultConstraints.weightx = 0.5;
nameResultConstraints.weighty = 0.5;
add(nameResult,nameResultConstraints);
add(gradeResult);
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and here is your Frame.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
OUTPUT
Hope this helps. :)
If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.
Maybe you can use a GridBagLayout. You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables.

Categories

Resources