Drawing the Quadratic formula with sliders on a JPanel - java

So, I'm trying to make a program where you can input the quadratic formula (ax^2+bx+c) via sliders. Then it draws a graph as you adjust for A, B, and C.
Issues:
I want the stuff I wrote in super paint and the sliders to be in one place.
The sliders are in place when I run it. There's space with the correct background where I want my graph in the panel but no actual graph.
Here's my driver class:
import java.awt.*;
import javax.swing.*;
public class quadraticslider
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Quadratic Slider");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new pp109quadraticpanel());
frame.pack();
frame.setVisible(true);
}
}
Here's the panel class:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class quadraticpanel extends JPanel
{
private JPanel controls, graphPanel;
private JSlider ASlider, BSlider, CSlider;
private JLabel ALabel, BLabel, CLabel;
double A, B, C, x,Y;
//
//SLIDERS YO
//
public quadraticpanel()
{
ASlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
ASlider.setMajorTickSpacing (50);
ASlider.setMinorTickSpacing (10);
ASlider.setPaintTicks (true);
ASlider.setPaintLabels (true);
ASlider.setAlignmentX (Component.LEFT_ALIGNMENT);
BSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
BSlider.setMajorTickSpacing (50);
BSlider.setMinorTickSpacing (10);
BSlider.setPaintTicks (true);
BSlider.setPaintLabels (true);
BSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
CSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
CSlider.setMajorTickSpacing (50);
CSlider.setMinorTickSpacing (10);
CSlider.setPaintTicks (true);
CSlider.setPaintLabels (true);
CSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
ASlider.addChangeListener (listener);
BSlider.addChangeListener (listener);
CSlider.addChangeListener (listener);
ALabel = new JLabel ("a: 0");
ALabel.setAlignmentX (Component.LEFT_ALIGNMENT);
BLabel = new JLabel ("b: 0");
BLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
CLabel = new JLabel ("c: 0");
CLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
controls = new JPanel();
BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);
controls.setLayout (layout);
controls.add (ALabel);
controls.add (ASlider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (BLabel);
controls.add (BSlider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (CLabel);
controls.add (CSlider);
graphPanel = new JPanel();
graphPanel.setPreferredSize (new Dimension (500, 500));
graphPanel.setBackground (Color.white);
add (controls);
add (graphPanel);
}
//Here I'm taking the equation, running it through -10 to 10
//It takes the doubles from the equation, converts
//it to int then draws the quadratic formula in dots.
public void paintComponent(Graphics page)
{
super.paintComponent (page);
for ( x=-10; x <= 10; x++)
{
Y = (A*(Math.pow(x,2)))+(B*x)+(C);
int g = (int)Math.round(x);
int h = (int)Math.round(Y);
page.setColor (Color.black);
page.fillOval (g, h, 1, 1);
}
}
public class SliderListener implements ChangeListener
{
///
///Reads the user input via slider.
///
public void stateChanged (ChangeEvent event)
{
A = ASlider.getValue();
B = BSlider.getValue();
C = CSlider.getValue();
ALabel.setText ("a: " + A);
BLabel.setText ("b: " + B);
CLabel.setText ("c: " + C);
}
}
}

These examples using JFreeChart may be of interest. As shown here, you can animate the rendering using SwingWorker, and this example updates a chart using a JSlider.
Addendum: This variation of your code may guide you going forward. Note,
Override relevant methods in your graphPanel.
Scale and invert coordinates, as shown here.
Consider JSpinner for fractional values.
Use constants for consistency.
Use common naming conventions for clarity.
See also Initial Threads.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/** #see https://stackoverflow.com/a/20556929/230513 */
public class QuadraticSlider {
private static final int N = 500;
private static final int A = 1;
private static final int B = 0;
private static final int C = 0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Quadratic Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new QuadraticPanel());
frame.pack();
frame.setVisible(true);
}
});
}
private static class QuadraticPanel extends JPanel {
private Box controls;
private JPanel graphPanel;
private JSlider aSlider, bSlider, cSlider;
private JLabel aLabel, bLabel, cLabel;
double a, b, c, x, y;
public QuadraticPanel() {
aSlider = new JSlider(JSlider.HORIZONTAL, -25, 25, A);
aSlider.setMajorTickSpacing(10);
aSlider.setMinorTickSpacing(5);
aSlider.setPaintTicks(true);
aSlider.setPaintLabels(true);
aSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
bSlider = new JSlider(JSlider.HORIZONTAL, -10, 10, B);
bSlider.setMajorTickSpacing(5);
bSlider.setMinorTickSpacing(1);
bSlider.setPaintTicks(true);
bSlider.setPaintLabels(true);
bSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
cSlider = new JSlider(JSlider.HORIZONTAL, -100, 100, C);
cSlider.setMajorTickSpacing(50);
cSlider.setMinorTickSpacing(10);
cSlider.setPaintTicks(true);
cSlider.setPaintLabels(true);
cSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
aSlider.addChangeListener(listener);
bSlider.addChangeListener(listener);
cSlider.addChangeListener(listener);
aLabel = new JLabel("a: 0");
bLabel = new JLabel("b: 0");
cLabel = new JLabel("c: 0");
controls = new Box(BoxLayout.Y_AXIS);
controls.add(aLabel);
controls.add(aSlider);
controls.add(Box.createRigidArea(new Dimension(0, 20)));
controls.add(bLabel);
controls.add(bSlider);
controls.add(Box.createRigidArea(new Dimension(0, 20)));
controls.add(cLabel);
controls.add(cSlider);
graphPanel = new JPanel() {
private static final int SCALE = 5;
#Override
public Dimension getPreferredSize() {
return new Dimension(N, N);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (x = -10; x <= 10; x++) {
y = a * x * x + b * x + c;
g.setColor(Color.black);
int w = (int) (x * SCALE) + N / 2;
int h = (int) (-y * SCALE) + N / 2;
g.fillOval(w, h, 5, 5);
}
}
};
graphPanel.setBackground(Color.white);
add(controls);
add(graphPanel);
listener.stateChanged(null);
}
class SliderListener implements ChangeListener {
#Override
public void stateChanged(ChangeEvent event) {
a = aSlider.getValue() / 5d;
b = bSlider.getValue();
c = cSlider.getValue();
aLabel.setText("a: " + a);
bLabel.setText("b: " + b);
cLabel.setText("c: " + c);
repaint();
}
}
}
}

_"error: possible loss of precision Y = (A*(Math.pow(x,2)))+(B*x)+(C); ^ required: int found: double"_
All your int variables int A, B, C, x,Y;. Make them doubles. double A, B, C, x,Y;

I modified the code so that it solves for x given a b and c. Then plugs x back in and solves for y. I'm still not getting it to draw though. I also took out the loop since the sliders are setting the a b and c values which lead to x. Anyone know why it won't draw?
package quadraticslider;
import java.awt.*;
import javax.swing.*;
public class quadraticslider
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Quadratic Slider");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new quadraticpanel());
frame.pack();
frame.setVisible(true);
}
}
package quadraticslider;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class quadraticpanel extends JPanel
{
private JPanel controls, graphPanel;
private JSlider ASlider, BSlider, CSlider;
private JLabel ALabel, BLabel, CLabel;
double A, B, C, x,Y;
public quadraticpanel()
{
ASlider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
ASlider.setMajorTickSpacing (50);
ASlider.setMinorTickSpacing (10);
ASlider.setPaintTicks (true);
ASlider.setPaintLabels (true);
ASlider.setAlignmentX (Component.LEFT_ALIGNMENT);
BSlider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
BSlider.setMajorTickSpacing (50);
BSlider.setMinorTickSpacing (10);
BSlider.setPaintTicks (true);
BSlider.setPaintLabels (true);
BSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
CSlider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
CSlider.setMajorTickSpacing (50);
CSlider.setMinorTickSpacing (10);
CSlider.setPaintTicks (true);
CSlider.setPaintLabels (true);
CSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
ASlider.addChangeListener (listener);
BSlider.addChangeListener (listener);
CSlider.addChangeListener (listener);
ALabel = new JLabel ("a: 0");
ALabel.setAlignmentX (Component.LEFT_ALIGNMENT);
BLabel = new JLabel ("b: 0");
BLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
CLabel = new JLabel ("c: 0");
CLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
controls = new JPanel();
BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);
controls.setLayout (layout);
controls.add (ALabel);
controls.add (ASlider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (BLabel);
controls.add (BSlider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (CLabel);
controls.add (CSlider);
graphPanel = new JPanel();
graphPanel.setPreferredSize (new Dimension (500, 500));
graphPanel.setBackground (Color.white);
add (controls);
add (graphPanel);
}
public void paintComponent(Graphics page)
{
super.paintComponent (page);
x = (-B + (Math.sqrt((B*B - ((4 * A * C))))))/ (2 * A);
Y = (A*(Math.pow(x,2)))+(B*x)+(C);
int g = (int)Math.round(x);
int h = (int)Math.round(Y);
page.setColor (Color.black);
page.drawOval (g, h, 1, 1);
}
public class SliderListener implements ChangeListener
{
///
///Reads the user input via slider.
///
public void stateChanged (ChangeEvent event)
{
A = ASlider.getValue();
B = BSlider.getValue();
C = CSlider.getValue();
ALabel.setText ("a: " + A);
BLabel.setText ("b: " + B);
CLabel.setText ("c: " + C);
}
}
}

Related

JComponents Moving to Origin After Repaint()

Similar to JButton showing up in the wrong spot after repaint is called, but the responses to that question only addressed the fact that he wasn't using a layout manager, while I am using a layout manager (poorly), so it didn't really help, unfortunately.
Details
Intent of the Program:
To show a preview of a 1920x1080 grid (scaled down to 640x480 to save space), stretching and shrinking as you change the height of each square, width of each square, and the number of columns it'll have. (You specify a number of total squares to be in the grid first, so the number of rows is inferred by the program.)
Structure:
One top-level JFrame.
Contains two JPanels: the Grid, and the sidebar, using a BorderLayout to snap them to the east and west sides.
Sidebar is one JPanel containing all of the JComponents in a Y-Axis aligned BoxLayout.
Grid extends JComponent, and uses Graphics.drawLine() to draw the grid.
Each component in the sidebar calls Grid.repaint() when changed to update the grid.
Current UI, with the two main JPanels outlined in red.
The Problem
Whenever I change any of the components and thus call Grid.repaint():
The grid doesn't clear, resulting in multiple lines appearing;
All of the sidebar components get painted at the top-left corner, while still showing/functioning on the sidebar;
The grid resizes itself to be wider than normal for some reason.
Current UI, but borked.
What I've Tried
Changing the repaint() region to be a rectangle that only covers the grid,
Checking the documentation for anything about this,
Google,
Asking you guys.
The Code
Reprex: (Simplified to "Press the button to reproduce", while still keeping the essence of the potential problem areas.)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BuildGridGUI2
{
static final int WIDTH_MIN = 100;
static final int WIDTH_MAX = 2000;
static final int WIDTH_INIT = 520;
static final int HEIGHT_MIN = 100;
static final int HEIGHT_MAX = 2000;
static final int HEIGHT_INIT = 300;
int widthOfFrames = 255;
int heightOfFrames = 255;
int numCols = 3;
int numFrames = 1;
private final JComponent makeUI()
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
Grid g = new Grid();
JComponent j = makeSideMenu(g);
g.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.red),
g.getBorder()));
j.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.red),
j.getBorder()));
p.add(j, BorderLayout.EAST);
p.add(g, BorderLayout.WEST);
return p;
}
private final JComponent makeSideMenu(Grid grid)
{
JPanel p = new JPanel();
JLabel numColsSelectorLabel = new JLabel("Frames Per Column");
JSpinner numColsSelectorField = new JSpinner();
JLabel widthLabel = new JLabel("Width per Frame (Pixels)");
JSpinner widthSpinner = new JSpinner();
JSlider widthSlider = new JSlider(WIDTH_MIN, WIDTH_MAX, WIDTH_INIT);
JLabel heightLabel = new JLabel("Height per Frame (Pixels)");
JSpinner heightSpinner = new JSpinner();
JSlider heightSlider = new JSlider(BuildGridGUI2.HEIGHT_MIN, BuildGridGUI2.HEIGHT_MAX, BuildGridGUI2.HEIGHT_INIT);
JButton confirmButton = new JButton("Confirm");
numColsSelectorField.setEditor(new JSpinner.NumberEditor(numColsSelectorField));
numColsSelectorField.setMaximumSize(numColsSelectorField.getPreferredSize());
widthSlider.setMajorTickSpacing(300);
widthSlider.setMinorTickSpacing(20);
widthSlider.setPaintTicks(true);
widthSlider.setPaintLabels(true);
widthSpinner.setEditor(new JSpinner.NumberEditor(widthSpinner));
widthSpinner.setPreferredSize(new Dimension(70, 30));
widthSpinner.setMaximumSize(widthSpinner.getPreferredSize());
heightSlider.setMajorTickSpacing(300);
heightSlider.setMinorTickSpacing(20);
heightSlider.setPaintTicks(true);
heightSlider.setPaintLabels(true);
heightSpinner.setEditor(new JSpinner.NumberEditor(heightSpinner));
heightSpinner.setPreferredSize(new Dimension(70, 30));
heightSpinner.setMaximumSize(heightSpinner.getPreferredSize());
confirmButton.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e)
{
widthOfFrames = 200;
grid.refresh();
}
});
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setPreferredSize(new Dimension(300, 480));
p.setSize(new Dimension(300, 480));
numColsSelectorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
numColsSelectorField.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
confirmButton.setAlignmentX(Component.CENTER_ALIGNMENT);
widthLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
heightLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
p.add(Box.createRigidArea(new Dimension(300, 30)));
p.add(numColsSelectorLabel);
p.add(Box.createRigidArea(new Dimension(300, 5)));
p.add(numColsSelectorField);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(widthLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(widthSpinner);
p.add(widthSlider);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(heightLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(heightSpinner);
p.add(heightSlider);
p.add(Box.createRigidArea(new Dimension(300, 45)));
p.add(confirmButton);
return p;
}
private static void createAndShowGUI() {
BuildGridGUI2 b = new BuildGridGUI2();
JFrame mainFrame = new JFrame("Grid Builder");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(940, 480);
mainFrame.getContentPane().add(b.makeUI());
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
class Grid extends JComponent
{
static final int CANVAS_WIDTH = 640;
static final int CANVAS_HEIGHT = 480;
private final double conversionRatio = 4.0/9.0; // 1080p scaled down to 480p preview
private int squareHeight, squareWidth, numColumns, numRows;
public Grid()
{
setOpaque(true);
setSize(CANVAS_WIDTH, CANVAS_HEIGHT); // trying to get the size to work properly.
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
updateVars();
int k;
for (k = 0; k < numColumns; k++)
{
// #param: (x1, y1), (x2, y2)
g.drawLine(k * squareWidth, 0, k * squareWidth, CANVAS_HEIGHT);
}
for (k = 0; k < numRows; k++)
{
g.drawLine(0, k * squareHeight, CANVAS_WIDTH, k * squareHeight);
}
}
public void refresh()
{
// Attempting to set the repaint area to only the grid region
// because CTRL+F is free and parameters are not
repaint(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
public void updateVars()
{
this.squareWidth = (int)(
(double)BuildGridGUI2.this.widthOfFrames
*
conversionRatio);
this.squareHeight = (int)(
(double)BuildGridGUI2.this.heightOfFrames
*
conversionRatio);
this.numColumns = BuildGridGUI2.this.numCols;
this.numRows = (int)(
(
(double)BuildGridGUI2.this.numFrames
/
numColumns
)
+ 0.5);
}
}
}
Actual Source Code (Not strictly relevant, but if you're in the mood for code review then I'd love to learn better coding conventions.)
Thank you!
All of the sidebar components get painted at the top-left corner, while still showing/functioning on the sidebar;
JComponent is an abstract class that all Swing components extend from. It has no default painting logic.
Therefore invoking super.paintComponent(...) does not really do anything.
In particular it does not clear the background of the component before doing custom painting. This will result in the painting artifacts that you see.
Any time you extend JComponent your logic should be something something like:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear background
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
// do custom painting
g.setColor( getForeground() );
...
}
Note: this is the reason the many people override JPanel for simple custom painting as mentioned by Abra. The paintComponent(...) method of the JPanel will clear the background by default.
I made a few changes to the code you posted.
I changed class Grid such that it extends JPanel and not JComponent, since custom painting is usually done on a JPanel.
I added a instance member variable grid with type Grid, to class BuildGridGUI2 rather than creating one and sending it as a parameter to method makeSideMenu.
Here is your code with my modifications (and my preferred coding style). It simply solves your reported problem and nothing more.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BuildGridGUI2 {
static final int WIDTH_MIN = 100;
static final int WIDTH_MAX = 2000;
static final int WIDTH_INIT = 520;
static final int HEIGHT_MIN = 100;
static final int HEIGHT_MAX = 2000;
static final int HEIGHT_INIT = 300;
int widthOfFrames = 255;
int heightOfFrames = 255;
int numCols = 3;
int numFrames = 1;
Grid grid;
private final JComponent makeUI() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
grid = new Grid();
JComponent j = makeSideMenu();
grid.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red),
grid.getBorder()));
j.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red),
j.getBorder()));
p.add(j, BorderLayout.EAST);
p.add(grid, BorderLayout.WEST);
return p;
}
private final JComponent makeSideMenu() {
JPanel p = new JPanel();
JLabel numColsSelectorLabel = new JLabel("Frames Per Column");
JSpinner numColsSelectorField = new JSpinner();
JLabel widthLabel = new JLabel("Width per Frame (Pixels)");
JSpinner widthSpinner = new JSpinner();
JSlider widthSlider = new JSlider(WIDTH_MIN, WIDTH_MAX, WIDTH_INIT);
JLabel heightLabel = new JLabel("Height per Frame (Pixels)");
JSpinner heightSpinner = new JSpinner();
JSlider heightSlider = new JSlider(BuildGridGUI2.HEIGHT_MIN,
BuildGridGUI2.HEIGHT_MAX,
BuildGridGUI2.HEIGHT_INIT);
JButton confirmButton = new JButton("Confirm");
numColsSelectorField.setEditor(new JSpinner.NumberEditor(numColsSelectorField));
numColsSelectorField.setMaximumSize(numColsSelectorField.getPreferredSize());
widthSlider.setMajorTickSpacing(300);
widthSlider.setMinorTickSpacing(20);
widthSlider.setPaintTicks(true);
widthSlider.setPaintLabels(true);
widthSpinner.setEditor(new JSpinner.NumberEditor(widthSpinner));
widthSpinner.setPreferredSize(new Dimension(70, 30));
widthSpinner.setMaximumSize(widthSpinner.getPreferredSize());
heightSlider.setMajorTickSpacing(300);
heightSlider.setMinorTickSpacing(20);
heightSlider.setPaintTicks(true);
heightSlider.setPaintLabels(true);
heightSpinner.setEditor(new JSpinner.NumberEditor(heightSpinner));
heightSpinner.setPreferredSize(new Dimension(70, 30));
heightSpinner.setMaximumSize(heightSpinner.getPreferredSize());
confirmButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
widthOfFrames = 200;
grid.refresh();
}
});
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setPreferredSize(new Dimension(300, 480));
p.setSize(new Dimension(300, 480));
numColsSelectorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
numColsSelectorField.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
confirmButton.setAlignmentX(Component.CENTER_ALIGNMENT);
widthLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
heightLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
p.add(Box.createRigidArea(new Dimension(300, 30)));
p.add(numColsSelectorLabel);
p.add(Box.createRigidArea(new Dimension(300, 5)));
p.add(numColsSelectorField);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(widthLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(widthSpinner);
p.add(widthSlider);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(heightLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(heightSpinner);
p.add(heightSlider);
p.add(Box.createRigidArea(new Dimension(300, 45)));
p.add(confirmButton);
return p;
}
private static void createAndShowGUI() {
BuildGridGUI2 b = new BuildGridGUI2();
JFrame mainFrame = new JFrame("Grid Builder");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(940, 480);
mainFrame.getContentPane().add(b.makeUI());
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
class Grid extends JPanel {
static final int CANVAS_WIDTH = 640;
static final int CANVAS_HEIGHT = 480;
private final double conversionRatio = 4.0 / 9.0; // 1080p scaled down to 480p preview
private int squareHeight, squareWidth, numColumns, numRows;
public Grid() {
setOpaque(true);
setSize(CANVAS_WIDTH, CANVAS_HEIGHT); // trying to get the size to work properly.
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
updateVars();
int k;
for (k = 0; k < numColumns; k++) {
// #param: (x1, y1), (x2, y2)
g.drawLine(k * squareWidth, 0, k * squareWidth, CANVAS_HEIGHT);
}
for (k = 0; k < numRows; k++) {
g.drawLine(0, k * squareHeight, CANVAS_WIDTH, k * squareHeight);
}
}
public void refresh() {
// Attempting to set the repaint area to only the grid region
// because CTRL+F is free and parameters are not
repaint(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
public void updateVars() {
this.squareWidth = (int) ((double) BuildGridGUI2.this.widthOfFrames * conversionRatio);
this.squareHeight = (int) ((double) BuildGridGUI2.this.heightOfFrames * conversionRatio);
this.numColumns = BuildGridGUI2.this.numCols;
this.numRows = (int) (((double) BuildGridGUI2.this.numFrames / numColumns) + 0.5);
}
}
}
One tip: Try to use specific sub-classes of JComponent rather than JComponent. For example, I suggest changing the return type of method makeSideMenu() to JPanel rather than JComponent since that method actually returns a JPanel.

How to make this text area show which toggle buttons are selected?

Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

JScrollPane not showing scrollbars when an Array of JPanels are added to it

Im adding an array of JPanels inside a JScrollPane. The array of JPanels are being added to the JScrollPane but the scroll bars just wont show.
public class MyFrame extends JFrame {
private JPanel contentPane;
private JPanel panel_1;
private JScrollPane scrollPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 288, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel_1 = new JPanel();
panel_1.setBounds(10, 114, 434, 136);
panel_1.setLayout(null);
scrollPane = new JScrollPane(panel_1);
scrollPane.setBounds(52, 57, 164, 126);
scrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Histogram", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
scrollPane.setLayout(new ScrollPaneLayout());
contentPane.add(scrollPane);
buildBar();
}
JPanel[] barPanel;
private void buildBar(){
int x=0,y=22,w=100,h=80,s=10,n=3;
barPanel = new JPanel[n];
for(int i=0; i<n; i++){
barPanel[i] = new JPanel();
barPanel[i].setBounds(x, y, w, h);
barPanel[i].setBackground(new Color(255,0,0));
panel_1.add(barPanel[i]);
panel_1.revalidate();
panel_1.repaint();
x = x + w + s;
}
}
}
I have been working on it for hours . Maybe there is something that I've missed out.
You're shooting yourself in the foot with these two lines:
panel_1.setBounds(10, 114, 434, 136);
panel_1.setLayout(null);
Both of which will mess up the JScrollPane's ability to use and display scrollbars. What you need to do is: not to use setBounds but rather have the components use their preferredSize, and avoid using null layout, since this won't change the container's preferredSize.
Yet another reason to studiously avoid null layouts.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class MyPanel2 extends JPanel {
private static final int PREF_W = 388;
private static final int PREF_H = PREF_W;
public static final int INNER_PREF_W = 434;
public static final int INNER_PREF_H = 126;
private static final int HISTO_PANEL_COUNT = 6;
private static final Dimension VP_SZ = new Dimension(164, 126);
private JPanel holderPanel = new JPanel(new GridLayout(0, 1));
public MyPanel2() {
int w = INNER_PREF_W;
int h = INNER_PREF_H;
for (int i = 0; i < HISTO_PANEL_COUNT; i++) {
holderPanel.add(new InnerPanel(w, h));
}
JScrollPane scrollPane = new JScrollPane(holderPanel);
scrollPane.getViewport().setPreferredSize(VP_SZ);
setLayout(new GridBagLayout());
add(scrollPane);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class InnerPanel extends JPanel {
private int w;
private int h;
public InnerPanel(int w, int h) {
this.w = w;
this.h = h;
setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0, y = 22, w = 100, h = 80, s = 10, n = 3;
g.setColor(Color.RED);
for (int i = 0; i < n; i++) {
g.fillRect(x, y, w, h);
x = x + w + s;
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(w, h);
}
}
private static void createAndShowGui() {
MyPanel2 mainPanel = new MyPanel2();
JFrame frame = new JFrame("MyPanel2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
JScrollPane relies on the preferredSize of your container to determine the scroll bar width. If you use a Layout, the preferredSize will be determined for you when components are added to the panel.
However, when you use:
contentPane.setLayout(null);
You are preventing the preferredSize from changing based on added components.
Try to use a layout which is applicable for your case.
In case you are very certain you do not want to use a Layout, in order to see the scroll bar, you may set the preferredSize of the container for every components you added by manually adjusting the preferredSize. That way, the scrollbar will still extend with newly added components.

Quadratic Equation In Java With Sliders

I have to design and implement an application that draws the graph of the equation of ax^2 + bx + c where the values of a b and c are set using sliders. I am editing my original post and thus am going to do my best to post an sscce. My code is below. Everything compiles and runs. My one question is why is my graph not displaying anything when the sliders are moved? Here are my 2 class files:
import java.awt.*;
import javax.swing.*;
public class QuadraticGraph
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Quadratic Grapher");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new QuadraticPanel());
frame.pack();
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class QuadraticPanel extends JPanel
{
private JPanel controls, quadpanel;
private JSlider aslider, bslider, cslider;
private JLabel alabel, blabel, clabel;
//-----------------------------------------------------------------
// Sets up the sliders and their labels, aligning them along
// their left edge using a box layout.
//-----------------------------------------------------------------
public QuadraticPanel()
{
aslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
aslider.setMajorTickSpacing (50);
aslider.setMinorTickSpacing (10);
aslider.setPaintTicks (true);
aslider.setPaintLabels (true);
aslider.setAlignmentX (Component.LEFT_ALIGNMENT);
bslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
bslider.setMajorTickSpacing (50);
bslider.setMinorTickSpacing (10);
bslider.setPaintTicks (true);
bslider.setPaintLabels (true);
bslider.setAlignmentX (Component.LEFT_ALIGNMENT);
cslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
cslider.setMajorTickSpacing (50);
cslider.setMinorTickSpacing (10);
cslider.setPaintTicks (true);
cslider.setPaintLabels (true);
cslider.setAlignmentX (Component.LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
aslider.addChangeListener (listener);
bslider.addChangeListener (listener);
cslider.addChangeListener (listener);
alabel = new JLabel ("A: 0");
alabel.setAlignmentX (Component.LEFT_ALIGNMENT);
blabel = new JLabel ("B: 0");
blabel.setAlignmentX (Component.LEFT_ALIGNMENT);
clabel = new JLabel ("C: 0");
clabel.setAlignmentX (Component.LEFT_ALIGNMENT);
controls = new JPanel();
BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);
controls.setLayout (layout);
controls.add (alabel);
controls.add (aslider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (blabel);
controls.add (bslider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (clabel);
controls.add (cslider);
quadpanel = new JPanel();
quadpanel.setPreferredSize (new Dimension (500, 500));
quadpanel.setBackground (Color.white);
add (controls);
add (quadpanel);
}
//*****************************************************************
// Represents the listener for all three sliders.
//*****************************************************************
private class SliderListener implements ChangeListener
{
private double a, b, c, x, y, g, h;
//--------------------------------------------------------------
// Gets the value of each slider, then updates the labels and
// the color panel.
//--------------------------------------------------------------
public void stateChanged (ChangeEvent event)
{
a = aslider.getValue();
b = bslider.getValue();
c = cslider.getValue();
alabel.setText ("A: " + a);
blabel.setText ("B: " + b);
clabel.setText ("C: " + c);
}
public void paintComponent (Graphics page)
{
x = (-b + (Math.sqrt((b*b - ((4 * a * c))))))/ (2 * a);
y= (a*(Math.pow(x,2)))+(b*x)+(c);
int g = (int)Math.round(x);
int h = (int)Math.round(y);
page.setColor (Color.black);
page.drawOval (g, h, 1, 1);
}
}
}
i guess you're very new to java, so here's some starters help ^^
create a content Panel and set some layout to the panel;
add the sliders and a drawing-panel to your content panel;
you're doing it right, adding an change listener to the slider, but they should redraw the drawing-panel.
i'll add this snippets to make it easier for you ^_^
private JPanel drawPanel; //don't forget to create a proper one! override paint in that panel!
private int a,b,c;
public QuadraticPanel(){ //constructor
setLayout(new BoderLayout();
JSlider aSidler = new JSlider();
slider.addChangeListener(new ChangeListener(){
#Override
public void stateChanged(ChangeEvent arg0) {
a = arg0.getValue(); //setting a value
//it might even be better to calculate the value
//BEFORE you redraw
//recalcEquotiation()
drawPanel.repaint(); //and redraw the paint-panel
}
});
add(aSlider, Borderlayout.WEST); //add more sliders with better layouts or subcomponents
add(drawPanel, BorderLayout.CENTER);
}
don't forget - these are just snippets, you'll have to do some work on your own...

ImageManager program

I am working on a project where I have to create an image manager program in Java. The program will have the following features in it: Program should take image from the user as input. Then it should display the image in panel(1), and in panel(2) it should give the user an options of changing width, height, hgap, vgap, top margin and left margin of the image with an 'OK' button at the end including an 'action listener' feature. Using the above mentioned features we will get the grids on the image. Now if the user clicks on the particular grid then that particular image should get extracted into a folder.
I am attaching the program which we have done so far.
The difficulties we are facing are: we are not able to insert a JScrollPane for the image. As well as we are unaware of how to add action listeners to the grids so that we can extract that particular image.
package project_image_manager_imp_files;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
class SidePanel1 extends JPanel implements ActionListener {
JTextField top_margin = new JTextField(10);
JTextField left_margin = new JTextField(10);
JTextField Width = new JTextField(10);
JTextField Height = new JTextField(10);
JTextField Vgap = new JTextField(10);
JTextField Hgap = new JTextField(10);
JLabel j1 = new JLabel("Top margin");
JLabel j2 = new JLabel("Left margin");
JLabel j3 = new JLabel("Width");
JLabel j4 = new JLabel("Height");
JLabel j5 = new JLabel("Vertical gap");
JLabel j6 = new JLabel("Horizontal gap");
JButton b = new JButton("OK");
public SidePanel1() {
this.setBackground(Color.black);
Dimension d1 = new Dimension(1000, 1000);
this.setMaximumSize(d1);
this.setPreferredSize(d1);
JPanel p = new JPanel();
JScrollPane vertical = new JScrollPane();
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(vertical);
vertical.setVerticalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(vertical);
//showCoo.build(c);
//c.add(p);
//p.setOpaque(false);
//t1.addActionListener(new JTextFieldEventClass() );
//b.addActionListener(new JTextFieldEventClass() );
// String s=t3.getText();
//int c=Integer.parseInt(s);
p.add(j1);
p.add(top_margin);
p.add(j2);
p.add(left_margin);
p.add(j3);
p.add(Width);
p.add(j4);
p.add(Height);
p.add(j5);
p.add(Vgap);
p.add(j6);
p.add(Hgap);
p.add(b);
p.setLayout(new GridLayout(7, 2));
b.addActionListener(this);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.setBounds(200, 200, 600, 400);
frame.setTitle("Hello World Test");
frame.setResizable(true);
//frame.setSize (500, 300);
Container c = frame.getContentPane();
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.WEST);
frame.add(p, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
int height;
int width;
int hgap;
int vgap;
int tm;
int lm;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("images1.jpg"), 0, 0, this);
Graphics2D g2d = (Graphics2D) g.create();
//File f=new File("images1.jpg");
//BufferedImage im=ImageIO.read(f);
int frame_width = getWidth();
int frame_height = getHeight();
for (int j = 0; j < frame_height; j++) {
int y = tm + (height * j) + (vgap * j);
for (int i = 0; i < frame_width; i++) {
int x = lm + (width * i) + (hgap * i);
g.drawRect(x, y, width, height);
}
}
}
public static void main(String[] argv) {
//static JScrollBar scrollbar;
SidePanel1 panel = new SidePanel1();
panel.setLayout(new FlowLayout());
//scrollbar = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//panel.add(scrollbar);
try {
while (true) {
Thread.sleep(100);
///.out.println("("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
}
} catch (InterruptedException e) {}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
width = Integer.parseInt(Width.getText());
height = Integer.parseInt(Height.getText());
hgap = Integer.parseInt(Hgap.getText());
vgap = Integer.parseInt(Vgap.getText());
lm = Integer.parseInt(left_margin.getText());
tm = Integer.parseInt(top_margin.getText());
repaint();
}
}

Categories