JPanels and GridLayouts - java

I have been attempting to recreate this in Java: http://imgur.com/pjt7SMZ
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 100;
private static final int FRAME_Y_ORIGIN = 75;
private JButton readFileButton;
private JButton exitButton;
private JButton statsButton;
private JButton clearButton;
private JButton helpButton;
private JLabel headerLabel;
public Display() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("CSCE155A Course Offering Viewer");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel header = new JPanel(new GridLayout(1, 1, 5, 5));
headerLabel = new JLabel("CSCE155A Course Offering Viewer");
header.add(headerLabel);
}
public static void main(String[] args) {
Display frame = new Display();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
}
}
My problem is with JPanel. As we were instructed, we are suppose to use the BorderLayout with GridLayout inside, but nothing happens whenever I run the code. Is JPanel even the best way to do this? Right now I'm just trying to get the header to work.

According to your design, you should not add JLabel on JPanel. Add headerLabel on top of JFrame and align the text CENTER.
headerLabel = new JLabel("CSCE155A Course Offering Viewer",JLabel.CENTER);
add(headerLabel,BorderLayout.NORTH);// Add it with JFrame.

Related

Why does my Canvas not draw the rectangles

I know this problem has probably already been solved before but I don't really know how to describe the problem well, so I have a hard time finding it.
The problem I have is that I have a canvas that is attached to a panel and that panel is attached to a main panel and that to the frame. When I run the code the canvas does nothing. However if I dont add the button panel it works.
this is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ColorFrame extends JFrame {
private static final int FRAMEWIDTH = 400;
private static final int FRAMEHEIGHT = 400;
private int aORec = 4;
private Canvas canvas;
private JPanel mainPanel;
private JPanel panel;
private JPanel buttonPanel;
private JButton lessButton;
private JButton moreButton;
public ColorFrame() {
mainPanel = new JPanel();
panel = new JPanel();
canvas = new painter();
panel.add(canvas);
mainPanel.add(panel, BorderLayout.CENTER);
createComponents();
add(mainPanel);
setSize(FRAMEWIDTH,FRAMEHEIGHT);
setDefaultCloseOperation(3);
}
private void createComponents() {
buttonPanel = new JPanel();
lessButton = new JButton("Less");
moreButton = new JButton("More");
ActionListener bL = new ButtonListener();
lessButton.addActionListener(bL);
moreButton.addActionListener(bL);
buttonPanel.add(moreButton);
buttonPanel.add(lessButton);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
}
class painter extends Canvas {
#Override
public void paint(Graphics g) {
for (int i = 0; i < aORec; i++) {
int tempWidth = (int)(Math.random() * (FRAMEWIDTH-0));
int tempHeight = (int)(Math.random() * (FRAMEHEIGHT -0));
g.drawRect(tempWidth,tempHeight,20,20);
}
}
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == moreButton) {
aORec =+ aORec;
canvas.repaint();
} else {
if (aORec != 1) {
aORec -= (aORec*0.5);
canvas.repaint();
} else {
System.out.println("There are not enough rectangles to be drawn.");
}
}
}
}
}
Main panel is created by
mainPanel = new JPanel();
Components are being added to the main panel as
mainPanel.add(panel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
but no LayoutManager was set, so the default FlowLayout is used, not BorderLayout. Create the panel by
mainPanel = new JPanel(new BorderLayout());
or add the statement
mainPanel.setLayout(new BorderLayout());
This is also valid for panel (otherwise it will not be resized, that is, stay with size zero)
(BorderLayout is the default for JFrame(

Switch Between JPanels With Use of JButton?

Trying to make flashcard application. The JButton b_switchmode will be used to switch between panels (an edit mode and a test mode, both have panels created for separate use). Not quite sure how to go from the GUI I've created. Ideally I would click the JButton b_switchmode and I would be able to switch from "Edit Mode" to "Test Mode".
I'm aware that a CardLayout may be needed but I'm unable to implement the correct syntax to make the program executable.
So I want to know how to:
insert CardLayout to be able to switch between JPanels
allow JButton b_switchmode to execute the switch between JPanels
public class App2 {
private static JFrame frame;
private static JPanel editpanel;
private static JPanel testpanel;
private static JLabel l_appmode;
private static JLabel l_number;
private static JLabel l_question;
private static JLabel l_answer;
public static JTextField t_questions;
public static JTextField t_answer;
public static JButton b_switchmode;
public static JButton b_previous;
public static JButton b_next;
public static JButton b_add;
public static JButton b_save;
public static JButton b_question;
public static JButton b_answer;
static int width = 600;
static int height = 450;
public static void main(String[] args) {
// TODO Auto-generated method stub
gui();
}
private static void gui(){
frame = new JFrame("Assignment2");
frame.setTitle("Flash Cards");
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l_appmode = new JLabel("Current Mode: Edit");
l_number = new JLabel ("");
l_question = new JLabel("Question:");
l_answer = new JLabel("Answer:");
t_questions = new JTextField("");
t_answer = new JTextField("");
b_switchmode = new JButton("Switch Mode");
b_previous = new JButton("Previous");
b_next = new JButton("Next");
b_add = new JButton("Add");
b_save = new JButton("Save");
b_question = new JButton("Question");
b_answer = new JButton("Answer");
editpanel = new JPanel();
int rows = 6, columns = 1;
int hgap = 20; int vgap = 20;
editpanel.setLayout(new GridLayout(rows, columns, hgap,
vgap));
editpanel.add(l_appmode);
editpanel.add(l_number);
editpanel.add(l_question);
editpanel.add(t_questions);
editpanel.add(l_answer);
editpanel.add(t_answer);
editpanel.add(b_switchmode);
editpanel.add(b_previous);
editpanel.add(b_next);
editpanel.add(b_add);
editpanel.add(b_save);
//testpanel.add(b_question);
//testpanel.add(t_questions);
//testpanel.add(b_answer);
//testpanel.add(t_answer);
frame.add(editpanel);
//frame.add(testpanel);
frame.setVisible(true);
}

JScrollPane not working in my code

Here, My Jscrollpane isn't working. I have added the scrollpane and list both on main Jpanel. The Jlist is working, But it seems, JScrollpane Not working in this code.
my main class extends Jframe, so from main class i just pass the main panel, and working on the same panel.
and here i'm using absolute layout.
public class ExternalsLinks extends JPanel {
///Links List
private JList mainList;
///List Custom Border
Border lineBorder = BorderFactory.createLineBorder(Color.BLACK, 5);
///Main Jpanel
private JPanel mainPanel;
///Scroll Pane for Lists
private JScrollPane mainListScrollPane;
/// Lebels
private JLabel lblExternalLinks;
///Buttons
private Button btnBackCredits = new Button("Back");
///Button Properties
private final int BUTTON_X = 220; private final int BUTTON_Y = 450;
private final int BUTTON_X_LENGTH = 350; private final int BUTTON_Y_LENGTH = 50;
///List Options
private String [] listMenu = {"Searching", "Sorting"};
///Constructors
public ExternalsLinks(JPanel mainPanel) {
this.mainPanel = mainPanel;
this.mainPanel.setLayout(null);
mainPanel.setBackground(Color.WHITE);
initialize_All();
}
/// Initialize method to initialize all components to JFrame
private void initialize_All() {
///Main Panel Components
lblExternalLinks = new JLabel("\"External Links\"");
lblExternalLinks.setBounds(290, 0, 400, 100);
lblExternalLinks.setFont(new Font("courier", Font.BOLD, 30));
mainPanel.add(lblExternalLinks);
mainList = new JList(listMenu);
mainList.setBackground(Color.CYAN);
mainList.setForeground(Color.BLACK);
mainList.setFont(new Font("Calibiri", Font.BOLD, 25));
mainList.setVisibleRowCount(2);
mainList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mainList.setBorder(lineBorder);
mainList.setBounds(50, 80, 300, 350);
mainListScrollPane = new JScrollPane();
mainPanel.add(mainListScrollPane);
mainPanel.add(mainList);
///Buttons
btnBackCredits.setBounds(BUTTON_X, BUTTON_Y, BUTTON_X_LENGTH, BUTTON_Y_LENGTH);
mainPanel.add(btnBackCredits);
btnBackCredits.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mainList.setVisible(false);
mainPanel.removeAll();
new MainMenu(mainPanel);
}
});
}
}
I have added the scrollpane and list both on main Jpanel.
That's a problem -- don't do that. You can only add a component to one container, and the JScrollPane counts as a container. So add your JList to the JScrollPane's viewport, and then only add the JScrollPane to the GUI.
i'm using absolute layout
And that's another serious problem. Don't use null layouts and setBounds(...). For instance calling setBounds on your list will prevent the scrollpane from being able to work since the list can't expand inside the JScrollPane as it should. Learn and use the layout managers.
Also, you never add the JList to the JScrollPane's viewport!
You need JScrollPane scrollPane = new JScrollPane(myList); or something similar, with whatever your variable names are. Please go through the tutorials as this is all fully explained there.
JScrollPane tutorial link
Swing Info link to tutorials and Swing resources
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
#SuppressWarnings("serial")
public class ExternalsLinks2 extends JPanel {
// constants
private static final String[] LIST_DATA = {"Searching", "Sorting"};
private static final Font LIST_FONT = new Font("Calibiri", Font.BOLD, 25);
private static final Font LABEL_FONT = new Font("courier", Font.BOLD, 30);
private static final int LIST_VISIBLE_ROW_COUNT = 10;
private static final String TITLE_TEXT = "External Links";
private static final Color LIST_BG = Color.CYAN;
// JList field created with constant array data
private JList<String> jList = new JList<>(LIST_DATA);
public ExternalsLinks2() {
jList.setFont(LIST_FONT);
jList.setPrototypeCellValue("ABCDEFGHIJKLMNOP ABCDE");
jList.setVisibleRowCount(LIST_VISIBLE_ROW_COUNT);
jList.setBackground(LIST_BG);
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(LABEL_FONT);
JButton backButton = new JButton("Back");
// add ActionListener or AbstractAction here
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5)); // use BorderLayout
add(titleLabel, BorderLayout.PAGE_START); // JLabel at top
add(new JScrollPane(jList), BorderLayout.CENTER); // JList inside of JScrollPane in center
add(backButton, BorderLayout.PAGE_END); // JButton at bottom
}
private static void createAndShowGui() {
JFrame frame = new JFrame("External Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ExternalsLinks2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Which displays as:

Java GUI won't display a prompt I want it to

So my program is designed to take in 2 values, make a calculation, and give this calculations value. I want to display it as a prompt in the GUI in the actionPerformed section after the button is clicked. It looks like it should show up but I can't seem to find why it isn't? It's "prompt2" that isn't showing up. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Windchill extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private String degree;
private String wind;
private int degreeInt;
private int windInt;
private double windChillInt;
private JButton windButton;
private JLabel prompt;
private JLabel prompt1;
private JLabel prompt2;
private JTextField inputLine;
private JTextField inputLine1;
public Windchill(){
setTitle("Windchill");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField();
inputLine.setColumns(3);
inputLine.addActionListener(this);
contentPane.add(inputLine);
prompt = new JLabel();
prompt.setText("Enter the degrees in Farienheight ");
prompt.setSize(150,25);
contentPane.add(prompt);
inputLine1 = new JTextField();
inputLine1.setColumns(3);
inputLine1.addActionListener(this);
contentPane.add(inputLine1);
prompt1 = new JLabel();
prompt1.setText("Enter the wind speed in MPH");
prompt1.setSize(150,25);
contentPane.add(prompt1);
windButton = new JButton("Calculate windchill");
contentPane.add(windButton);
windButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == windButton){
degree = inputLine.getText();
degreeInt = Integer.parseInt(degree);
wind = inputLine1.getText();
windInt = Integer.parseInt(wind);
windChillInt = 0.08 * (degreeInt - 91.4)*(3.71* (Math.sqrt(windInt)) + 5.81 - 0.25 *windInt) + 91.4;
prompt2 = new JLabel();
prompt2.setText("The windchill is " + windChillInt);
prompt2.setSize(150,25);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(prompt2);
}
}
}
public static void main(String[] args) {
Windchill frame;
frame = new Windchill();
frame.setVisible(true);
}
}
prompt2 isn't showing up as Swing containers need to be validated for any newly added components can be visible. Also it's good practice to repaint. You could do:
contentPane.revalidate();
contentPane.repaint();
Side Notes:
It is unnecessary to set the layout again for the your ActionListener
contentPane.add(prompt2) can be simplified to add(prompt2)
Alternatively, you could just add the prompt2 JLabel to the contentPane on startup with empty String content and call setText to update.

Syntax error on token, 'Class', invalid type

The part with asterisks is what it shows error. Can anyone explain to me why this is happening?
I already have a public class in the beginning.
If I take off the bracket "()", the code following that all shows errors.
Thanks!
public class ButtonTester {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new adasdad();
}
//Setting up variables
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 600;
private JButton button = new JButton ("A");
private JButton button2 = new JButton ("B");
**class ExP12_4 () {**
//Creating a frame
//Creating a panel
...
...
//Display frame
...
}
You have to remove the parenthesis and create a constructor for the class:
class ExP12_4 {
private JFrame frame;
private JPanel panel;
private JButton button;
private JButton button2;
public ExP12_4 (){
button = new JButton ("A");
button2 = new JButton ("B");
frame = new JFrame ();
panel = new JPanel ();
panel.add(button);
panel.add(button2);
frame.add(panel);
...
}
}
Take a look at this tutorial for more info about Java Classes
There's no parenthesis allowed in a class definition. These belong in a constructor.
Also you need to put your statements in a code block such as the constructor or init method:
public class ExP12_4 {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
private JButton button;
private JButton button2;
public ExP12_4() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(button);
panel.add(button2);
frame.add(panel);
// etc.
}
}
It should be ["a"] instead of ("a").

Categories

Resources