I have this code bellow that is suppose to display some text but it don't and I can't find the reason why.
public class TestMLD extends JPanel{
TestMLD(){
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
new TestMLD();
}
}
Thanks in advance
The issue here is that you never actually add the JLabel helloLabel to your JPanel / TestMLD.
To do so, add this line of code at the end of your init() method:
add(helloLabel);
You also never actually set the layout you created to your panel
setLayout(flow);
Also, the second time you create a new TestMLD() object is redundant. You can omit that.
All together, the updated code should look something like this:
public class TestMLD extends JPanel {
TestMLD() {
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
setLayout(flow);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
add(helloLabel);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Related
For some reason, when I run this code, my JFrame comes up as blank. I have been trying online tutorials for maybe an hour now, and I'm wondering if I'm misunderstanding something.
Here is the code:
public class Application {
public static JFrame f;
public static JButton submit;
public static JTextField unscramblee;
public static String scrambledWord, possibleWords;
public static JLabel possibleWordsDisplay;
public static JPanel UI;
public static JScrollPane scrollPane;
Application() {
f = new JFrame("test");
f.setResizable(true);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
UI = new JPanel();
scrollPane = new JScrollPane(UI);
unscramblee = new JTextField("test");
unscramblee.setBounds(240, 200, 400, 50);
submit = new JButton("Submit");
submit.setBounds(240, 350, 400, 100);
possibleWordsDisplay = new JLabel("possibleWordsDisplay - this is a display for words that are possible");
possibleWordsDisplay.setBounds(240, 0, 200, 200);
scrollPane.add(unscramblee);
scrollPane.add(submit);
scrollPane.add(possibleWordsDisplay);
f.getContentPane().add(scrollPane);
f.pack();
f.setSize(1280,720);
}
}
I hope this is enough information to help. Thanks.
(If anyone is wondering why the setSize method comes after the pack method, it's because the JFrame keeps collapsing on itself when I run it. If you also know how to fix that please tell me! I'd be very thankful.)
Setting bound manually is not a viable practice.
Instead use the appropriate Layout Managers for the desired layout.
The following is mre1 (note the comments) :
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Application {
Application() {
JFrame f = new JFrame("test");
//f.setSize(1280,720); f.pack should automatically set the size
f.setResizable(true);
//f.setLayout(null); do not use null layout
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel UI = new JPanel(); // uses flowlayout by default
//UI.setBounds(0, 0, 1280, 720); do not set bounds. that the job of the layout manager
JTextField unscramblee = new JTextField("test", 10);
//unscramblee.setBounds(240, 200, 400, 50);
JButton submit = new JButton("Submit");
//submit.setBounds(240, 350, 400, 100);
JLabel possibleWordsDisplay = new JLabel("possibleWordsDisplay - this is a display for words that are possible");
//possibleWordsDisplay.setBounds(240, 0, 200, 200);
UI.add(unscramblee);
UI.add(submit);
UI.add(possibleWordsDisplay);
JScrollPane scrollPane = new JScrollPane(UI);
f.getContentPane().add(scrollPane); //uses borderlayout by default
f.pack();
f.setVisible(true); //make frame visible after construction is completed
}
public static void main(String[] args) {
new Application();
}
}
1 Always consider an mre when posting question or answers
When creating a GUI, consider following the below design to start:
private JFrame frame;
private JPanel contentPane;
public static void main(String[] args) {
GUI gui = new GUI();
gui.start();
}
private void start() {
frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
makeContent();
frame.setSize(500, 130);
frame.setVisible(true);
}
private void makeContent() {
contentPane = (JPanel) frame.getContentPane();
makePanel();
}
private void makePanel() {
JPanel ui = new JPanel();
ui.setLayout(new BoxLayout(ui, BoxLayout.Y_AXIS));
JLabel possibleWordsDisplay = new JLabel("possibleWordsDisplay - this is a display for words that are possible");
ui.add(possibleWordsDisplay);
JTextField unscramblee = new JTextField();
JScrollPane scroll = new JScrollPane(unscramblee);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ui.add(scroll);
JButton submit = new JButton("Submit");
ui.add(submit);
contentPane.add(ui, BorderLayout.CENTER);
}
Both of the below methods return gui reference types.
If I replace JFrame and JButton return types with void and remove return statements, it still works. I couldn't understand the difference between both approaches.
public class JavaGui {
JFrame frame;
JFrame createGui(){
GraphicsConfiguration g = null ;
frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
return frame;
}
JButton createButton(){
JButton button=new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
return button;
}
public static void main(String[] args){
JavaGui javaGui=new JavaGui();
javaGui.createGui();
javaGui.createButton();
}
}
createButton and createGui should create a button and the gui, and nothing else. While your code is creating them and adding the button to the frame and assigning the frame to the global variable.
Please see two different re-implementations:
public class JavaGui {
public static JFrame createGui(){
GraphicsConfiguration g = null ;
JFrame frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
return frame;
}
public static JButton getButton(){
JButton button=new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
return button;
}
public static void main(String[] args){
JavaGui.createGui().add(getButton());
}
}
or
public class JavaGui {
static JFrame frame;
static void createGui(){
GraphicsConfiguration g = null ;
frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
}
static void addButton(){
JButton button=new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
}
public static void main(String[] args){
JavaGui.createGui();
JavaGui.addButton();
}
}
You would use the first case (returning the objects JFrame and JButton) because you want to use them somewhere else.
You would use the second case when you want your methods to build the UI (working more like a state machine).
The methods do not need to return anything because the frame object is stored in their class. If it was in another class or in the main method, you would need return statements.
Your JFrame is accessible to both the methods and so you can just do everything within them but below is a nicer way to do it:
public class JavaGui {
JFrame frame;
public JavaGui() {
GraphicsConfiguration g = null;
frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
}
public void createButton(){
JButton button = new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
}
public static void main(String[] args) {
JavaGui gui = new JavaGui();
gui.createButton();
}
}
I have used cardlayout in my main class. I have added first panel in that cardlayout. I'm trying to hide the image in frame from first panel. So I have used interface like below code,
My Main class,
public class HomePage implements OptionMenuListener{
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Already there
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(20, 20));
File file = new File(jsonFilePath);
if(!file.exists()) {
LoginPage login = new LoginPage();
contentPane.add(login, Constants.CARD_LOGIN);
ConfigueBranch configureBranch = new ConfigueBranch(false);
contentPane.add(configureBranch, Constants.CARD_CONFIGURE_BRANCH);
ConfigureSystem configureSystem = new ConfigureSystem(false);
contentPane.add(configureSystem, Constants.CARD_CONFIGURE_SYSTEM);
ConfigureCustomer configureCustomer = new ConfigureCustomer(false);
contentPane.add(configureCustomer, Constants.CARD_CONFIGURE_CUSTOMER);
}
MainPage mainPage = new MainPage(HomePage.this);
contentPane.add(mainPage, Constants.CARD_MAINPAGE);
// SettingsPage configureExpinContainer = new SettingsPage();
// contentPane.add(configureExpinContainer, Constants.CARD_SETTINGS_PAGE);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(new EmptyBorder(50, 10, 10, 10));
Image image = MyUtil.loadImage("/logo.png"); // transform it
Image newimg = image.getScaledInstance(244, 80, java.awt.Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(newimg); // transform it back
JLabel label = new JLabel("", icon, JLabel.LEFT);
label.setFont(new java.awt.Font("Arial", Font.BOLD, 24));
label.setOpaque(true);
label.setForeground(Color.BLACK);
label.setBounds(0, 60, 300, 200);
buttonPanel.add(label);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(1000, 700);
centeredFrame(frame);
frame.setVisible(true);
frame.setResizable(false);
}
public static void centeredFrame(javax.swing.JFrame objFrame) {
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void onMenuSelect(boolean isShow) {
}
}
I'm using for interface to provide communication to frame from panel,
public interface OptionMenuListener {
void onMenuSelect(boolean isShow);
}
I'm using the below panel in cardlayout,
public class MainPage extends JPanel{
JButton inputOutputFilesBtn, syncBtn, tsBtn, settingsBtn;
public MainPage(HomePage homePage){
homePage.onMenuSelect(true);
init();
}
public void init(){
JTabbedPane jtbExample = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("No device connected");
jtbExample.addTab("Input and Output Files", jplInnerPanel1);
jtbExample.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("No device connected");
jtbExample.addTab("Sync", jplInnerPanel2);
JPanel jplInnerPanel3;
if(configuredSystem.equalsIgnoreCase("Expeditors")) {
jplInnerPanel3 = createInnerPanel("No device connected");
jtbExample.addTab("TS", jplInnerPanel3);
}
JPanel jplInnerPanel4 = new SettingsPage();
jtbExample.addTab("Settings", jplInnerPanel4);
JPanel jplInnerPanel5 = new LogoutPage();
jtbExample.addTab("Logout", jplInnerPanel5);
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(620, 400));
this.add(jtbExample, BorderLayout.CENTER);
add(jtbExample);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
But i'm getting Cannot use this in a static context error in this below line
MainPage mainPage = new MainPage(HomePage.this);
Now i want to send some information from panel to the frame which have cardlayout. Could you please suggest me an idea to do this? Thanks in advance.
You can't use this in a static context like since this represent the class instance that is executing a method. Here, you are in a static context, so you don't have an instance.
private static void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}
You either need to declare a variable
private static void createAndShowGUI() {
HomePage homePage = /*initialize or get it from somewhere */
MainPage mainPage = new MainPage(homePage);
}
Or move that logic outside the static context
private void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}
public static void main(String[] args) throws IOException {
//cevir("ornek3.txt");
JFrame frame=new JFrame("Print");
JPanel input=new JPanel();
JPanel output=new JPanel(); output.setBackground(Color.black);
final JTextArea ita = new JTextArea(30, 40);
JScrollPane ijp = new JScrollPane(ita);
JTextArea ota = new JTextArea(30, 40);
JScrollPane ojp = new JScrollPane(ota);
JButton buton=new JButton("Print");
frame.setLayout(new FlowLayout());
buton.setSize(50, 20);
input.setBounds(0,0,500, 500);
output.setBounds(500, 0, 500, 450);
frame.setBounds(100, 50, 1000, 500);
input.add(ijp, BorderLayout.CENTER);
output.add(ojp, BorderLayout.EAST);
input.add(buton, BorderLayout.SOUTH);
frame.add(input);
frame.add(output);
buton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"));
System.out.println(line);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This is my code and i want to get the text that i wrote while the program running and print it to the console. Is it possible with JtextArea. This code prints null when i clicked the button to the console even if i write something to the textarea.
You have use the JtextArea#append method.
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"))
ota.append(line);
}
Also variables used inside the methods inner class should be final, so make ota as final
final JTextArea ota = new JTextArea(30, 40);
I have simple problem as I am not much familiar with Java GUI. I am trying to make visible the JLable on the below code as I find it hard to understand the concept. But still label is not visible but the frame do open on run time.
public class Sample extends JPanel {
public void Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Sample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
You are forgot to add panel p to sample. Either use add(p) at the end or just remove panel p cause your sample class is extending JPanel.
Option 1:
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
add(p);
option 2:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1 = new JLabel("add JLabel"));
Also why are you overriding initialization of JLabel? In your code JLable will always hold value "add JLabel". If you want to see "User Name" then use this add(lab1); instead of add(lab1 = new JLabel("add JLabel"));.
May be you just require this:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1);
Also constructor can not have return type so remove void from your constructor.
The constructor that you are using is not a proper constructor .. A java constructor does not have a return type and the void is extra. When in the main method you are calling new Sample() it is not actually calling your method but the default constructor that exists by default.
Try like this ..
public Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
also you need to do what #Harry Joy suggested to add the add(p); statement otherwise the panel is still not added.
Note the comments.
import java.awt.*;
import javax.swing.*;
public class Sample extends JPanel {
public Sample() {
// set the layout in the constructor
super(new FlowLayout(FlowLayout.LEADING));
// best not to set size OR preferred size!
setPreferredSize( new Dimension(200,200) );
JLabel lab1 = new JLabel("User Name");
add(lab1);
}
public static void main(String[] args) {
// construct the GUI on the EDT
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("User Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Sample());
// important!
frame.pack();
frame.setVisible(true);
}
});
}
}
Note also, that it is generally not considered a good idea to extend a component unless adding custom functionality. That would mean (for example) defining new methods for the Sample panel (Which might better be labelled a UserDetails or UserDetailsContainer if I guess correctly where you are going with that code..). Or it might be a Login component..
Sample is the Jpanel.
Sample extends JPanel means you inherit from JPanel.
just drop JPanel p and all your "p."s
#SuppressWarnings("serial")
public class MyGui extends JFrame{
private MyContentPane myContentPane = new MyContentPane();
public MyGui(){
super("title");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(myContentPane);
this.createMenu();
this.pack();
this.setVisible(true);
}
private void createMenu(){
JMenuBar myMenuBar = new JMenuBar();
JMenu xMenu = new JMenu("x");
JMenu x = new JMenu("x");
JMenuItem xItem = new JMenuItem("letter");
JMenuItem exitItem = new JMenuItem("exit");
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.xPanel();
}
});
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.setxPanel();
}
});
exitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
displayMenu.add(letterItem);
displayMenu.add(colorItem);
fileMenu.add(exitItem);
myMenuBar.add(displayMenu);
myMenuBar.add(fileMenu);
this.setJMenuBar(myMenuBar);
}
}