Reputation: 9
I have a problem with adding a JLabel to a JFrame. I use a JPanel as described in several tutorials, but the Label doesn't pop up in the Frame; the same problem with other swing components like JTextField, JButton etc.. Drawing lines, rectangles and so on does work. I hope someone knows, what kind of mistake I am making here:
package plot1;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Gui extends JFrame {
private JPanel contentPane;
public Gui(){
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
setSize(1200, 600);
setLayout(null);
setLocationRelativeTo(null);
setTitle("Plot");
addWindowListener(new WindowAdapter(){
public void windowClosed(WindowEvent evnt){
System.exit(0);
}
});
setResizable(false);
JLabel lblStanFunc = new JLabel("Die Funktionssyntax lautet:");
lblStanFunc.setBounds(800, 40, 300, 30);
lblStanFunc.setVisible(true);
add(lblStanFunc);
}
}
The main-method is in another class:
package plot1;
public class Main {
public static void main(String[] args){
new Gui().setVisible(true);;
}
}
The frame pops up as expected, but the JLabel is missing. Thanks for all helpful comments.
Upvotes: 0
Views: 3992
Reputation: 23
I can't reproduce it either. As sweeper mentioned, if your screen is not large enough, change the frame size to setSize(800, 600)
and label location to lblStanFunc.setBounds(300, 250, 300, 30)
. The label should be in the center of the screen.
Upvotes: 0
Reputation: 2224
Just Add setVisible(true)
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class GUI extends JFrame {
private JPanel contentPane;
public GUI(){
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
setSize(1200, 600);
setLayout(null);
setLocationRelativeTo(null);
setTitle("Plot");
addWindowListener(new WindowAdapter(){
public void windowClosed(WindowEvent evnt){
System.exit(0);
}
});
setResizable(false);
setVisible(true);
JLabel lblStanFunc = new JLabel("Die Funktionssyntax lautet:");
lblStanFunc.setBounds(800, 40, 300, 30);
lblStanFunc.setVisible(true);
add(lblStanFunc);
}
public static void main(String[] args) {
new GUI();
}
}
Upvotes: 3