I have this part of my code. I have a JLabel and a JButton that are in a panel. The I place that panel into another panel that has a border layout and I set the panel containing the label and button to be "NORTH", but the JLabel does not show. When I romove the button it does. Why? How can I fix this? Thanks. Here is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class ISU implements ActionListener{

	JFrame mainFrame;
	JLabel descriptionLabel;
	public JLabel pictureLabel;
	JButton launchApplication;
	public ISU (){
		mainFrame = new JFrame ("Physics ISU Library");
		JPanel mainPane = new JPanel ();
		JPanel descriptPane = new JPanel ();
		JPanel picPane = new JPanel ();
		
		pictureLabel = new JLabel ();
		
		JMenuBar menuBar = new JMenuBar ();
		JMenu motionItem = new JMenu ("Motion");
		
		JMenu energyItem = new JMenu ("Energy");
		
		JMenu soundItem = new JMenu ("Sound");
		JMenuItem transverseWave = new JMenuItem ("Transverse Wave"); transverseWave.setActionCommand("transverseWave");transverseWave.addActionListener(this);
		JMenuItem longitudinalWave = new JMenuItem ("Longitudinal Wave"); longitudinalWave.setActionCommand("longitudinalWave"); longitudinalWave.addActionListener (this);
		JMenuItem dopplerEffect = new JMenuItem ("Doppler Effect"); dopplerEffect.setActionCommand("dopplerEffect"); dopplerEffect.addActionListener(this);
		
		JMenu electricityItem = new JMenu ("Electricity");
		
		JMenu magnetismItem = new JMenu ("Magnetism");
		
		
		soundItem.add(transverseWave); soundItem.add(longitudinalWave); soundItem.add(dopplerEffect);
		
		menuBar.add(motionItem); menuBar.add(energyItem); menuBar.add(soundItem); menuBar.add(electricityItem); menuBar.add(magnetismItem);
		mainFrame.add("North",menuBar);
		
		descriptPane.setLayout (new BorderLayout ());
		
		
		descriptionLabel = new JLabel ("This is the program that demonstrates how a blank works.");
		
		launchApplication = new JButton ("Launch");
		
		descriptPane.add(descriptionLabel);
		descriptPane.add (launchApplication);
		
		mainPane.setLayout(new BorderLayout ());
		mainPane.add (descriptPane, BorderLayout.NORTH);
		
		mainPane.add(picPane, BorderLayout.CENTER);
		
		mainFrame.add (mainPane);
		
		mainFrame.setSize (600,500);
		mainFrame.setVisible(true);
	}
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ISU isu = new ISU ();
	}
}

Dani AI

Generated

A concise diagnosis and practical fixes for the two issues in this thread.

The JLabel problem

  • Root cause: descriptPane had a BorderLayout and both components were added without constraints, so each add(component) defaults to BorderLayout.CENTER and the last added component replaces the earlier one. That explains why removing the button made the label appear.
  • What fixed it: ’s FlowLayout wrapper is a simple, correct fix. Other valid options: add the components with explicit BorderLayout constraints (for example put the label WEST and the button EAST), or nest a small panel (FlowLayout or BoxLayout) inside the NORTH region. Also prefer mainFrame.setJMenuBar(menuBar) for menus, call mainFrame.pack() (or setPreferredSize) before setVisible(true), set mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), and build the GUI on the EDT (use SwingUtilities.invokeLater).

The sine-wave drawing

  • Three bugs to fix: Math.sin expects radians (so convert degrees with Math.toRadians or compute angle in radians), the method public void TransverseWave() is not a constructor for TransverseWaveProgram and may never be invoked, and calling fillPolygon(...) inside a loop draws the same polygon repeatedly instead of a connected curve.
  • A robust approach: sample one x per pixel across the panel, compute an angle = 2PIcycles(x/(width-1)), compute y = centerY - sin(angle)amplitude, then draw a single polyline (or Path2D). Example:
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int w = getWidth(), h = getHeight();
    int[] xs = new int[w], ys = new int[w];
    int centerY = h/2, amp = Math.min(h/2 - 4, 100);
    int cycles = 1;
    for (int x = 0; x < w; x++) {
        double angle = (2 * Math.PI * cycles * x) / (double)(w - 1);
        xs[x] = x;
        ys[x] = centerY - (int)(Math.sin(angle) * amp);
    }
    g2.drawPolyline(xs, ys, w);
    g2.dispose();
}

Flicker / flashing

  • Common causes: calling repaint() from inside painting code, doing heavy computation during paintComponent, or updating UI off the EDT. Fixes: precompute coordinates (or compute them in response to a Swing Timer), avoid repaint() inside the paint method, rely on JPanel’s double buffering, and use a Swing Timer for animation updates. These steps address the glitches seen after fixing the radians/array issues.

Tying threads together: was correct about radians and ’s advice to subdivide the period and connect points is the right rendering strategy — implement it with the single-polyline approach above and the drawing will be stable and stretch to any panel width.

Recommended Answers

All 7 Replies

Member Avatar for Member #647493

Try...

JPanel Top_Panel = new JPanel (new FlowLayout ());
Top_Panel.add (descriptionLabel);
Top_Panel.add (launchApplication);
descriptPane.add (Top_Panel, BorderLayout.NORTH);
commented: very good ++ +8

Thanks. I realized that I had the border layout code still added to the top pane. Thanks for your help.

I am having trouble printing a sine wave (transverse wave) a wave that kind of looks like this ~

except wounded. you can just goolge it here i will do it for you. here


that is what it is supposed to look like. One cycle, but my program gives me more and I dont know why. Thanks for the help

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class TransverseWaveProgram extends JPanel implements ActionListener{

		
		int [] xaxis = new int [360];
		int [] yaxis = new int [360];
	
		public void TransverseWave (){
			for (int i = 0; i < 360; i++){
				xaxis[i] = i;
				yaxis[i] = ((int)(Math.round( (Math.sin(i) * - 1) * 100)));
				yaxis[i] = yaxis[i] + 300;
			}
			
			repaint();
			
		}
		
		
		
		
		
		public void paintComponent (Graphics g){
			super.paintComponent (g);
			
			for (int i = 0; i < 360; i++){
				
				g.fillPolygon (xaxis,yaxis, 360);
				
			}
			
			
		}

		
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		
		
		
	
}

if you are wondering this is the basic equation

y = sinx

again. Thanks for the help.

Math.sin function wants the angle in radians, not degrees.

360 degrees would be 2*pi radians.

ok thanks. I didn't know it was radians

is there an easier way to graph it? I need it to stretch over a normal distance. Ho would I accomplish this? is there a graphing option that uses mathematical terms to graph a function at a certain point and allows you to vary it throughout the program? Also sometimes when I use my code it glitches and it flashes the drawing and then disappears. What could be the cause of this? Thanks.

You just need to subdivide the period of your function over a certain number of pixels and build a Path2D from the (x,y) value pairs.

Here are some fragments of pseudocode to get you started:

periodValueOfPixel = x/graphWidth*periodOfFunction

Looping over an x range you calc

y = Math.sin(periodValueOfPixel)*graphHeight

and connect your path to the next point

path.lineTo(x,y)

When your path is complete use Graphics2D.draw(Shape) to render it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.