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

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.

Related

Remove JTextPane Lines and Keep Styling

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

Why won't the JButtons, JLabels and JTextFields be displayed?

This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().

how to make a jscrollpane scroll from the start to the end?

I'm trying to make a jscorllpane automatic scroll from the start to the end. I use set value method for verticalbar but it's doesn't work. How can i make it scroll ?
Here is my code: When i run this code it just jump to the end of the jscorllpane instead of scorlling step by step
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
run();
}
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum()+i);
i += 50;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
I think the problem is your calls to repaint are queued for computation by EDT, but EDT is busy executing your actionPerformed. EDT will execute your repaint requests only after your run() completes. That's why you can see only the final result.
I'm not sure I can make it clear... check this code, it works for me:
import java.awt.BorderLayout;
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.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
class JScrollPaneToTopAction implements ActionListener, Runnable {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
new Thread(this).start();
}
#Override
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum() + i);
i += 50;
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
}
});
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
I hope it helps.

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