Java Swing button creates a dupe on the panel below it - java

We have this assignment where we make a GUI window which sets a panel's color based on RGB-Alpha values. I got it mostly working, but when I click the change color button, it duplicates (I'm not sure if its only visual bug) a clicked state of itself under it. It's not visible if alpha is 255 because it's fully opaque, but if it's transparent, the visual glitch thing is visible.
Screenshots of Window/Frame: https://imgur.com/a/Vf1Hb2B
This is my current code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class ColorCalc implements ActionListener {
//Containers
private JFrame f;
private JPanel colorPanel;
//Components
private JLabel l1,l2,l3,l4;
private JTextField redTf,greenTf,blueTf,alphaTf;
private JButton bCompute,bClear;
public ColorCalc()
{
//Containers
f = new JFrame("My Color Calculator");
f.setPreferredSize(new Dimension(400, 250));//Set Frame Size
colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(300, 200));//Set Panel Size
//Components
l1 = new JLabel("Red:");
l2 = new JLabel("Green:");
l3 = new JLabel("Blue:");
l4 = new JLabel("Alpha:");
redTf = new JTextField("0", 3);
greenTf = new JTextField("0", 3);
blueTf = new JTextField("0", 3);
alphaTf = new JTextField("0", 3);
bCompute = new JButton("Compute");
bClear = new JButton("Clear");
//Action Listeners
bCompute.addActionListener(this);
bClear.addActionListener(this);
}
public void startApp()
{
//Labels Panel
JPanel lPanel = new JPanel();
lPanel.setLayout(new GridLayout(5,1));
lPanel.add(l1);
lPanel.add(l2);
lPanel.add(l3);
lPanel.add(l4);
lPanel.add(bCompute);
//Text Fields Panel
JPanel tfPanel = new JPanel();
tfPanel.setLayout(new GridLayout(5,1));
tfPanel.add(redTf);
tfPanel.add(greenTf);
tfPanel.add(blueTf);
tfPanel.add(alphaTf);
tfPanel.add(bClear);
//Labels + TextFields Panel
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new GridLayout(1,2));
inputPanel.add(lPanel);
inputPanel.add(tfPanel);
//Add all panels to Frame
f.setLayout(new GridLayout(2,1));
f.add(inputPanel);
f.add(colorPanel);
f.setLocationRelativeTo(null);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == bCompute)
{
//Set Default Values
int red = 255;
int green = 255;
int blue = 255;
int alpha = 255;
try
{
//Get Values and Parse to Integer
red = Integer.parseInt(redTf.getText());
green = Integer.parseInt(greenTf.getText());
blue = Integer.parseInt(blueTf.getText());
alpha = Integer.parseInt(alphaTf.getText());
} catch (NumberFormatException nfe)//If Parsing failed due to invalid types
{
red = 255; green = 255; blue = 255; alpha = 255; //Set values to white
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
if(red < 256 && green < 256 && blue < 256 && alpha < 256)//Max Value: 255
{
if(red > -1 && green > -1 && blue > -1 && alpha > -1)//Min Value: 0
colorPanel.setBackground(new Color(red, green, blue, alpha));
else
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
else
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
else if(e.getSource() == bClear)
{
//Set all values to 0 and set panel to white
redTf.setText("0");
greenTf.setText("0");
blueTf.setText("0");
alphaTf.setText("0");
colorPanel.setBackground(Color.WHITE);
}
}
public static void main(String[] args)
{
ColorCalc colCalc = new ColorCalc();
colCalc.startApp();
}
}

Call the method f.repaint(); at the end of the actionPerformed() method
See more info here

Related

FlowLayout not going to new line

I'm trying to add a variable number of JPanels (each one containst 2 Label) inside another JPanel using the FlowLayout.
When there's too many panels added instead of going to the new row they disappear out of the border
I've tried many types of Layouts, setting sizes, maximussizes but nothing changes.
public class AlbumView extends javax.swing.JFrame
{
private Album A;
public AlbumView()
{
initComponents();
A = new Album();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = this.getSize().width;
int h = this.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
this.setLocation(x, y);
pnlCategorie.setLayout(new FlowLayout(FlowLayout.TRAILING, 10, 10));
/*
Insert of many elements in the Album
*/
aggiornaAlbum();
}
public void aggiornaAlbum()
{
for(int i = 0; i < A.getDim(); i++)
{
Categoria c = A.getCategoria(i);
JPanel pnl = new JPanel();
pnl.setName(c.getNome());
JLabel lb1, lb2;
ImageIcon img = new ImageIcon(c.getPhoto(0).getImg(95, 95)); //da cambiare lo 0 con un numero casuale tra le foto disponibili
lb1 = new JLabel(img, JLabel.CENTER);
lb2 = new JLabel(c.getNome(), JLabel.CENTER);
pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));
pnl.setBorder(BorderFactory.createLineBorder(Color.black));
pnl.add(lb1);
pnl.add(lb2);
//pnl.revalidate();
//pnl.repaint();
pnlCategorie.add(pnl);
}
//ADDED AFTER COMMENT, NOTHING CHANGED (but probably it's because i didn't get exaclty what to do
pnlCategorie.revalidate();
pnlCategorie.repaint();
}
pnlCategorie is created using NetBeans swing.
I expect that after the number of jpanels that fits the bigger jPanel the next one goes to a new line
Example of what is appearing (I'm using some exaple image, don't judge) :

JPanel sizing inside Another JPanel

I really need help with this. I have been having problems resizing the gameBoardPanel JPanel that is added the the main Panel. Everything I have tried including resizing it has not helped, I basically want to add the gameBoardPanel at 400x400 to the main panel (which is 400x500), leaving me 400x100 of space for other buttons e.x return to menu, etc. Any help would be much appreciated!
Thanks!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.*;
public class SliderPractice extends JFrame implements ActionListener {
private int numberOfRows, mode;
private JPanel gameBoardPanel, menuPanel, main; //create a panel to add to JFRAME
private int emptyIndex; //Variable will track the empty spot
private int moves = 0;
JButton[] buttons, compareButtons;
private JLabel radioButtons, radioButtons1;
private ButtonGroup radioButtonGroup1, radioButtonGroup2;
private JButton start, displayInstructions = new JButton(); //buttons on start panel
private JTextArea title;
private JRadioButton easy, medium, hard, extreme, three, four, five, six; //Radio buttons allow user to only select 1 of 3
public SliderPractice()
{
super("Slider! - By: Michel V.");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400); //Overall size of grid but window
//is resizable by default. Layout
//Manager takes care of the necessary scaling.
setResizable(false); //set resizable false for menu
menu(); //calling menu
}
public void actionPerformed(ActionEvent e) { //when an action is performed
if (e.getSource().equals(start)){ //Start button
startUp(); //starts up game
}
for(int i = 0 ; i < buttons.length; i++) //checks for all the game buttons if any were pressed
{
if(e.getSource() == buttons[i]) //if a specific game button is pressed
{
if(isNextTo(i, emptyIndex)==true) //calling isNextTo to make sure its beside one another
{
swapPieces(i); //if its beside, swap pieces and increase number of moves
moves++;
}
}
}
if(win()){ //if Win == true
int select = JOptionPane.showConfirmDialog(this, "You won with " + moves + " moves! Play same settings again(Y/N)?\n Or press cancel to exit!");
//Yes clicked - Play again
if (select == JOptionPane.YES_OPTION){
scramble();
moves = 0;
}//no picked, resetGUI!
else if (select == JOptionPane.NO_OPTION){
resetGUI();
}//if Cancel or closed is picked, exit program
else if (select == JOptionPane.CANCEL_OPTION){
System.exit(0);
}
else if (select == JOptionPane.CLOSED_OPTION){
System.exit(0);
}
}
}
public void gamePanel(int numberRows){
numberOfRows = numberRows;
buttons = new JButton[numberOfRows*numberOfRows]; //Make room for as many buttons as needed for picked number of Rows
compareButtons = new JButton[numberOfRows*numberOfRows];
Font f = new Font("Arial", Font.BOLD, 22);
Color[] colours = {Color.red, Color.green};
gameBoardPanel = new JPanel();
gameBoardPanel.setLayout(new GridLayout(numberOfRows,numberOfRows,5,5)); // 4x4 grid with 5 pixel
// vert/horz dividers
gameBoardPanel.setBackground(Color.white); //Allows empty space to be black
for (int i = 0; i < buttons.length; i++) //From i is 0 to 15
{
int colourIndex = 0; //Start with Orange
compareButtons[i] = new JButton("" + i);
buttons[i] = new JButton("" + i); //Constructor sets text on new buttons
buttons[i].setSize(100,100); //Button size, but don't really need this line
//line since we are using Layout Manager
if (numberOfRows %2 ==0){
if (i % 2 == 0) //Alternate orange and white for evens and odds
colourIndex = 1;
if ((i/4)%2 == 0)
colourIndex = 1-colourIndex;
}
else{
if(i % 2 == 0)
colourIndex = 1;
}
buttons[i].setBackground(colours[colourIndex]);
buttons[i].setForeground(Color.white); //Text colour
buttons[i].setFont(f);
buttons[i].addActionListener(this); //Set up ActionListener on each button
gameBoardPanel.add(buttons[i]); //Add buttons to the grid layout of
//gameBoardPanel
}
emptyIndex=(numberOfRows*numberOfRows-1);
buttons[emptyIndex].setVisible(false);
}
public void menu(){
Font f = new Font("Arial", Font.BOLD, 26);
Font t = new Font("Trebuchet MS", Font.BOLD, 13);
Color[] colours = {Color.red, Color.green};
/*--- JPanel for Start Menu ---*/
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(colours[0]);
menuPanel.setVisible(true);
//Title
title = new JTextArea("Michel's Slider \n Game!");
title.setLineWrap(true);
title.setWrapStyleWord(true);
title.setBounds(100, 10, 250, 60);
title.setFont(f);
title.setBorder(BorderFactory.createEmptyBorder());
title.setBackground(colours[0]);
title.setEditable(false);
title.setEnabled(false);
title.setDisabledTextColor(Color.BLACK);
//Label for radio buttons
radioButtons = new JLabel("Choose the difficulty for this game:");
radioButtons.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
radioButtons.setBounds(50, 155, 400, 20);
//Radio buttons to select picture to play with
easy = new JRadioButton("Easy");
easy.setBackground(colours[0]);
easy.setBounds(15, 178, 100, 20);
easy.setActionCommand("Mode 1");
easy.setFont(t);
easy.setSelected(true); //Default selection
medium = new JRadioButton("Medium");
medium.setBackground(colours[0]);
medium.setBounds(120, 178, 100, 20);
medium.setFont(t);
hard = new JRadioButton("Hard");
hard.setBackground(colours[0]);
hard.setBounds(215, 178, 100, 20);
hard.setFont(t);
extreme = new JRadioButton("Extreme");
extreme.setBackground(colours[0]);
extreme.setBounds(310, 178, 100, 20);
extreme.setFont(t);
//Add radio buttons to a group
radioButtonGroup1 = new ButtonGroup();
radioButtonGroup1.add(easy);
radioButtonGroup1.add(medium);
radioButtonGroup1.add(hard);
radioButtonGroup1.add(extreme);
radioButtons1 = new JLabel("Choose the size for this game:");
radioButtons1.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
radioButtons1.setBounds(68, 100, 400, 20);
//Radio buttons to select picture to play with
three = new JRadioButton("3x3");
three.setBackground(colours[0]);
three.setBounds(15, 124, 110, 20);
three.setActionCommand("Mode 1");
three.setFont(t);
three.setSelected(true); //Default selection
four = new JRadioButton("4x4");
four.setBackground(colours[0]);
four.setBounds(120, 124, 100, 20);
four.setFont(t);
five = new JRadioButton("5x5");
five.setBackground(colours[0]);
five.setBounds(215, 124, 100, 20);
five.setFont(t);
six = new JRadioButton("6x6");
six.setBackground(colours[0]);
six.setBounds(310, 124, 100, 20);
six.setFont(t);
//Add radio buttons to a group
radioButtonGroup2 = new ButtonGroup();
radioButtonGroup2.add(three);
radioButtonGroup2.add(four);
radioButtonGroup2.add(five);
radioButtonGroup2.add(six);
//Start game button
start = new JButton("Start Game");
start.addActionListener(this);
start.setBounds(110, 290, 170, 35);
start.setBackground(colours[1]);
start.setFont(new Font("Trebuchet MS", Font.BOLD, 22));
//Instructions button
displayInstructions = new JButton("Instructions");
displayInstructions.addActionListener(this);
displayInstructions.setBounds(130, 335, 130, 20);
displayInstructions.setBackground(colours[1]);
displayInstructions.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
//Add components to start panel
menuPanel.add(start);
menuPanel.add(displayInstructions);
menuPanel.add(title);
menuPanel.add(easy);
menuPanel.add(medium);
menuPanel.add(hard);
menuPanel.add(extreme);
menuPanel.add(radioButtons);
menuPanel.add(three);
menuPanel.add(four);
menuPanel.add(five);
menuPanel.add(six);
menuPanel.add(radioButtons1);
/*--- End Start Menu JPanel ---*/
add(menuPanel);
setVisible(true);
}
public static void main(String[] args) {
new SliderPractice(); //Run constructor for class
}
private void swapPieces(int btnIndex) //Send along button that was pushed
{
buttons[emptyIndex].setText(buttons[btnIndex].getText()); //Move over text
//to blank button
buttons[btnIndex].setVisible(false); //Turn off visibility of button that was pushed
//and background will show through as black
buttons[emptyIndex].setVisible(true);//Turn on visibility of the old blank button
emptyIndex = btnIndex; //Update the emptyIndex to the button that was
//pushed.
}
private boolean isNextTo(int choice, int blankButton)
{
if(choice/numberOfRows==blankButton/numberOfRows){
if(Math.abs(choice-blankButton)==1) return true;
}
else if(Math.abs(choice/numberOfRows-blankButton/numberOfRows)==1) {
if(Math.abs(choice-blankButton)==numberOfRows) {
return true;
}
}
return false;
}
private boolean win()
{
int count = 0;
for (int i = 0; i < buttons.length; i++) //From i is 0 to 15
{
if(buttons[i].getText().equals(compareButtons[i].getText()))
{
count++;
}
else{
break;
}
}
if (count == (numberOfRows*numberOfRows-1))
return true;
else
return false;
}
private void scramble()
{
int s = 0;
int g;
int max = (int) Math.pow(numberOfRows, mode);
while (s<max)
{
g = (int) ((Math.random()*(numberOfRows*numberOfRows))-1);
if(isNextTo(g, emptyIndex)==true)
{
swapPieces(g);
s++;
}
}
}
private void startUp(){
int size = 0;
//Set image on button according to radio button selection
if (three.isSelected()){
size = 3;
}
else if (four.isSelected()){
size = 4;
}
else if (five.isSelected()){
size = 5;
}
else if (six.isSelected()){
size = 6;
}
if (easy.isSelected()){
mode = 2;
}
else if (medium.isSelected()){
mode = 3;
}
else if (hard.isSelected()){
mode = 4;
}
else if (extreme.isSelected()){
mode = 5;
}
gamePanel(size);
setSize(400, 500);
gameBoardPanel.setEnabled(false);
//Switch panels from start panel to main panel
main = new JPanel();
menuPanel.setVisible(false);
remove(menuPanel);
main.add(gameBoardPanel);
main.setSize(400, 400);
main.setBackground(Color.white);
add(main);
setResizable(true);
//Shuffle Pieces
scramble();
}
private void resetGUI(){
numberOfRows = 0;
moves = 0;
emptyIndex = 0;
setResizable(false);
setSize(400,400);
remove(gameBoardPanel);
add(menuPanel);
menu();
mode = 0;
}
}
It's really hard to understand what you want to achieve. You want to make room to which buttons at the bottom?? How is the screen supposed to look like?
Anyway, i think you should use different panels and layoutmanagers to solve your problem, and what I think can help you best is the BorderLayout.
If you want your gameBoardPanel to fully fit the window when the game starts, you could change your code to something like this at the end of your startUp() method:
//Switch panels from start panel to main panel
main = new JPanel(new BorderLayout());
menuPanel.setVisible(false);
remove(menuPanel);
main.add(gameBoardPanel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
buttonsPanel.setPreferredSize(new Dimension(400, 100));
main.add(buttonsPanel, BorderLayout.SOUTH);
From looking at your code it is obvious you haven't read the layout manager tutorials. From your description you almost certainly want to use BorderLayout, put your game panel in CENTER and your button panel in SOUTH.
The component in CENTER position gets all left over space and the component in SOUTH gets its preferred height honored, but takes all available width.
https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

JFrame not becoming transparent

Recently I have been trying to get a transparent JFrame without success.
I want to make all components visible but not the frame and I see that people set the background to transparent and set Opaque to false.
I am doing this but without success.
public class KeyDialog extends JFrame {
public static MapPanel mapPanel = new MapPanel();
public KeyDialog() {
GridBagConstraints customGridBagLayout = new GridBagConstraints();
setLayout(new GridBagLayout());
setUndecorated(true);
// Title - Row 1
JTextField row1 = new JTextField();
row1.setSize(new Dimension(this.getWidth(), HEIGHT));
row1.setFont(new Font("Arial", Font.PLAIN, 30));
PromptSupport.setPrompt("Title Goes Here", row1);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.gridy = 0;
add(row1, customGridBagLayout);
// Key - Row 2
JPanel row2 = new JPanel();
row2.setOpaque(false);
// With Key
JPanel withKey = titleBoxKey(true);
withKey.setBackground(new Color(0, 0, 0, 0));
row2.add(withKey);
// Against Key
JPanel againstKey = titleBoxKey(false);
againstKey.setBackground(new Color(0, 0, 0, 0));
row2.add(againstKey);
customGridBagLayout.gridy = 1;
add(row2, customGridBagLayout);
pack();
}
public static JPanel titleBoxKey(boolean with) {
JPanel keyPanel = new JPanel();
keyPanel.setLayout(new GridBagLayout());
GridBagConstraints customGridBagLayout = new GridBagConstraints();
customGridBagLayout.insets = new Insets(7, 7, 7, 7); // Padding
Color republicanColor = null;
Color democraticColor = null;
if (with) {
republicanColor = mapPanel.getRepublicanWithColor();
democraticColor = mapPanel.getRepublicanAgainstColor();
} else if (!with) {
republicanColor = mapPanel.getDemocraticAgainstColor();
democraticColor = mapPanel.getDemocraticAgainstColor();
}
// Row 1 - Rectangles and Text Field
// Democratic Rectangle
JLabel republicanRect = mapPanel.drawRect(republicanColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 0;
keyPanel.add(republicanRect, customGridBagLayout);
// Republican Rectangle
JLabel democraticRect = mapPanel.drawRect(democraticColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 0;
keyPanel.add(democraticRect, customGridBagLayout);
// With/Against Label
JLabel infoLabel;
if (with) {
infoLabel = new JLabel("With");
} else {
infoLabel = new JLabel("Against");
}
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 2;
customGridBagLayout.gridy = 0;
keyPanel.add(infoLabel, customGridBagLayout);
// Row 2 - Bottom Text
// Republican Label
JLabel republicanLabel = new JLabel("Republican");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 1;
keyPanel.add(republicanLabel, customGridBagLayout);
// Democrat Label
JLabel democraticLabel = new JLabel("Democratic");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 1;
keyPanel.add(democraticLabel, customGridBagLayout);
return keyPanel;
}
}
You've made a nice attempt, but try this instead.
// Apply a transparent colour
setBackground(new Color(0, 255, 0, 0));
Simply add that code and your done :)
I set the background to frame.setBackground(new Color(0, 0, 0, 0)); thanks to the help of #JontyMorris
I then set all the contents on the frame to opaque panel.setOpaque(false);
and removed the backgrounds I set so the stripped down version looks like this...
// Frame
JFrame frame = new JFrame();
frame.setBackground(new Color(0, 0, 0, 0)); // Setting frame to be transparent
// Components
JPanel panel = new JPanel();
//add stuff to panel...
panel.setOpaque(false);
Actually there's a bit more to it than setting the background color. You have to change the undecorated property to true. Here's a quick tutorial you can follow. Well explained.
https://www.youtube.com/watch?v=zecGJfNHPWo

prompting a user input for both rows and columns in my Checkerboard? (Java Programming)

I am trying to prompt a user input for my rows and columns for my checkerboard with a dialog box (J option something?)
// Displays an 8 by 8 grid of red and black rectangles
import javax.swing.*; // For JFrame and JPanel
import java.awt.*; // For Color, Container, and GridLayout
public class checkerboard{
public static void main(String[] args){
JFrame theGUI = new JFrame();
theGUI.setTitle("Checkerboard");
theGUI.setSize(300,300);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = theGUI.getContentPane();
pane.setLayout(new GridLayout(8,8));
Color color1 = Color.black;
Color color2 = Color.red;
for (int i = 1; i<= 64; i++){
JPanel panel = new JPanel();
// Alternate colors on a row
if (i % 2 == 0)
panel.setBackground(color1);
else
panel.setBackground(color2);
pane.add(panel);
// At the end of a row, start next row on the other color
if (i % 8 == 0){
Color temp = color1;
color1 = color2;
color2 = temp;
}
}
theGUI.setVisible(true);
}
}
Have you tried
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter number of columns"));

JList is showing duplicates

I am working on a small example using Java Swing where I want to draw a sine graph on one panel and the co-ordinates of the graph in another panel. So I created a class that extends the JFrame then I created the JPanel for graph and co-ordinates. For displaying co-ordinates I am using JList. Now the problem is the co-ordinates are showing duplicate values. Here is my code:
public class MyFrame extends JFrame {
JList list;
DecimalFormat df = new DecimalFormat("#.###");
DefaultListModel model = new DefaultListModel();
private JPanel contentPane;
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, 600, 600);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0)));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 2, 0, 0));
JPanel panel = new MyGraph();
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
contentPane.add(panel);
list = new JList(model);
list.setVisibleRowCount(4);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0)));
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
JLabel lblNewLabel_1 = new JLabel("X - Y");
panel_1.add(lblNewLabel_1);
JScrollPane slistScroller = new JScrollPane(list);
panel_1.add(slistScroller);
contentPane.add(panel_1);
}
class MyGraph extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int xBase = 10;
int top = 100;
int yScale = 10;
int xAxis = 360;
int yBase = top + yScale;
g.drawLine(xBase, top, xBase, top + 2 * yScale);
g.drawLine(xBase, yBase, xBase + xAxis, yBase);
g.setColor(Color.red);
int x2=0, y2=0;
int x1 = xBase + 0;
int y1 = yBase - (int) (10*Math.sin(0) * yScale);
int i;
for (i = 0; i < 10; i++) {
x2 = xBase + i;
y2 = yBase - (int) (10*Math.sin(i) * yScale);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
df = new DecimalFormat("#.###");
model.addElement(i +" -- " + df.format(10*Math.sin(i)));
}
model.addElement("------END----------");
}
}
}
Here is the output of my program:
As per my program, I have a for loop from angles 0 to 10 and I am adding the values to DefaultListModel model which is added to JList list.
Can someone please help me where I am doing mistake in this code?
Also even when I have this line list.setVisibleRowCount(4); , I was expecting only 4 records displayed to the user with a scroll-bar, but as per the output image it is not working like that.
paintComponent may be any number of times, for any number of reasons, try resizing the frame and see what happens.
Your paint method should focus on doing just that, painting.
You need to change the process so that the paintComponent becomes depend on the model, not the other way round.
Take a look at Painting in AWT and Swing for more details about painting in Swing.
You may also want to consider using a ListCellRender to render the data in the model in the JList, this way, you could more easily share the model and it's data.
See Writing a Custom Cell Renderer for more details

Categories