I am a high school student trying to teach myself GUI basics. The program I am trying to write would take two numbers from the user and then plot those two numbers in a graph. The user can also enter more points if he or she likes. The problem I am having is that when I press the button that opens the GUI that should be the graph, the GUI appears but it is blank. I think there is an issue with the paint method and the way that is being set up and called but I am not sure. Thanks in advance for any advice or help.
This is the class that creates the graph GUI:
package dataGraph;
import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class graphGUI extends JFrame {
//public Graphics2D g2;
public graphGUI() {
setTitle("Data Graph");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g) {
super.paintComponents(g);
g.drawLine(40, 425, 450, 425);
g.drawLine(40, 425, 40, 70);
g.drawString("Graph", 20, 20);
// g2.draw
g.drawLine(50, 50, 50, 50);
for(int i = 0; i < dataEntryGUI.x.size(); i++){
g.drawOval(Integer.parseInt(dataEntryGUI.x.get(i)),
Integer.parseInt(dataEntryGUI.y.get(i)),5,5);
}
}
}
This is the class that creates the GUI for data entry and has the action listener that allows the user to add more "points" and then "graph" them:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
public class dataEntryGUI extends JFrame implements ActionListener {
public static ArrayList<String> x;
public static ArrayList<String> y;
private Button btnAdd;
private Button btnGraph;
private Label lbl;
private Label lbl2;
private TextField xInt;
private TextField yInt;
public dataEntryGUI() {
setTitle("Data entry");
setSize(250, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
lbl = new Label("x");
lbl2 = new Label("y");
// text fields
xInt = new TextField();
yInt = new TextField();
x = new ArrayList<String>();
y = new ArrayList<String>();
// add button
btnAdd = new Button("Add another");
// btnAdd.setPreferredSize(new Dimension(70,30));
btnAdd.addActionListener(this);
btnGraph = new Button("Make Graph");
btnGraph.addActionListener(this);
add(lbl);
add(xInt);
add(lbl2);
add(yInt);
add(btnAdd);
add(btnGraph);
setLayout(new FlowLayout());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// System.out.println("boogers");
if (e.getSource() == btnAdd) {
//xInt.getText();
x.add(xInt.getText());
y.add(yInt.getText());
xInt.setText("");
yInt.setText("");
} else {
graphGUI graph = new graphGUI();
graph.repaint();
}
}
}
And this is the main method:
package dataGraph;
public class dataGraphMain {
public static void main(String[] args) {
dataEntryGUI gui = new dataEntryGUI();
//graphGUI gui2 = new graphGUI();
}
}
public void paint(Graphics g) {
super.paintComponents(g);
In general, whenever you override a method you should be invoking "super" on the method name you are overriding, not some other method. That is in this case you would invoke:
super.paint(g);
However, for custom painting you should NOT override the paint() method of a JFrame.
Instead you should override the paintComponent(...) method of a JPanel and then add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and examples.
I am a high school student trying to teach myself GUI basics.
Keep a link to the Table of Contents of the Swing tutorial handy for future reference as the tutorial covers the basics and more.
As mentioned by camickr, some refactoring should be done. Perhaps this will help.
First, you are trying to repaint the JFrame. This is not recommended. What you want to do is define a JPanel to work on and add it to the frame's pane content.
I refactored your code a bit, so that GraphGUI is now a JPanel, and not a JFrame. This way, you can use it as a component in any future JFrame you might create.
Second, I defined a function within DataEntryGUI that creates a new frame, which will hold the graph component and paint it. Here's the complete code:
Class GraphGUI
package dataGraph;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class graphGUI extends JPanel {
public GraphGUI() {
setBackground(Color.WHITE);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(40, 425, 450, 425);
g.drawLine(40, 425, 40, 70);
g.drawString("Graph", 20, 20);
g.drawLine(50, 50, 50, 50);
for(int i = 0; i < dataEntryGUI.x.size(); i++){
g.drawOval(Integer.parseInt(dataEntryGUI.x.get(i)),
Integer.parseInt(dataEntryGUI.y.get(i)),5,5);
}
}
}
DataEntryGUI
package dataGraph;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
public class DataEntryGUI extends JFrame implements ActionListener {
public static ArrayList<String> x; //This should be figured out by
public static ArrayList<String> y; //the OP. Encapsulation and
//decoupling is a different matter.
private Button btnAdd;
private Button btnGraph;
private Label lbl;
private Label lbl2;
private TextField xInt;
private TextField yInt;
public DataEntryGUI() {
setTitle("Data entry");
setSize(250, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
lbl = new Label("x");
lbl2 = new Label("y");
// text fields
xInt = new TextField();
yInt = new TextField();
x = new ArrayList<String>();
y = new ArrayList<String>();
// add button
btnAdd = new Button("Add another");
// btnAdd.setPreferredSize(new Dimension(70,30));
btnAdd.addActionListener(this);
btnGraph = new Button("Make Graph");
btnGraph.addActionListener(this);
add(lbl);
add(xInt);
add(lbl2);
add(yInt);
add(btnAdd);
add(btnGraph);
setLayout(new FlowLayout());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// System.out.println("boogers");
if (e.getSource() == btnAdd) {
//xInt.getText();
x.add(xInt.getText());
y.add(yInt.getText());
xInt.setText("");
yInt.setText("");
} else {
paintGraph();
}
}
private void paintGraph() {
JFrame graphFrame = new JFrame();
GraphGUI graph = new GraphGUI();
graphFrame.getContentPane().add(graph);
graphFrame.setTitle("Data Graph");
graphFrame.setSize(500, 500);
graphFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
graphFrame.setResizable(false);
graphFrame.setVisible(true);
}
}
This seems to exhibit the behavior you wanted. I have some thoughts/comments on how you pass your x,y data (and the fact that they are public and not private), but this is beyond the scope of what you needed here.
Related
how to draw below a label / button? -JAVA
I wanted to write a coordinate calculation program for ax^2 + bx + c, but thats not the important point...
I'd like to draw the graph only via AWT and the paint method. (not implemented yet), but I'm not able to set the paint method in the foreground. Can you please help me to fix the problem so that the paint is at least visible?
I have attached a outline of my thoughts.
Sorry for my bad english
idea
import java.awt.Button;
import java.awt.Canvas;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
public class MyWindow extends Frame {
Frame frame;
Label l1;
Label l2;
Label l3;
Button b1;
TextField t1;
TextField t2;
TextField t3;
Panel panel;
Canvas canvas;
MyWindow() {
frame = new Frame("GraphPlotter");
frame.setSize(800, 800);
frame.setLayout(new FlowLayout());
l1 = new Label("f(x)= ");
l2 = new Label(" x^2 + ");
l3 = new Label(" x + ");
t1 = new TextField("1");
t2 = new TextField("2");
t3 = new TextField("3");
b1 = new Button("Plot");
frame.add(l1);
frame.add(t1);
frame.add(l2);
frame.add(t2);
frame.add(l3);
frame.add(t3);
frame.add(b1);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.fillRect(10, 10, 300, 300); // ist im "Hintergrund"??
}
}
` public class Start {
public static void main(String[] args) {
MyWindow window = new MyWindow();
}
}
`
You haven't set a color before
g.fillRect(10, 10, 300, 300);
I solved that problem like two months or so, but I'm a bit motivated at the moment, so I am going to answer my question on my own. Info: repaint() calls paint, so you don't have to implement this method on your own.
in the task I forgot to:
-generate a canvas
-use layout manager
-call paint with the methods repaint(); or update();
The question was only how to paint and this should be clear after reading following code:
package delete;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
public class AwtFrame extends Frame {
AwtCanvas c;
Panel p1;
Label la_ax2, la_bx, la_c;
TextField tf_Ax2, tf_bx, tf_c;
public AwtFrame() {
super("paint example.");
this.setSize(800, 800);
initComp();
addComp();
// TODO: write a graph drawing method
c.repaint(); // paints a line of your graph
this.setVisible(true);
}
public void initComp() {
p1 = new Panel();
la_ax2 = new Label("x^2 ");
la_bx = new Label("+ x ");
la_c = new Label("+ c ");
tf_Ax2 = new TextField(0);
tf_bx = new TextField(0);
tf_c = new TextField(0);
c = new AwtCanvas();
}
public void addComp() {
this.setLayout(new BorderLayout());
p1.setLayout(new FlowLayout());
this.add(p1, BorderLayout.NORTH);
this.add(c, BorderLayout.CENTER);
p1.add(tf_Ax2);
p1.add(la_ax2);
p1.add(tf_bx);
p1.add(la_bx);
p1.add(tf_c);
p1.add(la_c);
}
public static void main(String[] args) {
new AwtFrame();
}
}
package delete;
import java.awt.Canvas;
import java.awt.Graphics;
import java.util.LinkedList;
public class AwtCanvas extends Canvas {
// LinkedList<ToImplement> coords = new LinkedList<ToImplement>();
// TODO: implement plotter
public void paint(Graphics g) {
g.drawLine(40, 40, 100, 100);
g.drawLine(54, 22, 300, 200);
}
}
I have looked at a lot of answers but i still cannot find a solution. I have a JFrame and two JPanels. I want to remove the one panel and replace it with the second when a button is pressed, but the repaint() method does not refresh the frame. Please help.
Here is my code for the frame:
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MainFrame
{
static JFrame mainFrame;
int height = 650;
int width = 1042;
public MainFrame()
{
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, width, height);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}
public static void main(String[] args)
{
new MainMenu();
mainFrame.setVisible(true);
}
}
This is the code for my MainMenu panel
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.Color.CYAN;
import static java.awt.Color.red;
public class MainMenu extends MainFrame
{
public MainMenu()
{
components();
}
//variable decleration
JPanel menuPanel;
JLabel title;
JButton periodicTable;
private void components()
{
int buttonW = 500;
int buttonH = 50;
//creating panel
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(CYAN);
//creating title label
title = new JLabel("Application Title", SwingConstants.CENTER);
title.setFont(new Font("Calibri Body", 0, 50));
title.setBounds(width / 3 - buttonW / 2, 50, buttonW, buttonH + 10);
//creating periodic table button
periodicTable = new JButton();
periodicTable.setText("Periodic Table");
periodicTable.setBounds(width / 3 - buttonW / 2, 50 + buttonH + 60, buttonW, buttonH);
periodicTable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
periodicTableActionPerformed(event);
}
});
//adding components to panel
menuPanel.add(title);
menuPanel.add(periodicTable);
//adding panel to MainFrame
mainFrame.add(menuPanel);
}
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel);
mainFrame.repaint();
new PeriodicTable();
mainFrame.repaint();
}
}
And finally my PeriodicTable panel
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends MainFrame
{
public PeriodicTable()
{
periodicComponents();
}
JPanel ptPanel;
private void periodicComponents()
{
ptPanel = new JPanel();
ptPanel.setLayout(null);
ptPanel.setBackground(Color.RED);
mainFrame.add(ptPanel);
}
}
I have no idea why you are extending MainFrame. Looks unnecessary to me.
I want to remove the one panel and replace it with the second when a button is pressed
Then use a CardLayout. Read the section from the Swing tutorial on How to Use CardLayout for a working example.
The tutorial will show you how to better structure your code.
Your PeriodicTable extends MainFrame. When creating new PeriodicTable you create with it new MainFrame which has its own instance of JFrame (MainFrame.mainFrame). You need to add that panel to existing mainFrame in MainMenu
I suggest removing changing your PeriodicTable class like this:
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends JPanel // Not MainFrame, but new custom panel
{
public PeriodicTable()
{
periodicComponents();
}
private void periodicComponents()
{
// You don't need ptPanel anymore, because `this` is JPanel
setLayout(null);
setBackground(Color.RED);
}
}
and change your actionPerformed function to something like this:
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel); // Remove old panel
mainFrame.add(new PeriodicTable()); // Create and add to existing mainFrame
mainFrame.repaint(); // Just one repaint at the end
// I think it will work even without repaint, because add and remove should schedule repainting as well
}
public class FaceMain extends JFrame {
CreateFace p1 = new CreateFace();
private ControlPanel panel;
public FaceMain(ControlPanel value) {
panel = value;
JFrame main = new JFrame();
main.setTitle("Face Frame");
main.setSize(new Dimension(600, 600));
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Container c = main.getContentPane();
main.add(p1);
panel.eyesSetE(true);
JFrame control = new JFrame();
control.setTitle("Control Panel");
control.setSize(new Dimension(300, 300));
control.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
control.setLocationRelativeTo(main);
control.setVisible(true);
ControlPanel p2 = new ControlPanel(p1);
control.add(p2);
}
}
public class ControlPanel extends JPanel {
boolean eyesSetEdit = false, faceSetEdit = false, mouthSetEdit = false,
editEyes;
private Color purple = new Color(133, 22, 145);
private CreateFace face;
private CreateFace p1;
public ControlPanel(CreateFace value) {
face = value;
p1 = value;
setLayout(new GridLayout(4, 0));
JButton change = new JButton("Click");
add(change);
JLabel info = new JLabel("Click Above To Change Features",
JLabel.CENTER);
add(info);
JLabel info1 = new JLabel("Slide Below To Change Size", JLabel.CENTER);
add(info1);
JScrollBar slider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 100, 0, 300);
add(slider);
public void eyesSetE(boolean x) {
eyesSetEdit = x;
}
public boolean getEyesSet() {
return eyesSetEdit;
}
I have expanded my class to try and change a boolean value which will be used exstensivly in the ControlPanel class to make decisions however everytime I start the program I get a nullpointerexception at the line "panel.eyesSetE(true);" Even if I try and call getEyesSet() I still recieve a nullpointer
You never change the instance of circle within the CreateCircle class, so it never changes size.
Don't use static for what should be an instance variable, instead make use of the instance of the class you created and provide a setter method to change the variable...
Basically, this example passes the instance of p1 to the ControlPanel pane so that it has some context by which to manipulate what you have previously created.
import datetest.CircleShort.ControlPanel;
import datetest.CircleShort.CreateCircle;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Scrollbar;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
public class CircleShort extends JFrame {
CreateCircle p1 = new CreateCircle();
public CircleShort() {
CreateCircle p1 = new CreateCircle();
JFrame main = new JFrame();
main.setSize(new Dimension(600, 600));
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Container c = main.getContentPane();
main.add(p1);
JFrame control = new JFrame();
control.setTitle("Control Panel");
control.setSize(new Dimension(300, 300));
control.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
control.setLocationRelativeTo(main);
control.setVisible(true);
ControlPanel p2 = new ControlPanel(p1);
control.add(p2);
}
static class CreateCircle extends JComponent {
int circleX = 100;
Ellipse2D.Double circle;
public CreateCircle() {
circle = new Ellipse2D.Double(circleX, 50, 400, 350);
}
public void setCircleX(int x) {
circleX = x;
circle = new Ellipse2D.Double(circleX, 50, 400, 350);
repaint();
}
public int getCircleX() {
return circleX;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fill(circle);
}
}
class ControlPanel extends JComponent {
private CreateCircle circle;
public ControlPanel(CreateCircle value) {
circle = value;
setLayout(new GridLayout(4, 0));
JButton change = new JButton("Click");
add(change);
JLabel info = new JLabel("Click Above To Change Color",
JLabel.CENTER);
add(info);
JLabel info1 = new JLabel("Slide Below To Change Size",
JLabel.CENTER);
add(info1);
JScrollBar slider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 100, 0,
300);
add(slider);
slider.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println(e.getValue());
circle.setCircleX((circle.getCircleX() + (e.getValue() % 5)));
}
});
}
}
static class CircleRun {
public static void main(String[] args) {
new CircleShort();
}
}
}
static is evil until you truly understand how to use it. If you find yourself making some field or method static just because you can't seem to figure out how to access it, then you are likely doing something wrong, be careful with it...
The next question this actually raises is, "why?"
A JSlider would be a more appropriate control to use and would be conceptually easier for a user to understand
So I have this problem with my code. Whenever I load up the game there is a red square in the center of the screen, and I have not programmed it to do so. I have tried to find the error for hours but I just can't see it. I think it has to do with the panels or something. The second thing is that when I press the button to draw the grid, only a small line appears. It is programmed to be much bigger than what it is, and it is not in the right location either. Below is all my code, and any help is greatly appreciated!!
package com.theDevCorner;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class Game extends JPanel implements ActionListener {
public static JButton grid = new JButton("Show Grid");
public static JPanel drawArea = new JPanel();
public static JMenuBar menu = new JMenuBar();
public static JPanel notDrawn = new JPanel();
public static boolean gridPressed = false;
public Game() {
grid.addActionListener(this);
}
public static void main(String args[]) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(
Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit
.getDefaultToolkit().getScreenSize().height));
frame.setTitle("Game");
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
menu.setSize(new Dimension(1600, 20));
menu.setLocation(0, 0);
notDrawn.setBackground(new Color(255, 0, 50));
notDrawn.setSize(100, 900);
notDrawn.add(grid);
notDrawn.setLayout(null);
grid.setSize(new Dimension(100, 25));
grid.setLocation(0, 25);
drawArea.setSize(new Dimension((Toolkit.getDefaultToolkit()
.getScreenSize().width), Toolkit.getDefaultToolkit()
.getScreenSize().height));
drawArea.setLocation(100, 0);
drawArea.setBackground(Color.black);
drawArea.add(menu);
drawArea.add(game);
frame.add(drawArea);
frame.add(notDrawn);
}
public void paint(Graphics g) {
Game game = new Game();
if (gridPressed) {
Game.drawGrid(0, 0, g);
}
g.dispose();
repaint();
}
public static void drawGrid(int x, int y, Graphics g) {
g.setColor(Color.white);
g.drawLine(x, y, 50, 300);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == grid && gridPressed == true) {
gridPressed = false;
System.out.println("Unpressed");
}
if (e.getSource() == grid) {
gridPressed = true;
System.out.println("Pressed");
}
}
}
There are a number of problems...
The red "square" you are seeing is actually your grid button. The reason it's red is because of your paint method.
Graphics is a shared resource, that is, each component that is painted on the screen shares the same Graphics context. Because you chose to dispose of the context and because you've failed to honor the paint chain, you've basically screwed it up.
Don't EVER dispose of a Graphics context you didn't create. It will prevent anything from being painted to it again. Always call super.paintXxx. The paint chain is complex and does a lot of very important work. If you're going to ignore it, be ready to have to re-implement it.
null layouts are vary rarely the right choice, especially when you're laying out components. You need to separate your components from your custom painting, otherwise the components will appear above the custom painting.
This frame.setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height)) is not the way to maximize a window. This does not take into consideration the possibility of things like tasks bars. Instead use Frame#setExtendedState
As Andreas has already commented, you actionPerformed logic is wrong. You should be using an if-statement or simply flipping the boolean logic...
Updated with simple example
ps- static is not your friend here...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel implements ActionListener {
private GridPane gridPane;
public Game() {
setLayout(new BorderLayout());
SideBarPane sideBar = new SideBarPane();
sideBar.addActionListener(this);
add(sideBar, BorderLayout.WEST);
gridPane = new GridPane();
add(gridPane);
}
public static void main(String args[]) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setTitle("Game");
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("grid")) {
gridPane.setGridOn(!gridPane.isGridOn());
}
}
public class GridPane extends JPanel {
private boolean gridOn = false;
public GridPane() {
setBackground(Color.BLACK);
}
public boolean isGridOn() {
return gridOn;
}
public void setGridOn(boolean value) {
if (value != gridOn) {
this.gridOn = value;
repaint();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (gridOn) {
g.setColor(Color.white);
g.drawLine(0, 0, 50, 300);
}
}
}
public class SideBarPane extends JPanel {
public JButton grid;
public SideBarPane() {
setBackground(new Color(255, 0, 50));
setLayout(new GridBagLayout());
grid = new JButton("Show Grid");
grid.setActionCommand("grid");
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
add(grid, gbc);
}
public void addActionListener(ActionListener listener) {
grid.addActionListener(listener);
}
}
}
Can someone please assist me on why my background color of the frame is not being set. Is it possible to set the background color within the Paint() or must it be done in the JColor constructor
I am supposed to do the following for the BG color-
Write A GUI application that displays a single JButton and any background color you choose.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* #author Curtis
*/
public class JColor extends JFrame implements ActionListener
{
Font myFont = new Font("Playbill", Font.PLAIN, 28);
JButton myButton = new JButton("Click Me!");
Color bgColor = new Color(255, 97, 3);
Color txtColor = new Color(0, 0, 205);
String firstName = "Curtis";
String lastName = "Sizemore";
public JColor()
{
super("String Painting Fun");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout (new BorderLayout());
add(myButton, BorderLayout.SOUTH);
setDefaultLookAndFeelDecorated(true);
setBackground(Color.BLUE);
}
#Override
public void paint(Graphics e)
{
super.paint(e);
}
public static void main(String[] args)
{
final int TALL = 200;
final int WIDE = 250;
JColor frame = new JColor();
frame.setSize(WIDE, TALL);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
Try calling it on the ContentPane instance (more info here)
public JColor() {
super("String Painting Fun");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(myButton, BorderLayout.SOUTH);
setDefaultLookAndFeelDecorated(true);
getContentPane().setBackground(Color.BLUE);//<- update
}