border and panel orginization - java

I'm having a very hard time with borders, I've looked through tutorials and examples and each seems to use a different style, I'm just trying to organise the content into separated borders. The content for the bottom panal isn't finished yet but I'm just trying to get it to work as is before adding more.
The compiler says there are problems on two lines java.lang.NullPointerException:
package question2;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
* #author Matt Headley
This frame shows a data set and its statistics.
*/
public class ComputerStoreGUI extends JFrame
{
private JCheckBox item1;
private JCheckBox item2;
private JCheckBox item3;
private JCheckBox item4;
private JCheckBox item5;
private TitledBorder border;
private TitledBorder border2;
private static JPanel content;
private static JPanel top;
private static JPanel bottom;
private JTextField parts;
public ComputerStoreGUI()
{
JCheckBox item1 = new JCheckBox("Install Hard Drive - $25.00");
JCheckBox item2 = new JCheckBox("Install RAM - $15.00");
JCheckBox item3 = new JCheckBox("Remove Virus - $50.00");
JCheckBox item4 = new JCheckBox("Format Hard Drive - $80.00");
JCheckBox item5 = new JCheckBox("Quote Hourly Labour - $10.00");
item1.setHorizontalAlignment(JCheckBox.LEFT);
item2.setHorizontalAlignment(JCheckBox.LEFT);
item3.setHorizontalAlignment(JCheckBox.LEFT);
item4.setHorizontalAlignment(JCheckBox.LEFT);
item5.setHorizontalAlignment(JCheckBox.LEFT);
JTextField cost = new JTextField(10);
top = new JPanel(new FlowLayout(FlowLayout.LEFT));
top.add(item1);
top.add(item2);
top.add(item3);
top.add(item4);
top.add(item5);
bottom.add(cost); //here ????????
cost.setHorizontalAlignment(JTextField.CENTER);
}
public static void main(String[] args)
{
JFrame frame = new ComputerStoreGUI(); // and here ???????
content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
top = new JPanel();
top.setBorder(BorderFactory.createTitledBorder("Standard Services"));
bottom = new JPanel();
bottom.setBorder(BorderFactory.createTitledBorder("Hourly Service"));
frame.setSize(250, 400);
frame.setTitle("LU Computer Store");
frame.setContentPane(content);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content.add(top);
content.add(bottom);
frame.setVisible(true);
}
}
the end goal is to look something like this:

First, I dont see a reson to extend JFrame in your example. So without inheritance you can use composition like:
JFrmae frame = new JFrame();
Read more: Why do we need to extend JFrame in a swing application?
The compiler says there are problems on two lines
java.lang.NullPointerException:
Reason is, you have declared the JPanel bottom but without initializing you are trying to use it, from this line: bottom.add(cost);
Do something like:
bottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
bottom.add(cost);
EDIT:
comment: It runs now, but the panels are tiny
Because you need to set layout for the parent JPanel, you can use BoxLayout, to add child panels one below another, like below:
content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
In case if you want to add space between those two child panels, use as below:
content.add(top);
content.add(Box.createRigidArea(new Dimension(0,10)));
content.add(bottom);

Related

Set minimum width in side panel of Swing BorderLayout

I understand some parts of BorderLayout -- e.g., the EAST/WEST (or BEGINNING_OF_LINE/END_OF_LINE) panel component stays one width and its length is stretched with the length of the window.
I want to put a panel on the WEST side that itself has multiple components - a panel of buttons and a JList of things the buttons control, in this case. I would like to allocate a minimum width for the strings in that JList, but something (probably BorderLayout) prevents me from setting a minimum or preferred width.
When I run the code below, the list in the left panel is wide enough for "LongNameGame 3", but only because I added the string before rendering the list. I would like to set the width of that JList to accommodate strings of the width of my choice. Later I'll put it in a ScrollPane for strings wider than that, but that's a different problem.
My question is not answered by referring me to other layout managers -- I want to know how to do this with BorderLayout, if possible.
package comm;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class BLPlay
{
public static void main(String ... arguments)
{
JFrame frame = buildLoungeFrame();
frame.setVisible(true);
}
private static JFrame buildLoungeFrame()
{
JFrame loungeFrame = new JFrame("BLPlay");
loungeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loungeFrame.setLayout(new BorderLayout(10,10));
// left panel is another BorderLayout panel with buttons and a list of games
JPanel gameListControlPanel = new JPanel(new BorderLayout());
Border innerBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
Border outerBorder = BorderFactory.createEmptyBorder(3,3,3,3);
gameListControlPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
String[] gamePanelButtonLabels = { "New", "Join", "Leave", "End" };
JPanel gamePanelButtons = new JPanel(new GridLayout(gamePanelButtonLabels.length,1));
addButtons(gamePanelButtons, gamePanelButtonLabels);
JPanel gamePanelButtonsContainerPanel = new JPanel();
gamePanelButtonsContainerPanel.add(gamePanelButtons);
gameListControlPanel.add(gamePanelButtonsContainerPanel, BorderLayout.WEST);
Vector<String> gameList = new Vector<>();
gameList.add("Game 1");
gameList.add("Game 2");
gameList.add("LongNameGame 3");
JList<String> gameJList = new JList<>(gameList);
JPanel gameListPanel = new JPanel(new FlowLayout());
gameListPanel.setMinimumSize(new Dimension(600,600)); // <-- has no effect
gameListPanel.add(gameJList);
gameListControlPanel.add(gameListPanel, BorderLayout.EAST);
loungeFrame.add(gameListControlPanel, BorderLayout.WEST);
// center panel in the lounge is for chat messages; it has a separate border layout,
// center for accumulated messages, bottom for entering messages
JPanel chatMessagePanel = new JPanel(new BorderLayout());
// Border chatMessagePanelBorder = BorderFactory.createEmptyBorder(7,7,7,7);
// chatMessagePanel.setBorder(chatMessagePanelBorder);
JTextArea chatMessages = new JTextArea();
chatMessagePanel.add(chatMessages, BorderLayout.CENTER);
// debug
chatMessages.append("message one\n");
chatMessages.append("message two\n");
chatMessages.append("message three\n");
// and lower panel is for entering one's own chat messages
JPanel chatMessageEntryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JTextField chatMessageEntryField = new JTextField(35);
JButton chatMessageEntryButton = new JButton("Enter");
chatMessageEntryPanel.add(chatMessageEntryField);
chatMessageEntryPanel.add(chatMessageEntryButton);
chatMessagePanel.add(chatMessageEntryPanel, BorderLayout.SOUTH);
loungeFrame.add(chatMessagePanel, BorderLayout.CENTER);
loungeFrame.pack();
return loungeFrame;
}
private static void addButtons(JPanel panel, String ... labels)
{
for (String label : labels)
{
JButton button = new JButton(label);
panel.add(button);
}
}
}
Give the JList a prototype cell value that is wide enough to display what you need. e.g.,
gameJList.setPrototypeCellValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
The prototype value (here a String because the list has been declared as a JList<String>) is used to set the list's preferred size, but is not displayed in the JList. You can use as large or small a list as you need. Also be sure to set visible row count for the same purpose in the horizontal dimension:
gameJList.setVisibleRowCount(20); // for example

JSplitPane ignoring alignment

Hello StackExchange community,
I'm at my wits end about this JSplitPane I'm trying to put into my frame, it is sitting on the right side of my frame instead of filling it up or atleast sitting on the left.
If anyone could help me with this issue I'd be very thankful.
See below an image of my problem and the code
The problem area is the pane with "tab1" and "tab2", the divider and the pane on the right side of that divider:
I've tried setting setAlignmentX(Component.LEFT_ALIGNMENT) on all the individual parts of the JSplitPane. I've also tried making a JPanel to hold it and aligning that. All to no avail.
Furthermore, existing information I've been able to find hasn't been relevant, mostly people discussing how to align the contents of the JSplitPane.
The code below is all that is needed to make this frame, if any of you need it to help me out feel free.
package test;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
public class FrameMaker {
public int x = 0;
private ArrayList<String> mpLabels;
private JFrame theFrame;
public void MakeFrame() {
theFrame = new JFrame("title");
theFrame.getContentPane().setLayout(new BoxLayout(theFrame.getContentPane(), BoxLayout.Y_AXIS));
mpLabels = new ArrayList<String>();
//label1
JPanel bgSwitches = new JPanel();
JLabel calcsLabel = new JLabel("top label, broadened with lines to exaggerate problem-------------------------------------------");
bgSwitches.add(calcsLabel);
//label2
JPanel topLevel = new JPanel();
JLabel textinfo = new JLabel("label below that");
topLevel.add(textinfo);
//splitpane tabs
mpLabels.add("tab1");
mpLabels.add("tab2");
String[] mpLabelsAr = new String[mpLabels.size()];
JList<String> posL = new JList<String>(mpLabels.toArray(mpLabels.toArray(mpLabelsAr)));
posL.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//panel inside the right splitpane pane, this is needed for something later.
JPanel RPanel = new JPanel();
RPanel.setLayout(new BoxLayout(RPanel, BoxLayout.Y_AXIS));
JScrollPane scrollPos = new JScrollPane(posL);
JScrollPane scrollROI = new JScrollPane(RPanel);
JSplitPane posPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scrollPos,scrollROI);
posPanel.setOneTouchExpandable(false);
posPanel.setDividerLocation(75);
//label and textfield
JLabel msLabel = new JLabel("another label");
JTextField msField = new JTextField("textfield");
JPanel buttonPanel = new JPanel();
buttonPanel.add(msLabel);
buttonPanel.add(msField);
bgSwitches.setBackground(new Color(0,0,255));
theFrame.add(bgSwitches);
topLevel.setBackground(new Color(0,255,0));
theFrame.add(topLevel);
posPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
posPanel.setBackground(new Color(0,255,255));
theFrame.add(posPanel);
buttonPanel.setBackground(new Color(255,0,0));
theFrame.add(buttonPanel);
theFrame.pack();
theFrame.setVisible(true);
}
}
You need to align all of your other elements to the left as well.
bgSwitches.setAlignmentX(Component.LEFT_ALIGNMENT);
topLevel.setAlignmentX(Component.LEFT_ALIGNMENT);
buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
You can also add posPanel.setResizeWeight(VALUE BETWEEN 0 AND 1); to specify what percent of the space the JSplitPane should occupy and it will resize with your window.

How to correctly align two JPanel inside a JFrame

I'm building an interface for a little game/exercise. In this interface, I got a top section, witch is a JPanel, that takes the width of the window and a certain height. Right under it is an other section (JPanel again) that is suppose to align to the left and be wright under the first section.
I've been struggling to make the interface looks like what I want. I tried two things, and but failed:
The first one is that I have GameView Class that extends JFrame and I create a JPanel for both section and directly add them to the JFrame, but it seems like they just ends up over each other. The black section is the first one and the red is the second one:
The second thing I tried is putting both of those JPanel inside an other JPanel called container, but still don't get what I want. The first section is perfect, but the second should stick to the left and I would like to have no space between the two sections:
How can I stick the second section (the red one) to the left and have no space between the two sections? Here is the code of my class:
package game;
import java.awt.Color;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GameView extends JFrame //implements MouseListener
{
private GameNumView numberPanel;
private JLabel butLabel;
private JLabel progresLabel;
private JButton nextButton;
private JButton giveUpButton;
private JButton resetButton;
private JCheckBox findMeanCheckBox;
private JCheckBox noiseCheckBox;
public GameView()
{
initUI();
}
public void initUI()
{
setTitle("Sommurai");
setSize(800, 350);
setLocationRelativeTo(null);
butLabel = new JLabel("97");
progresLabel = new JLabel("Somme: 90 (2)");
nextButton = new JButton("NEXT");
giveUpButton = new JButton("GIVE UP");
resetButton = new JButton("RESET");
findMeanCheckBox = new JCheckBox("Find Mean");
noiseCheckBox = new JCheckBox("Noise");
createLayout(butLabel, progresLabel, nextButton, giveUpButton, resetButton, findMeanCheckBox, noiseCheckBox);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg)
{
JPanel container = new JPanel();
numberPanel = new GameNumView(800, 120);
JPanel buttonsPanel = new JPanel();
GroupLayout gl = new GroupLayout(buttonsPanel);
buttonsPanel.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = gl.createSequentialGroup();
GroupLayout.SequentialGroup vGroup = gl.createSequentialGroup();
hGroup.addGroup(gl.createParallelGroup()
.addComponent(arg[0])
.addComponent(arg[1])
.addComponent(arg[2])
.addComponent(arg[3])
.addComponent(arg[4])
.addComponent(arg[5])
.addComponent(arg[6]));
gl.setHorizontalGroup(hGroup);
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[0]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[1]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[2]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[3]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[4]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[5]));
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(arg[6]));
gl.setVerticalGroup(vGroup);
buttonsPanel.setBackground(Color.RED);//
container.add(numberPanel);
container.add(buttonsPanel);
add(container);
}
}
GameNumView is an other class that is a JPanel
Instead of group layout use BorderLayout (). Make the red panel BorderLayout.LEFT and the other BorderLayout.CENTER.
Example:
JPanel container = new JPanel();
JFrame frame = new JFrame();
frame.add (container, BorderLayout.LEFT);

Add Multiple JPanels to JFrame

Been having a hard time adding JPanels to JFrame. Am pretty much new on java, always used C++
I need to do 4 Panels inside one Frame.
Here is my Code, just started today..
package project2;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Container;
import java.awt.Dimension;
public class GUI extends JFrame
{
private JPanel Checks; //Panel to Hold Checks
private JPanel Transactions;
private JPanel History;
private JPanel Graphics;
private JLabel CLabel;
public GUI()
{
super ( "UTB Check-In");
JPanel Checks = new JPanel(); //set up panel
CLabel = new JLabel("Label with text");
Checks.setBackground(Color.red);
Checks.setLayout( new BoxLayout(Checks,BoxLayout.LINE_AXIS));
add(Checks);
// JPanel Transactions = new JPanel();
// Transactions.setToolTipText("Electronic Transactions");
//Transactions.setBackground(Color.blue);
// add(Transactions);
}
}
I was trying to put Transaction and Checks one side from the other with different colors,in this case blue and red it doesnt stay in the middle it those one or the other.
One of my Colleagues told me that the BoxLayout(or any layout) needed to be implemented with the size..something to that extend. am not really sure I been reading
http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
But I still do not get it completely. If somebody can help me out
thanks!
Your code fail cause you are adding directly to the JFrame which have by default BorderLayout. You are setting BoxLayout to the wrong panel.
You have to setLayout() to the top component(jframe) that you are adding or as i prefer adding to a jpanel rather than directly to the jframe to acomplish what you want to do.
Example:
public GUI()
{
super ( "UTB Check-In");
JPanel parent = new JPanel();
parent.setLayout(new BoxLayout(parent,BoxLayout.LINE_AXIS));
add(parent);
JPanel Checks = new JPanel(); //set up panel
CLabel = new JLabel("Label with text");
Checks.setBackground(Color.red);
parent.add(Checks);
JPanel Transactions = new JPanel();
Transactions.setToolTipText("Electronic Transactions");
Transactions.setBackground(Color.blue);
parent.add(Transactions);
}
By the way, in Java variables starts with lowerCase as a code convention.

Replacing a JPanel with a different JPanel

Hi this is a bit of a basic question. In my code I create a gui in a constructor then nest a ActionListener class to handle button changes. This code will create the gui and the action listener runs through the actionPerformed method correctly. However, I've tried multiple ways to change the panel in the gui but I feel like the way I have the program set up it is not possible for this to work. Sorry if this is a repeat but after searching for a while on S.O. I haven't found a good example that would help me with my problem.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
public class GraphGui extends JFrame {
//default width and height of the GUI
private static final int WIDTH = 1200;
private static final int HEIGHT = 700;
GraphPlot gp = new GraphPlot();
Plot2DPanel plotPanel =gp.determinePlotToPlot("duration");
/**
* This is the constructor that initializes the JFrame and the layout of the GUI.
* The radio buttons are also created here and grouped accordingly.
*/
public GraphGui() {
//title of GUI
setTitle("VibeTech Graph Gui");
//First JRadioButton for date vs duration
JRadioButton durToDate = new JRadioButton("Duration vs. Date");
durToDate.addActionListener(new RadioButtonListener());
durToDate.setActionCommand("duration");
durToDate.setSelected(true);
//JRadioButton for weight vs date
JRadioButton weightToDate = new JRadioButton("Weight vs. Date");
weightToDate.addActionListener(new RadioButtonListener());
weightToDate.setActionCommand("weight");
//JRadioButton for plan type vs date
JRadioButton planToDate = new JRadioButton("Plan vs. Date");
planToDate.addActionListener(new RadioButtonListener());
planToDate.setActionCommand("level");
//button group of the buttons to display them as one group
ButtonGroup group = new ButtonGroup();
group.add(planToDate);
group.add(weightToDate);
group.add(durToDate);
//create JPanel to add objects to
JPanel jplRadio = new JPanel();
jplRadio.setLayout(new GridLayout(0, 1));
//add radio buttons
jplRadio.add(planToDate);
jplRadio.add(weightToDate);
jplRadio.add(durToDate);
Plot2DPanel dvt = new Plot2DPanel();
dvt.addLinePlot("Duration over Time", gp.getDate(), gp.getDuration());
BaseLabel title = new BaseLabel("Duration over Time", Color.RED,
0.5, 1.1);
title.setFont(new Font("Courier", Font.BOLD, 20));
dvt.addPlotable(title);
dvt.setAxisLabels("Time", "Duration");
setLayout(new BorderLayout());
add(jplRadio, BorderLayout.WEST);
add(plotPanel, BorderLayout.EAST);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//main method to run program
public static void main(String [ ] args)
{
//create new GUI
#SuppressWarnings("unused")
GraphGui test = new GraphGui();
}
//create a radio button listener to switch graphs on button press
class RadioButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("duration")) {
plotPanel = gp.determinePlotToPlot("duration");
} else if (e.getActionCommand().equals("weight")) {
plotPanel = gp.determinePlotToPlot("weight");
} else if (e.getActionCommand().equals("level")) {
plotPanel = gp.determinePlotToPlot("level");
}
//here is where I tried to do removes, adds, and validates but
//I have trouble getting to the frame itself to remove the JPanel
//component. I think this is a setup problem.
}
}
}
You would need to add the panel and revalidate/repaint the JFrame for it to appear:
add(plotPanel, BorderLayout.EAST);
revalidate();
repaint();
Better to use CardLayout to manage this type of functionality.
Try using CardLayout for switching between panels. Here is my solution for a similar question: https://stackoverflow.com/a/9377623/544983

Categories

Resources