I'm trying to add various JButtons to a JPanel using "for" but doesn't work. No compilation or other errors. Buttons just won't appear.
A bit of context, I create an ArryList in another class ("GestorFrigo") that gets data from DataBase, this works fine, the array has all the data and there's no problem getting back the data from the array.
This is my code: Thanks in advance.
import gestor.GestorFrigo;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollBar;
#SuppressWarnings("serial")
public class VentanaInterior extends JFrame {
private JPanel contentPane;
private JButton btnPerfiles;
private JButton btnAadir;
private JButton btnRecetas;
private JScrollBar scrollBar;
private GestorFrigo frigo;
private ArrayList<JButton> botones;
private ArrayList<Object> boton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VentanaInterior frame = new VentanaInterior();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VentanaInterior() {
//Componentes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 556, 363);
setLocationRelativeTo(null);
setTitle("Tu FrigorÃfico Inteligente");
setIconImage(new ImageIcon(getClass().getResource("img/logo.png")).getImage());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnPerfiles = new JButton("Perfiles");
btnPerfiles.setBounds(0, 302, 96, 23);
contentPane.add(btnPerfiles);
btnAadir = new JButton("A\u00F1adir alimento");
btnAadir.setBounds(369, 302, 148, 23);
contentPane.add(btnAadir);
btnRecetas = new JButton("Recetas");
btnRecetas.setBounds(96, 302, 103, 23);
contentPane.add(btnRecetas);
scrollBar = new JScrollBar();
scrollBar.setBounds(523, 0, 17, 325);
contentPane.add(scrollBar);
JButton btnQueso = new JButton();
btnQueso.setBounds(24, 35, 62, 61);
contentPane.add(btnQueso);
frigo = new GestorFrigo(); //creamos el gestor
String imagen = frigo.getArray().get(1).getImagen(); //cogemos la imagen asociada al alimento
btnQueso.setIcon(new ImageIcon("src/img/"+imagen));
for(int i=0;i<frigo.getArray().size();i++){
JButton boton = new JButton();
String imagen2 = frigo.getArray().get(i).getImagen();
boton.setIcon(new ImageIcon("src/img/"+imagen2));
contentPane.add(boton);
}
}
}
Don't use a null layout.
By default your buttons have a default size of (0, 0) so there is nothing to paint.
User a layout manager, probably a GridLayout, and the layout manager will determine the size and location of each button for you.
Read the section from the Swing tutorial o Using Layout Managers for more information and working examples.
Related
I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
I tried to add a button to the JFrame, but it won't appear for some reason. How do I make it appear?
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.*;
public class GraficoconArreglo extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
JLabel []lab = new JLabel[6];
JTextField []text = new JTextField[6];
Border border = BorderFactory.createLineBorder(Color.pink,1);
JButton b = new JButton("Calculate");
public GraficoconArreglo() {
initComponents();
pan.setLayout(null);
pan.setBackground(Color.GRAY);
for(int i=0; i<lab.length ;i++){
lab[i] = new JLabel();
text[i] = new JTextField();
lab[i].setBounds(new Rectangle(15,(i+1)*40, 60, 25));
lab[i].setText("Data " + (i+1));
lab[i].setBorder(border);
text[i].setBounds(new Rectangle(100,(i+1)*40, 60, 25));
pan.add(lab[i],null);
pan.add(text[i],null);
setSize(200,330);
setTitle("Arrays in forums.");
add(b);
b.addActionListener((ActionListener) this);
}
}
You are creating only one button and adding it to 6 different places. Therefore, you only would see it on the last place you added.
You should add the button to the contentPane, not the JFrame. A working code for this, provided from SwingDesigner from Eclipse Marketplace would be:
public class Window extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(170, 110, 89, 23);
contentPane.add(btnNewButton);
}
}
I am trying to code a program with multiple screens, however, I do not want to use tabbed panes. I have looked at using multiple JPanels with the card layout and the methods are simply not working. What I need to be able to do is load the new JPanel when a button is clicked. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IA extends JFrame {
private JPanel contentPane;
private JPanel home;
private JPanel clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
The problem is that you have duplicate variables home and clients .
The folllowing is your modified code to fix that, with comments on the changed lines (five lines total) :
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class IA extends JFrame {
private final JPanel contentPane;
// private final JPanel home; // REMOVED
// private JPanel clients; // REMOVED
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
final JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
final JPanel clients = new JPanel(); // MOVED UP
contentPane.add(clients, "name_714431450350356"); // MOVED UP
clients.setLayout(null); // MOVED UP
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
I would take a look at this post, however I have a feeling you'll need to use a actionlistener to get this done...
Java Swing. Opening a new JPanel from a JButton and making the buttons pretty
I would of left this as a comment but apparently you need 50 rep for that...
This link might be more helpful.. How to open a new window by clicking a button
When the following code is invoked the clients variable equals to null.
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
Write this:
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
before you add the Action Listener
I have a JTextArea wrapped in a JScrollPane, which I use to log my application's output.
As the application produces many lines, the number of lines in the text area is growing really fast and the scroll becomes nearly invisible.
I'd like to have a text area like the Eclipse console.. I mean.. a text area with a vertical scroll but when using the scroll I can only show at maximum the latest 200 rows.
Here is the runnable code I'm using:
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
public class WindowLog extends JFrame {;
private JPanel contentPane;
private static JTextArea textArea = new JTextArea();
public static void run() {
try {
WindowLog frame = new WindowLog();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeText(JTextArea ta, String s){
DefaultCaret caret = (DefaultCaret)ta.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
ta.append(s);
}
/**
* Create the panel.
*/
public WindowLog() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 523, 299);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.setLayout(null);
JLabel lblLog = new JLabel("Log");
lblLog.setBounds(5, 5, 497, 14);
getContentPane().add(lblLog);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 30, 492, 138);
//scrollPane.getViewport().setPreferredSize(new Dimension(300, 100));
textArea.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
contentPane.add(scrollPane);
scrollPane.setViewportView(textArea);
Main.setTextProva(textArea);
}
}
and here is Main class:
public class Main {
static JTextArea textProva;
public static void setTextProva(JTextArea textProva) {
Main.textProva = textProva;
}
public static void main(String[] args) {
WindowLog.run();
System.out.println(textProva);
WindowLog.writeText(textProva, "hello"+"\n");
}
Thanks in advance.
Add a DocumentFilter to the document of the text area. In the filter check how many rows are there. If the max count is achieved remove previous content from the text area.
You can use
txt.setRows(int rows);
txt.setColumns(int cols)
by this you can control horizontal, vertical size.
or further reference you can read Oracle documentation
I'm getting a NullPointerException error at line 77 lblNewLabel.setVisible(false);
which is called from line 65 runTest(); in the following code. (This is a dummy project I wrote to simulate a problem I'm having in a larger project). What I'm trying to do is change the attribute of several fields, buttons, etc based on user action at various places in the project. I would like to group all the changes in a separate method that can be called from various other methods. I'm still a Java novice, having come from some Visual Basic and Pascal experience. Seems like what I'm trying to do should be straight forward, but for now, I'm at a loss. Thanks in advance for your suggestions.
package woodruff;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class MyTest extends JFrame {
private JPanel contentPane;
private JTextField txtHasFocus;
private JLabel lblNewLabel;
/**
* Create the frame.
*/
public MyTest() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 237, 161);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("This is a label.");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel.setBounds(10, 25, 202, 14);
contentPane.add(lblNewLabel);
JButton btnShow = new JButton("Show");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setVisible(true);
}
});
btnShow.setBounds(10, 50, 89, 23);
contentPane.add(btnShow);
JButton btnHide = new JButton("Hide");
btnHide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel.setVisible(false);
}
});
btnHide.setBounds(123, 50, 89, 23);
contentPane.add(btnHide);
txtHasFocus = new JTextField();
txtHasFocus.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
// Following results in NullPointerException error
// at woodruff.MyTest.runTest(MyTest.java:77)
runTest();
}
});
txtHasFocus.setHorizontalAlignment(SwingConstants.CENTER);
txtHasFocus.setText("Has Focus?");
txtHasFocus.setBounds(67, 92, 86, 20);
contentPane.add(txtHasFocus);
txtHasFocus.setColumns(10);
}
private void runTest() {
lblNewLabel.setVisible(false);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyTest frame = new MyTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the initialize() method, you have created a local variable for JLabel, and hence are not initializing the instance field, as a reason it remains initialized to null, and hence NPE.
final JLabel lblNewLabel = new JLabel("This is a label.");
change the above line to: -
lblNewLabel = new JLabel("This is a label.");