How to strike through text in JTextArea in java? - java

I am trying to add text in a JTextArea.
But i need some of the text to be strike through and some to added as it is.
I have searched over the internet, but couldn't find any answer.
Any help on what to refer?

JTextArea allow you set font style, but you cannot set style to text partially. Please see the code below, you can use setFont method to specify font with strikethru style, but it applies to all text in the JTextArea:
JTextArea area = new JTextArea();
Font font = new Font("arial", Font.PLAIN, 12);
Map fontAttr = font.getAttributes();
fontAttr.put (TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
Font myFont = new Font(fontAttr);
area.setFont (myFont);
area.setText ("Hello");
Whereas, if you want some text are in strikethru and some not, then you have to use JTextPane with StyledDocument, but I do not recommend this because you need a lot of tweaking to display your content with specific style. Below code may give you the idea:
DefaultStyledDocument doc = new DefaultStyledDocument();
StyleContext sc = new StyleContext();
Style style = sc.addStyle("strikethru", null);
StyleConstants.setStrikeThrough (style,true);
doc.insertString (0, "Hello ", null);
doc.insertString (6, "strike through ", style);
JTextPane pane = new JTextPane(doc);

You can use below code. Here some of the strike text "#11#","#22#" and some to added text "#yicHFRx1nc#" ,"#icHFRx1nc#" which replace of strike text.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaExample {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public JTextAreaExample() {
prepareGUI();
}
public static void main(String[] args) {
JTextAreaExample swingControlDemo = new JTextAreaExample();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("JTextArea Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo() {
headerLabel.setText("JTextArea");
JLabel descriptionLabel = new JLabel("Description: ", JLabel.RIGHT);
final JTextArea descriptionTextArea = new JTextArea("Enter String ", 5, 20);
JScrollPane scrollPane = new JScrollPane(descriptionTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String b = descriptionTextArea.getText().replace("#11#", "#yicHFRx1nc#")
.replace("#22#", "#icHFRx1nc#");
System.out.println("b=" + b);
statusLabel.setText(b);
}
});
controlPanel.add(descriptionLabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}

Related

How to add new line after JTextField in each iteration of loop?

I have to display a map containing two columns and the size is dynamic. I am currently displaying it in a panel, but the problem is I cannot start each row of the map in the new line, rather it depends on the frame size of the display. Here is the full code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.awt.BorderLayout;
import java.awt.Image;
public class P05 {
private JLabel label;
private JLabel label1;
private JLabel label3;
private JTextField tf;
private JPanel panel;
public P05() {
JFrame frame = new JFrame("Search result and score");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel buttonPane = new JPanel();
label = new JLabel("Search Result: ");
label1 = new JLabel();
label3 = new JLabel("Score: ");
tf=new JTextField(10);
tf.setBounds(10,10, 150,20);
JButton button = new JButton("Search");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
label1.setText("The input query is " + text);
panel.removeAll();
panel.add(label);
panel.add(label3);
int i = 0;
Map < String, Double> map = new HashMap < String, Double> ();
map.put("Jennifer Anniston", 31.0);
map.put("brad_pit", 29.0);
map.put("Angelina Jolie", 30.0);
map.put("badley", 21.0);
map.put("Leonardo Decaprio", 43.0);
map.put("Kate Winslet", 41.0);
map.put("Julia Roberts", 40.0);
map.put("Emma Watson", 34.0);
map.put("Mayim Bialik", 28.0);
map.put("Cobie Smulders", 28.0);
for(String item:map.keySet()) {
JTextField t1[] = new JTextField[12];
t1[i] = new JTextField(20);
t1[i].setText(item );
panel.add(t1[i]);
JTextField t2[] = new JTextField[12];
t2[i] = new JTextField(5);
t2[i].setText(Double.toString(map.get(item)));
panel.add(t2[i]);
i++;
}
panel.add(label1);
panel.revalidate();
}
});
buttonPane.add(tf);
buttonPane.add(button);
panel = new JPanel();
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new P05();
}
The output looks like somewhat this:
The quick and dirty solution right now is for me to set the frame size of lower width and it will come in a new line, but in that case, if the text field contains a value with many characters it will not show the whole text. So need a solution to add a new line after each row.

How do you add a JPanel from another class to a panel with CardLayout?

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);
}
}
}

JSwing Split Panes won't display

I am creating a simple messenger in Java(just for learning purposes) and I am trying to have a friends tab that, on the left side is the list of friends, and the right side is the messages with the friend that you click on, but whenever I try to add the JSplitPane in the tab, but it doesn't display. I have done this exact same code(except I only did the JSplitPane stuff and its components, not the other tabs and the menus and such.
All my code
package Client;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane, friendChatScrollPane, friendListScrollPane;
JSplitPane friendsSplitPane;
JTextArea friendChatArea, testArea;
JTextField friendChatField, testField;
JList friendList;
Box box;
DefaultListModel friends;
public ClientMain() {
super("Messenger Client");
//Networking();
/** MAIN PANEL **/
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
/** TEST PANEL **/
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
/** FRIENDS PANEL **/
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
/** TEST PANEL **/
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
/** SET UP **/
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void createSplitPane() {
friendListScrollPane = new JScrollPane();
friendListScrollPane.add(new JLabel("Hello"));
friendChatArea = new JTextArea();
friendChatArea.setBounds(0, 150, HEIGHT, HEIGHT);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
Dimension minimumSize = new Dimension(WIDTH/2 , HEIGHT);
friendListScrollPane.setMinimumSize(minimumSize);
//friendsSplitPane.setLeftComponent()
friendsSplitPane.add(friendChatArea);
friendsSplitPane.setRightComponent(friendChatScrollPane);
}
}
The specific JSplitPane code(part of the code above)
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
friendsPanel.setLayout(null);
your friendsPanel has the null layout and you are adding split pane as:
friendsPanel.add(friendsSplitPane);
to add a component to a container(friendsPanel) with null layout, you must specify the bound of the component you are adding with component.setBounds() method. But seriously why are even using null layout ? Don't use it. It has been already advice from page to page in by the swing family of stack overflow. Try to use one of the layout manager the Swing developer has created for us with effort wasting time from day after day just to save our own time.
Start learning : Lesson: Laying Out Components Within a Container. Let us give some value their efforts for saving our time, which we are spending just to find the answer: uhh! where is my component!?!

Centering image in a JFrame?

I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

MigLayout resizing with JScrollPane

I searched a little bit and did not find a good answer to my problem.
I am working on a gui that has to be resizable. It contains a status JTextArea that is inside a JScrollPane. And this is my problem. As long as I don't manually resize my JFrame, the "initial" layout is kept and everything looks fine. As soon as I manually resize (if the JTextArea is already in scrolled mode), the layout gets messed up.
Here is a SSCCE (I got rid of most of the parts while keeping the structure of the code. I hope it's more readable that way):
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
public class Tab extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
final Tab tab = new Tab();
tab.setSize(1000, 600);
tab.setVisible(true);
new Thread(new Runnable() {
#Override
public void run() {
int count = 0;
tab.printRawMessage("start");
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
tab.printRawMessage("\ntestMessage" + count++);
}
}
}).start();
}
public Tab() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new MigLayout("insets 0", "", ""));
mainPanel.add(getLeftTopPanel(), "shrinky, top, w 450!");
mainPanel.add(getRightPanel(), "spany 5, wrap, grow, pushx, wmin 400");
mainPanel.add(getMessagePanel(), "pushy, growy, w 450!");
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
}
protected JPanel getLeftTopPanel() {
if (optionPanel == null) {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null, "Configuration", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
optionPanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label, "w 65!");
optionPanel.add(new JSeparator(JSeparator.VERTICAL), "spany 5, growy, w 2!");
optionPanel.add(new JComboBox(new String[] {"option1", "option2", "option3"}), "span, growx, wrap");
optionPanel.add(new JLabel("Type"), "right");
optionPanel.add(new JTextField("3"), "w 65!, split 2");
optionPanel.add(new JLabel("Unit"), "wrap");
optionPanel.add(new JLabel("Slide"), "right");
optionPanel.add(new JSlider(0, 100), "span, growx, wrap");
}
return optionPanel;
}
protected JTabbedPane getRightPanel() {
if (plotTabPane == null) {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
}
return plotTabPane;
}
protected JPanel getMessagePanel() {
if (messagePanel == null) {
messagePanel = new JPanel();
messagePanel.setBorder(BorderFactory.createTitledBorder(null, "Status Console", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
messagePanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
messagePanel.add(new JScrollPane(getMessageTextArea()), "push, grow");
}
return messagePanel;
}
protected JTextArea getMessageTextArea() {
if (messageTextArea == null) {
messageTextArea = new JTextArea();
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
}
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
getMessageTextArea().append(rawMessage);
getMessageTextArea().setCaretPosition(getMessageTextArea().getText().length());
}
}
The layout stuff basically happens in initComponents().
To see the problem:
Start the Application (I used miglayout-4.0-swing.jar).
Wait a bit (don't resize the window), until there are enough messages to create the scrollbar in the status text area.
Now this is what I want. The JTextArea goes all the way to the bottom of the JFrame and is scrolled if neccessary.
Now resize the window. As you can see, everything gets messed up. It will only be fine, if the window is maximized.
Here are two screenshots. The first one is how I want it to be:
The second one is after resizing:
My question: Can somebody tell me, how I keep the layout the way it is before resizing? I want to have the JTextArea go all the way down to the bottom of the window. And if neccessary, the scrollbar should appear. The only way, the status panel can go below the bottom of the window is, if the window is too small (because the configuration panel has a fixed height).
I hope I made myself clear. If not, please ask. ;)
EDIT: You can see the behaviour I want, if you remove the top JScrollPanel (the one that holds all the components). Just change
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
to
setContentPane(mainPanel);
to see what I mean. Unfortunately, this way I loose the scrollbars if the window is very small.
Focusing on your status area and using nested layouts produces the result shown below. Note in particular,
Use invokeLater() to construct the GUI on the EDT.
Use javax.swing.Timer to update the GUI on the EDT.
Use pack() to make the window fit the preferred size and layouts of its subcomponents.
Use the update policy of DefaultCaret to control scrolling.
Avoid needless lazy instantiation in public accessors.
Avoid setXxxSize(); override getXxxSize() judiciously.
Critically examine the decision to extend JFrame.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultCaret;
public class Tab extends JFrame {
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final Tab tab = new Tab();
tab.setVisible(true);
Timer t = new Timer(200, new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
tab.printRawMessage("testMessage" + count++);
}
});
t.start();
}
});
}
public Tab() {
initComponents();
}
private void initComponents() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(1, 0));
Box leftPanel = new Box(BoxLayout.Y_AXIS);
leftPanel.add(getLeftTopPanel());
leftPanel.add(getMessagePanel());
mainPanel.add(leftPanel);
mainPanel.add(getRightPanel());
this.add(mainPanel);
this.pack();
this.setLocationRelativeTo(null);
}
protected JPanel getLeftTopPanel() {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null,
"Configuration", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label);
optionPanel.add(new JSeparator(JSeparator.VERTICAL));
optionPanel.add(new JComboBox(
new String[]{"option1", "option2", "option3"}));
optionPanel.add(new JLabel("Type"));
optionPanel.add(new JTextField("3"));
return optionPanel;
}
protected JTabbedPane getRightPanel() {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
return plotTabPane;
}
protected JPanel getMessagePanel() {
messagePanel = new JPanel(new GridLayout());
messagePanel.setBorder(BorderFactory.createTitledBorder(null,
"Status Console", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
final JScrollPane sp = new JScrollPane(getMessageTextArea());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
messagePanel.add(sp);
return messagePanel;
}
protected JTextArea getMessageTextArea() {
messageTextArea = new JTextArea("", 10, 19);
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
DefaultCaret caret = (DefaultCaret) messageTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
messageTextArea.append(rawMessage + "\n");
}
}
Add size constraints to your mainPanel in the initComponents method. For instance :
mainPanel.setMinimumSize(new Dimension(400, 400));
mainPanel.setPreferredSize(new Dimension(400, 400));
mainPanel.setMaximumSize(new Dimension(400, 400));

Categories