I'm trying to build a dynamic log window (basically a auto-scrolling jtext-area).
The problem I'm having is that although I'm printing 500 lines in the text area, it displays as below:
Below you have my code:
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
public class Main {
private static JFrame mainFrame;
public static void main(String args[]) {
mainFrame = new JFrame();
mainFrame.setSize(500, 500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ControlPanel cp = new ControlPanel();
mainFrame.add(cp);
mainFrame.setVisible(true);
}
}
class ControlPanel extends JPanel {
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
actionLog.setPreferredSize(new Dimension(500, 300));
actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
pointsLog.setPreferredSize(new Dimension(500, 300));
pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for(int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Hopefully someone with a bit more Swing experience can take the time to point me the right way with this.
Never do this:
actionLog.setPreferredSize(new Dimension(500, 300));
Since by doing this you artificially restrict the size of the JTextArea causing the effect that is currently vexing you. Note also that it's generally a good idea to avoid setting preferred sizes on anything.
Instead set the column and row counts of the JTextARea. This can be done via setter methods or via a simple constructor call: JTextArea myTextArea = new JTextArea(rows, columns);
As an aside: I wonder if a JList will work better for you.
MCVE Example:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class Main2 {
private static void createAndShowGUI() {
JPanel mainPanel = new ControlPanel();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class ControlPanel extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LOG_COLS = 40;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
// !! actionLog.setPreferredSize(new Dimension(500, 300));
// !! actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setRows(LOG_ROWS); // !!
actionLog.setColumns(LOG_COLS); // !!
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// !! pointsLog.setPreferredSize(new Dimension(500, 300));
// !! pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setRows(LOG_ROWS); // !!
pointsLog.setColumns(LOG_COLS); // !!
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Edit
Example with nested layouts and JLists:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Main2B {
private static void createAndShowGUI() {
ControlPanel2B controlPanel = new ControlPanel2B();
controlPanel.setBorder(BorderFactory.createEtchedBorder());
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.add(controlPanel, gbc);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
#SuppressWarnings("serial")
class ControlPanel2B extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LIST_WIDTH = 500;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private DefaultListModel<String> actionLogListModel = new DefaultListModel<>();
private JList<String> actionLogList = new JList<String>(actionLogListModel);
private DefaultListModel<String> pointsLogListModel = new DefaultListModel<>();
private JList<String> pointsLogList = new JList<String>(pointsLogListModel);
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel2B() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
actionLogList.setVisibleRowCount(LOG_ROWS);
pointsLogList.setVisibleRowCount(LOG_ROWS);
actionLogList.setFixedCellWidth(LIST_WIDTH);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
pointsScroll = new JScrollPane(pointsLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLogListModel.addElement("Line: " + i);
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Related
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}
I'm having a problem with a JFrame not showing a JTable that is added to it. I've tried getContentPane().add(..), I've switched to just add to keep the code a little shorter. Any help is more than appreciated!
package com.embah.Accgui;
import java.awt.*;
import javax.swing.*;
public class accCreator extends JFrame {
private String[] columnNames = {"Username", "Password", "Members", "World"};
private Object[][] data = {{"b", "b", "b", "b"},
{ "e", "e", "e", "e"}};
private JTable tbl_Accounts;
private JScrollPane scrollPane;
private JLabel lbl_Account = new JLabel();
private JLabel lbl_Username = new JLabel();
private JLabel lbl_Password = new JLabel();
private JLabel lbl_Homeworld = new JLabel();
private JButton btn_Select = new JButton();
private JButton btn_Addacc = new JButton();
private JButton btn_Delacc = new JButton();
private JTextArea txt_Username = new JTextArea();
private JTextArea txt_Password = new JTextArea();
private JTextArea txt_Homeworld = new JTextArea();
private JCheckBox cbox_Members = new JCheckBox();
private JCheckBox cbox_RanWrld = new JCheckBox();
public accCreator() {
setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI() {
tbl_Accounts = new JTable(data, columnNames);
tbl_Accounts.setLocation(5, 30);
tbl_Accounts.setPreferredScrollableViewportSize(new Dimension(420, 250));
tbl_Accounts.setFillsViewportHeight(true);
tbl_Accounts.setVisible(true);
add(tbl_Accounts);
scrollPane = new JScrollPane(tbl_Accounts);
add(scrollPane);
lbl_Account.setLocation(4, 5);
lbl_Account.setSize(100, 20);
lbl_Account.setText("Select Account:");
add(lbl_Account);
lbl_Username.setLocation(5, 285);
lbl_Username.setSize(70, 20);
lbl_Username.setText("Username:");
add(lbl_Username);
lbl_Password.setLocation(5, 310);
lbl_Password.setSize(70, 20);
lbl_Password.setText("Password:");
add(lbl_Password);
lbl_Homeworld.setLocation(310, 310);
lbl_Homeworld.setSize(80, 20);
lbl_Homeworld.setText("Home World:");
add(lbl_Homeworld);
btn_Select.setLocation(305, 5);
btn_Select.setSize(120, 20);
btn_Select.setText("Select Account");
add(btn_Select);
btn_Addacc.setLocation(300, 285);
btn_Addacc.setSize(60, 20);
btn_Addacc.setText("Add");
btn_Addacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String worldSel = "";
if(cbox_RanWrld.isSelected()){
worldSel = "Random";
} else {
worldSel = txt_Homeworld.getText();
}
Object[] row = {txt_Username.getText(), txt_Password.getText(), cbox_Members.isSelected(), worldSel};
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
model.addRow(row);
}
});
add(btn_Addacc);
btn_Delacc.setLocation(365, 285);
btn_Delacc.setSize(60, 20);
btn_Delacc.setText("Del");
btn_Delacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
}
});
add(btn_Delacc);
txt_Username.setLocation(80, 285);
txt_Username.setSize(100, 20);
txt_Username.setText("");
txt_Username.setRows(5);
txt_Username.setColumns(5);
add(txt_Username);
txt_Password.setLocation(80, 310);
txt_Password.setSize(100, 20);
txt_Password.setText("");
txt_Password.setRows(5);
txt_Password.setColumns(5);
txt_Password.setTabSize(0);
add(txt_Password);
txt_Homeworld.setLocation(395, 310);
txt_Homeworld.setSize(30, 20);
txt_Homeworld.setText("82");
txt_Homeworld.setRows(5);
txt_Homeworld.setColumns(5);
txt_Homeworld.setTabSize(0);
add(txt_Homeworld);
cbox_Members.setLocation(185, 285);
cbox_Members.setSize(80, 20);
cbox_Members.setText("Members");
cbox_Members.setSelected(false);
add(cbox_Members);
cbox_RanWrld.setLocation(185, 310);
cbox_RanWrld.setSize(115, 20);
cbox_RanWrld.setText("Random World");
cbox_RanWrld.setSelected(false);
add(cbox_RanWrld);
setTitle("Account Manager");
setSize(440, 370);
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new accCreator();
}
}
I know thats not the problem tho because everything else shows up just fine
Oh... really? Not in my computer...
Let's have a picture of your actual GUI shown in my PC:
Does the GUI looks the same in your computer? I bet no.
But... why does it looks like that in my PC?
Well, as stated above in the comments by #MadProgrammer this is because of the setLayout(null); line. You might want to read Why is it frowned upon to use a null layout in Java Swing? for more information.
Now, that being said, you should also want to read and learn how to use the various layout managers that will let you create complex GUIs.
In your code you never set the location / bounds for scrollPane, and the size of it, so the component has a default size of 0, 0.
But... I think it's better to show you how you can get a really similar GUI (I'm in a hurry so I didn't make an even more similar GUI). You can copy-paste my code and see the same output (with slight differences because of the OS maybe) but text won't be cropped.
The code that produces the above image is this one:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AccountCreator {
private JFrame frame;
private JPanel mainPane;
private JPanel topPane;
private JPanel tablePane;
private JPanel bottomPane;
private JLabel selectAccountLabel;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel homeWorldLabel;
private JTextField userNameField;
private JTextField homeWorldField;
private JPasswordField passwordField;
private JCheckBox membersBox;
private JCheckBox randomBox;
private JButton selectAccountButton;
private JButton addButton;
private JButton deleteButton;
private JTable table;
private JScrollPane scroll;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AccountCreator().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
int rows = 30;
int cols = 3;
String[][] data = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = i + "-" + j;
}
}
String[] columnNames = { "Column1", "Column2", "Column3" };
table = new JTable(data, columnNames);
scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(new Dimension(420, 250));
table.setFillsViewportHeight(true);
selectAccountLabel = new JLabel("Select Account");
userNameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
homeWorldLabel = new JLabel("Home world");
selectAccountButton = new JButton("Select Account");
addButton = new JButton("Add");
deleteButton = new JButton("Del");
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
homeWorldField = new JTextField(3);
membersBox = new JCheckBox("Members");
randomBox = new JCheckBox("Random world");
topPane = new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(selectAccountLabel, BorderLayout.WEST);
topPane.add(selectAccountButton, BorderLayout.EAST);
tablePane = new JPanel();
tablePane.add(scroll);
bottomPane = new JPanel();
bottomPane.setLayout(new GridLayout(0, 5, 3, 3));
bottomPane.add(userNameLabel);
bottomPane.add(userNameField);
bottomPane.add(membersBox);
bottomPane.add(addButton);
bottomPane.add(deleteButton);
bottomPane.add(passwordLabel);
bottomPane.add(passwordField);
bottomPane.add(randomBox);
bottomPane.add(homeWorldLabel);
bottomPane.add(homeWorldField);
mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
frame.add(topPane, BorderLayout.NORTH);
frame.add(tablePane, BorderLayout.CENTER);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also, you might have noticed that the main() method is different, well, the code inside it is placing the program on the Event Dispatch Thread (EDT).
So, be sure to include it in your future programs
As you can see from the image above some of the text is being cut off :(
Code:
package malgm.school.clockui.ui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import malgm.school.clockui.ClockUI;
import malgm.school.clockui.ResourceLoader;
public class ClockFrame extends JFrame {
private static final long serialVersionUID = 1L;
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 200;
public ClockFrame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
}
public void relocalize() {
//Wipe controls
this.getContentPane().removeAll();
this.setLayout(null);
initComponents();
}
#SuppressWarnings("unused")
private void initComponents() {
setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
speakButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec(ClockUI.dir + "/SpeakingClock.exe");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
FONT: http://www.dafont.com/digital-7.font
Any help will be greatly appreciated
A key to success with Swing layouts is to avoid setLayout(null) and to pack() the enclosing Window. This lets the contained components adopt their preferred sizes, as shown below. To avoid this pitfall, don't invoke setResizable(false).
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/23551260/230513 */
public class ClockFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ClockFrame cf = new ClockFrame();
}
});
}
public ClockFrame() {
setTitle("Clock");
setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
#SuppressWarnings("unused")
private void initComponents() {
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
JLabel time = new JLabel("00:00");
time.setFont(time.getFont().deriveFont(72f));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
After
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
Add time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
After it will look like:
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
change your constructor definition to (EDITED)
public Frame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
setSize(850, 650);
setLocationRelativeTo(null);
setVisible(true);
}
I'm having trouble getting a JPanel inside a BorderLayout to work.
I defined the layout of the Panel as a Grid Layout, and then added a bunch of buttons I had made before hand to the JPanel. However, when I run the program, the JFrame loads but nothing within the frame loads. Here's the code:
import java.awt.*;
import javax.swing.*;
public class Phone extends JFrame {
private JTextField PhoneText;
private JPanel ButtonPanel;
private JButton bttn1;
private JButton bttn2;
private JButton bttn3;
private JButton bttn4;
private JButton bttn5;
private JButton bttn6;
private JButton bttn7;
private JButton bttn8;
private JButton bttn9;
private JButton bttn10;
private JButton bttn11;
private JButton bttn12;
public Phone(){
setTitle("Phone - Agustin Ferreira");
Container ContentPane = getContentPane();
ContentPane.setLayout(new BorderLayout());
setSize(300, 400);
setVisible(true);
setBackground(Color.DARK_GRAY);
PhoneText = new JTextField("(317)188-8566");
bttn1 = new JButton ("1");
bttn2 = new JButton ("2");
bttn3 = new JButton ("3");
bttn4 = new JButton ("4");
bttn5 = new JButton ("5");
bttn6 = new JButton ("6");
bttn7 = new JButton ("7");
bttn8 = new JButton ("8");
bttn9 = new JButton ("9");
bttn10 = new JButton ("*");
bttn11 = new JButton ("0");
bttn12 = new JButton ("#");
ButtonPanel = new JPanel(new GridLayout(4,3,0,0));
ButtonPanel.add(bttn1);
ButtonPanel.add(bttn2);
ButtonPanel.add(bttn3);
ButtonPanel.add(bttn4);
ButtonPanel.add(bttn5);
ButtonPanel.add(bttn6);
ButtonPanel.add(bttn7);
ButtonPanel.add(bttn8);
ButtonPanel.add(bttn9);
ButtonPanel.add(bttn10);
ButtonPanel.add(bttn11);
ButtonPanel.add(bttn12);
ContentPane.add(PhoneText, BorderLayout.NORTH);
ContentPane.add(ButtonPanel, BorderLayout.CENTER);
}
}
Additionally, I have another class that calls the Phone class. Here's the code for that, just in case:
package ProgrammingAssignment11;
import javax.swing.JFrame;
public class GUI_Driver {
public static void main(String[] args) {
Phone Nokia;
Nokia = new Phone();
Nokia.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
Any Help?
Much appreciated, M3tal T1ger
Your main problem:
You should only call setVisible(true) after adding components to your GUI. You don't do this and so the GUI gets drawn without its components.
Also:
You should avoid setting the sizes or preferred sizes of anything. Instead let the components and layout managers size themselves.
And don't forget to call pack() after adding all components and before making the GUI visible.
Learn and follow Java naming conventions, including giving all variables and methods names that begin with a lower case letter, and all classes with names that start with an upper-case letter.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Phone2 extends JPanel {
private static final String[][] BTN_TEXTS = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"*", "0", "#"}
};
private static final float BTN_POINTS = 48f;
private static final float TEXT_POINTS = 24f;
private static final int DISPLAY_COLUMNS = 12;
private JButton[][] buttons = new JButton[BTN_TEXTS.length][BTN_TEXTS[0].length];
private JTextField display = new JTextField(DISPLAY_COLUMNS);
public Phone2() {
display.setFocusable(false);
display.setFont(display.getFont().deriveFont(TEXT_POINTS));
GridLayout gridLayout = new GridLayout(BTN_TEXTS.length, BTN_TEXTS[0].length);
JPanel btnPanel = new JPanel(gridLayout);
for (int i = 0; i < BTN_TEXTS.length; i++) {
for (int j = 0; j < BTN_TEXTS[i].length; j++) {
String text = BTN_TEXTS[i][j];
JButton btn = new JButton(new BtnAction(text));
btn.setFont(btn.getFont().deriveFont(Font.BOLD, BTN_POINTS));
btnPanel.add(btn);
buttons[i][j] = btn;
}
}
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(btnPanel, BorderLayout.CENTER);
}
private class BtnAction extends AbstractAction {
public BtnAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
String text = evt.getActionCommand();
display.setText(display.getText() + text);
}
}
private static void createAndShowGui() {
Phone2 mainPanel = new Phone2();
JFrame frame = new JFrame("Phone");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel. I need to add JTextfield and JLabel to panel1 and I add panel1 to panel. I need to add JTextFields and JLabels in a Top-Bottom manner and set layout. panel1 and panel are instances of JPanel.
My code :
public class MakeScrollablePanel extends JFrame implements ActionListener
{
static JButton jButton11,jButton12;
static JPanel panel,panel1;
static JTextField jTextFields;
static JLabel label;
static JComboBox<String> jComboBox;
static Dimension dime,dime1,dime2,dime3,dime4,dime5;
static JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
BoxLayout bx=null;// #jve:decl-index=0:
int count=1,i=0;
public MakeScrollablePanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11);
add(scroll);
dime=new Dimension(600,550);
setSize(dime);
setTitle("Priyank Panel");
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
private void Show()
{
jButton11=new JButton("Add Designation");
panel=new JPanel();
bx=new BoxLayout(panel,BoxLayout.Y_AXIS);
scroll=new JScrollPane(panel);
dime1=new Dimension(500,3000);
dime5=new Dimension(500,450);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230 , 255));
jButton11.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==jButton11)
{
label=new JLabel("Add Designation "+count +" :-");
jTextFields=new JTextField(30);
panel1=new JPanel();
panel1.setBackground(new Color(204, 230 , 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel1.revalidate();
panel.revalidate();
panel.updateUI();
count++;
i++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
still not working
still I can't see thre any problem with (depsite fact that there is used BoxLayout instead of GridLayout, but result could be very similair in the case that is used many JTextFields)
.
.
from (little bit) modifyied OPs code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MakeScrollablePanel extends JFrame implements ActionListener {
private JButton jButton11, jButton12;
private JPanel panel, panel1;
private JTextField jTextFields;
private JLabel label;
private JComboBox<String> jComboBox;
private Dimension dime, dime1, dime2, dime3, dime4, dime5;
private JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
private BoxLayout bx = null;// #jve:decl-index=0:
private int count = 1, i = 0;
public MakeScrollablePanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11, BorderLayout.NORTH);
add(scroll);
setTitle("Priyank Panel");
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
private void Show() {
jButton11 = new JButton("Add Designation");
panel = new JPanel();
bx = new BoxLayout(panel, BoxLayout.Y_AXIS);
scroll = new JScrollPane(panel);
dime5 = new Dimension(500, 150);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230, 255));
jButton11.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton11) {
label = new JLabel("Add Designation " + count + " :-");
jTextFields = new JTextField(30);
panel1 = new JPanel();
panel1.setBackground(new Color(204, 230, 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel.revalidate();
panel.repaint();
count++;
i++;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}