Remove JTextPane Lines and Keep Styling - java

I'm using JTextPane and StyledDocument for styling message and I want to clear the messages or clear only the oldest message.
I can easily clear all by using:
textPane.setText("");
But if I want to clear all, except some lines, then not sure if/how it can be done.
I tried
textPane.setText(textPane.getText().substring(0, Math.min(200, textPane.getText().length())));
but the issue is that it remove the content styling.
Here is simple demo that shows the issue.
Is there an easy way to do it?
import java.awt.Color;
import java.awt.Dimension;
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.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestJTextPane {
private JTextPane infoTextPane = new JTextPane();
private StyledDocument styledDocument;
private SimpleAttributeSet attributeSet = new SimpleAttributeSet();
private JButton addText;
private JButton clearText;
public static void main(String[] argv) {
new TestJTextPane();
}
public TestJTextPane(){
addText = new JButton("add");
addText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
StyleConstants.setForeground(attributeSet, Color.GREEN);
StyleConstants.setBackground(attributeSet, Color.BLACK);
StyleConstants.setBold(attributeSet, true);
StyleConstants.setFontSize(attributeSet, 20);
styledDocument.insertString(styledDocument.getLength(), "sample text message to add\n", attributeSet);
infoTextPane.setCaretPosition(infoTextPane.getDocument().getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
clearText = new JButton("clear");
clearText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//infoTextPane.setText("");
infoTextPane.setText(infoTextPane.getText().substring(0, Math.min(200, infoTextPane.getText().length())));
}
});
styledDocument = infoTextPane.getStyledDocument();
JPanel p = new JPanel();
p.add(addText);
p.add(clearText);
p.add(infoTextPane);
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
f.setPreferredSize(new Dimension(400, 400));
f.pack();
f.setVisible(true);
}
}

Figure how to do it with Element. For example, the below code will keep only the latest 2 messages.
Element root = infoTextPane.getDocument().getDefaultRootElement();
try {
while(root.getElementCount() > 3){
Element first = root.getElement(0);
infoTextPane.getStyledDocument().remove(root.getStartOffset(), first.getEndOffset());
}
} catch (BadLocationException e1) {
// FIXME Auto-generated catch block
e1.printStackTrace();
}

Related

How do I add Command + Delete functionality in JTextPane [duplicate]

I have a small text editor that I made in Java Swing with JTextArea.
I want to implement the following:
When the user presses Command+Backspace I want to remove all the text from the beginning of the line up to the cursor. How to implement this? I tried using KeyListeners but it doesn't work.
For example (before user presses Command+Backspace) ...
Result (after user presses Command+Backspace) ...
My code (Not 100% exact compared to the image):
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main{
static JFrame frame = new JFrame();
static JTextArea textArea = new JTextArea();
static JScrollPane scrollPane = new JScrollPane(textArea);
public static void main(String[] args) throws BadLocationException {
frame.setTitle("Untitled");
addComponentsToFrame();
textArea.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == (Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | KeyEvent.VK_BACK_SPACE)){
System.out.println("Delete"); //Placeholder
}
}
#Override
public void keyPressed(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
});
}
public static void addComponentsToFrame(){
scrollPane.setAutoscrolls(true);
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For now when I have placed a print Statement as a place holder, since I don't know how to delete all the words from the beginning of the line up to the cursor (i.e. the logic).
Credits: #Abra
Solution:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import java.awt.Toolkit;
public class TestSamplePrograms {
private JTextArea textarea;
private void buildAndShowGui() {
JFrame frame = new JFrame("Untitled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
textarea = new JTextArea(20, 60);
InputMap im = textarea.getInputMap();
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
im.put(ks, "del2EoL");
ActionMap am = textarea.getActionMap();
am.put("del2EoL", new Delete2EOL());
JScrollPane pane = new JScrollPane(textarea);
return pane;
}
#SuppressWarnings("serial")
private class Delete2EOL extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
int caretOffset = textarea.getCaretPosition();
int lineNumber = 0;
try {
lineNumber = textarea.getLineOfOffset(caretOffset);
int startOffset = textarea.getLineStartOffset(lineNumber);
int endOffset = textarea.getLineEndOffset(lineNumber);
textarea.replaceRange("", startOffset, endOffset);
} catch (BadLocationException ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new TestSamplePrograms().buildAndShowGui());
}
}

Command + Backspace functionality in JTextArea

I have a small text editor that I made in Java Swing with JTextArea.
I want to implement the following:
When the user presses Command+Backspace I want to remove all the text from the beginning of the line up to the cursor. How to implement this? I tried using KeyListeners but it doesn't work.
For example (before user presses Command+Backspace) ...
Result (after user presses Command+Backspace) ...
My code (Not 100% exact compared to the image):
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main{
static JFrame frame = new JFrame();
static JTextArea textArea = new JTextArea();
static JScrollPane scrollPane = new JScrollPane(textArea);
public static void main(String[] args) throws BadLocationException {
frame.setTitle("Untitled");
addComponentsToFrame();
textArea.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == (Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | KeyEvent.VK_BACK_SPACE)){
System.out.println("Delete"); //Placeholder
}
}
#Override
public void keyPressed(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
});
}
public static void addComponentsToFrame(){
scrollPane.setAutoscrolls(true);
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For now when I have placed a print Statement as a place holder, since I don't know how to delete all the words from the beginning of the line up to the cursor (i.e. the logic).
Credits: #Abra
Solution:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import java.awt.Toolkit;
public class TestSamplePrograms {
private JTextArea textarea;
private void buildAndShowGui() {
JFrame frame = new JFrame("Untitled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
textarea = new JTextArea(20, 60);
InputMap im = textarea.getInputMap();
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
im.put(ks, "del2EoL");
ActionMap am = textarea.getActionMap();
am.put("del2EoL", new Delete2EOL());
JScrollPane pane = new JScrollPane(textarea);
return pane;
}
#SuppressWarnings("serial")
private class Delete2EOL extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
int caretOffset = textarea.getCaretPosition();
int lineNumber = 0;
try {
lineNumber = textarea.getLineOfOffset(caretOffset);
int startOffset = textarea.getLineStartOffset(lineNumber);
int endOffset = textarea.getLineEndOffset(lineNumber);
textarea.replaceRange("", startOffset, endOffset);
} catch (BadLocationException ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new TestSamplePrograms().buildAndShowGui());
}
}

Retrieving values from properties file when key node is clicked in JTree

I have a Jtree that displays all the keys in my properties file - however when I click on a node I want it to obtain the value that goes with the currently selected key and display it in my panel on the right of my Jtree. I have my code below, if anyone knows how I'd display that it would a big help!
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.io.FileInputStream;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeSelectionModel;
import net.miginfocom.swing.MigLayout;
public class HelpSystem implements TreeSelectionListener {
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField textFieldSearch;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HelpSystem window = new HelpSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public HelpSystem() {
frame = new JFrame();
frame.setBounds(100, 100, 842, 516);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new MigLayout("", "[grow]", "[][grow]"));
JSplitPane splitPane = new JSplitPane();
frame.getContentPane().add(splitPane, "cell 0 1,grow");
JPanel panel = new JPanel();
splitPane.setRightComponent(panel);
panel.setLayout(new MigLayout("", "[]", "[]"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
splitPane.setLeftComponent(tabbedPane);
JPanel panelSearch = new JPanel();
panelSearch.setPreferredSize(new Dimension(7, 10));
tabbedPane.addTab("Search", null, panelSearch, null);
panelSearch.setLayout(new MigLayout("", "[][][]", "[][][][][][][][][]"));
JLabel lblSearchForGit = new JLabel("Search for Git command:");
panelSearch.add(lblSearchForGit, "cell 0 1,alignx center");
textFieldSearch = new JTextField();
panelSearch.add(textFieldSearch, "cell 0 3,growx");
textFieldSearch.setColumns(10);
JLabel lblSearchForGit_1 = new JLabel("search for git command to display info in the right");
panelSearch.add(lblSearchForGit_1, "cell 0 8");
JPanel panelLookup = new JPanel();
panelLookup.setToolTipText("Lookup a command");
tabbedPane.addTab("Lookup", null, panelLookup, null);
panelLookup.setLayout(new MigLayout("", "[grow][grow]", "[grow][grow][][][][][][][][][][]"));
JScrollPane scrollPane = new JScrollPane();
panelLookup.add(scrollPane, "flowx,cell 0 0 2 11,grow");
///Area related to displaying JTree inside jpanel /////
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.WHITE);
panel_1.setSize(new Dimension(22, 0));
scrollPane.setViewportView(panel_1);
Properties properties = new Properties();
try {
//properties file - get the data in the file
String filename = "GitCommands.properties";
// Properties p =System.getProperties();
Properties p = properties;
FileInputStream fileInputStream = new FileInputStream(filename);
//load properties file
properties.load(fileInputStream);
panel_1.setLayout(new MigLayout("", "[64px][][][][][][][]", "[322px,grow,fill][][]"));
//sets up a scroll pane to view all of the tree
JScrollPane scrollpane = new JScrollPane();
//frame.getContentPane().add(scrollpane, "Center");
panel_1.add(scrollpane, "cell 0 5,alignx left,aligny top");
//what will happen when the user closes the program
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//sets new jtree
final JTree tree = new JTree(p);
//Where the tree is initialized:
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
//Listen for when the selection changes.
tree.addTreeSelectionListener(this);
panel_1.add(tree, "cell 7 0 1 3");
tree.setAlignmentX(Component.RIGHT_ALIGNMENT);
tree.setBounds(new Rectangle(0, 0, 40, 0));
tree.setToolTipText("Click a command");
//sort in to order
//allows the root of the tree to be shown
tree.setRootVisible(true);
//re size the width
tree.setSize(20, 10);
//it will be visible
frame.setVisible(true);
} catch (Exception e) {
}
}
#Override
public void valueChanged(TreeSelectionEvent e) {
//
}
}
Then I have my method to go with the listener for the event of the node being clicked
private void createSelectionListener(Object node) {
//if nothing is selected
if (node == null) return;
// retrieve the node that was selected
Object nodeInfo = ((DefaultMutableTreeNode) node).getUserObject();
// What happens when node is clicked
}
}
I am just unsure of what to put underneath //what happens when node is clicked in order to get it display?
I'm assuming your question is a continuation of the one you've asked before. What you want is to utilize a Tree Selection Listener.
import java.awt.BorderLayout;
import java.util.Properties;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
public class GetAllProperties extends JFrame {
private static final String NOTHING_SELECTED = "<nothing selected>";
private final JScrollPane treeScroll;
private final JTree tree;
private final DefaultTreeModel treeModel;
private final DefaultMutableTreeNode root;
private final JLabel descriptionLabel;
private Properties properties;
public GetAllProperties() {
setLayout(new BorderLayout());
root = new DefaultMutableTreeNode("GIT commands");
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
treeScroll = new JScrollPane(tree);
add(treeScroll, BorderLayout.WEST);
populateTree();
descriptionLabel = new JLabel(NOTHING_SELECTED);
add(descriptionLabel, BorderLayout.CENTER);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode selection =
(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if (selection != null) {
String key = (String)selection.getUserObject();
String command = properties.getProperty(key);
descriptionLabel.setText(command);
} else {
descriptionLabel.setText(NOTHING_SELECTED);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GetAllProperties().setVisible(true);
}
});
}
private void populateTree() {
// fake properties in order to avoid IO
properties = new Properties();
properties.setProperty("foo1", "bar1");
properties.setProperty("foo2", "bar2");
properties.setProperty("foo3", "bar3");
properties.setProperty("foo4", "bar4");
Set<Object> keySet = properties.keySet();
for (Object key : keySet) {
root.add(new DefaultMutableTreeNode(key));
}
tree.expandPath(new TreePath(root));
}
}
You really should consider reading and understanding the How to use Trees tutorial, like it has already been suggested to you.
I wanted to answer your prior question with the above code, but was to late, so here you go.

JLayeredPane formatting issue

I have a problem with my JLayeredPane, I am probably doing something incredibly simple but I cannot wrap my head around it. The problem i have is that all the components are merged together and have not order. Could you please rectify this as I have no idea. The order I am trying to do is have a layout like this
output
label1 (behind)
input (in Front)
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class window extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 7092006413113558324L;
private static int NewSize;
public static String MainInput;
public static JLabel label1 = new JLabel();
public static JTextField input = new JTextField(10);
public static JTextArea output = new JTextArea(main.Winx, NewSize);
public window() {
super("Satine. /InDev-01/");
JLabel label1;
NewSize = main.Winy - 20;
setLayout(new BorderLayout());
output.setToolTipText("");
add(input, BorderLayout.PAGE_END);
add(output, BorderLayout.CENTER);
input.addKeyListener(this);
input.requestFocus();
ImageIcon icon = new ImageIcon("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\.Satine\\img\\textbox.png", "This is the desc");
label1 = new JLabel(icon);
add(label1, BorderLayout.PAGE_END);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
try {
MainMenu.start();
} catch (IOException e1) {
System.out.print(e1.getCause());
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And the main class.
import java.awt.Container;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class main {
public static int Winx, Winy;
private static JLayeredPane lpane = new JLayeredPane();
public static void main(String[] args) throws IOException{
Winx = window.WIDTH;
Winy = window.HEIGHT;
window Mth= new window();
Mth.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mth.setSize(1280,720);
Mth.setVisible(true);
lpane.add(window.label1);
lpane.add(window.input);
lpane.add(window.output);
lpane.setLayer(window.label1, 2, -1);
lpane.setLayer(window.input, 1, 0);
lpane.setLayer(window.output, 3, 0);
Mth.pack();
}
}
Thank you for your time and I don't expect the code to be written for me, all I want is tips on where I am going wrong.
I recommend that you not use JLayeredPane as the overall layout of your GUI. Use BoxLayout or BorderLayout, and then use the JLayeredPane only where you need layering. Also, when adding components to the JLayeredPane, use the add method that takes a Component and an Integer. Don't call add(...) and then setLayer(...).
Edit: it's ok to use setLayer(...) as you're doing. I've never used this before, but per the API, it's one way to set the layer.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class LayeredPaneFun extends JPanel {
public static final String IMAGE_PATH = "http://duke.kenai.com/" +
"misc/Bullfight.jpg";
public LayeredPaneFun() {
try {
BufferedImage img = ImageIO.read(new URL(IMAGE_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel backgrndLabel = new JLabel(icon);
backgrndLabel.setSize(backgrndLabel.getPreferredSize());
JPanel forgroundPanel = new JPanel(new GridBagLayout());
forgroundPanel.setOpaque(false);
JLabel fooLabel = new JLabel("Foo");
fooLabel.setFont(fooLabel.getFont().deriveFont(Font.BOLD, 32));
fooLabel.setForeground(Color.cyan);
forgroundPanel.add(fooLabel);
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JButton("bar"));
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JTextField(10));
forgroundPanel.setSize(backgrndLabel.getPreferredSize());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(backgrndLabel.getPreferredSize());
layeredPane.add(backgrndLabel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(forgroundPanel, JLayeredPane.PALETTE_LAYER);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(new JTextArea("Output", 10, 40)));
add(layeredPane);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayeredPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayeredPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java Box Class: Unsolvable: aligning components to the left or right

I have been trying to left align buttons contained in a Box to the left, with no success.
They align left alright, but for some reason dont shift all the way left as one would imagine.
I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me.
Thanks, Eric
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MainGUI extends Box implements ActionListener{
//Create GUI Components
Box centerGUI=new Box(BoxLayout.X_AXIS);
Box bottomGUI=new Box(BoxLayout.X_AXIS);
//centerGUI subcomponents
JTextArea left=new JTextArea(), right=new JTextArea();
JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right);
//bottomGUI subcomponents
JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info");
//Create Menubar components
JMenuBar menubar=new JMenuBar();
JMenu fileMenu=new JMenu("File");
JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit");
int returnVal =0;
public MainGUI(){
super(BoxLayout.Y_AXIS);
initCenterGUI();
initBottomGUI();
initFileMenu();
add(centerGUI);
add(bottomGUI);
addActionListeners();
}
private void addActionListeners() {
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
encrypt.addActionListener(this);
decrypt.addActionListener(this);
close.addActionListener(this);
info.addActionListener(this);
}
private void initFileMenu() {
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(exit);
menubar.add(fileMenu);
}
public void initCenterGUI(){
centerGUI.add(leftScrollPane);
centerGUI.add(rightScrollPane);
}
public void initBottomGUI(){
bottomGUI.setAlignmentX(LEFT_ALIGNMENT);
//setBorder(BorderFactory.createLineBorder(Color.BLACK));
bottomGUI.add(encrypt);
bottomGUI.add(decrypt);
bottomGUI.add(close);
bottomGUI.add(info);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// find source of the action
Object source=arg0.getSource();
//if action is of such a type do the corresponding action
if(source==close){
kill();
}
else if(source==open){
//CHOOSE FILE
File file1 =chooseFile();
String input1=readToString(file1);
System.out.println(input1);
left.setText(input1);
}
else if(source==decrypt){
//decrypt everything in Right Panel and output in left panel
decrypt();
}
else if(source==encrypt){
//encrypt everything in left panel and output in right panel
encrypt();
}
else if(source==info){
//show contents of info file in right panel
doInfo();
}
else {
System.out.println("Error");
//throw new UnimplementedActionException();
}
}
private void doInfo() {
// TODO Auto-generated method stub
}
private void encrypt() {
// TODO Auto-generated method stub
}
private void decrypt() {
// TODO Auto-generated method stub
}
private String readToString(File file) {
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader br=new BufferedReader(fr);
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String input="";
while(line!=null){
input=input+"\n"+line;
try {
line=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return input;
}
private File chooseFile() {
//Create a file chooser
final JFileChooser fc = new JFileChooser();
returnVal = fc.showOpenDialog(fc);
return fc.getSelectedFile();
}
private void kill() {
System.exit(0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MainGUI test=new MainGUI();
JFrame f=new JFrame("Tester");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(test.menubar);
f.setPreferredSize(new Dimension(600,400));
//f.setUndecorated(true);
f.add(test);
f.pack();
f.setVisible(true);
}
}
Read the section from the Swing tutorial on How to Use Box Layout. It explains (and has an example) of how BoxLayout works when components have different alignments.
The simple solution is to add:
centerGUI.setAlignmentX(LEFT_ALIGNMENT);
Not sure why the buttons are aligned the way they are, but it's probably because they are trying to align with the box above it (I'm sure someone better versed in Swing can give you a better answer to that one). A handy way to debug layout issues is to highlight the components with coloured borders, e.g. in your current code:
centerGUI.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(centerGUI);
bottomGUI.setBorder(BorderFactory.createLineBorder(Color.RED));
add(bottomGUI);
However, if I had those requirements, I'd use a BorderLayout, e.g. this code is loosely based on yours, I removed the unnecessary bits, to concentrate on the layout portion (you should do this when asking questions, it allows others to answer questions more easily)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Tester {
private JPanel contentPanel;
private JTextArea leftTextArea = new JTextArea();
private JTextArea rightTextArea = new JTextArea();
private JMenuBar menuBar = new JMenuBar();
public Tester() {
initialisePanel();
initFileMenu();
}
public JPanel getContent() {
return contentPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
private final void initialisePanel() {
contentPanel = new JPanel(new BorderLayout());
Box centreBox = new Box(BoxLayout.X_AXIS);
JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
centreBox.add(leftScrollPane);
centreBox.add(rightScrollPane);
Box bottomBox = new Box(BoxLayout.X_AXIS);
bottomBox.add(new JButton(new SaveAction()));
bottomBox.add(new JButton(new ExitAction()));
contentPanel.add(centreBox, BorderLayout.CENTER);
contentPanel.add(bottomBox, BorderLayout.SOUTH);
}
private void initFileMenu() {
JMenu fileMenu = new JMenu("File");
fileMenu.add(new SaveAction());
fileMenu.add(new ExitAction());
menuBar.add(fileMenu);
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save");
}
#Override
public void actionPerformed(ActionEvent e) {
handleSave();
}
}
void handleSave() {
System.out.println("Handle save");
}
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}
#Override
public void actionPerformed(ActionEvent e) {
handleExit();
}
}
void handleExit() {
System.out.println("Exit selected");
System.exit(0);
}
public static void main(String[] args) {
Tester test = new Tester();
JFrame frame = new JFrame("Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(test.getContent());
frame.setJMenuBar(test.getMenuBar());
frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setVisible(true);
}
}
Why not try using MiGLayout?
They have a lot of great online demos with source code, including lots of different alignment examples.

Categories