I wrote a little code to see how the scroll Pane functions but my code never worked.
here's the code,
public Fenetre(){
this.setTitle("Data Simulator");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
String hello = "hello";
int number = 69;
JPanel content = new JPanel();
content.setBackground(Color.LIGHT_GRAY);
//Box imad = Box.createHorizontalBox();
JTextArea textArea = new JTextArea(10, 10);
JLabel imad = new JLabel();
imad.setText(hello + " your favorite number is " + number + "\nRight?");
JScrollPane scrollPane = new JScrollPane();
setPreferredSize(new Dimension(450, 110));
scrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setEnabled(true);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
add(scrollPane, BorderLayout.CENTER);
//---------------------------------------------
//On ajoute le conteneur
scrollPane.add(textArea);
scrollPane.add(imad);
content.add(textArea);
content.add(imad);
content.add(scrollPane);
this.setContentPane(content);
this.setVisible(true);
this.setResizable(false);
}
When I run it, I get a little window with the textArea and next to the text area a very little white square, which is the scrollpane i suppose because when I remove it from the code, this square disappears. When I write in the text area and exceed the window's dimension, I can't scroll vertically using the mouse wheel, and not horizontally at all. I saw many examples on internet and I can't understand why my code doesn't work??
Any help explaining how scrollpane works?
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
Only one component can be added to the viewport of the scroll pane, so the label replaces the text area.
content.add(textArea);
content.add(imad);
A component can only have a single parent. The above code removes the label from the scrollpane, so nothing is now in the scrollpane.
Try something like:
JScrollPane = new JScrollPane( textArea );
JPanel content = new JPanel( new BorderLayout() );
content.add(scrollPane, BorderLayout.CENTER);
content.add(imad, BorderLayout.PAGE_END);
setContentPane( content );
For a better solution, start with the working example found in the Swing tutorial on How to Use Text Areas and then modify the code. This way you will start with a better structured program that follows Swing standards.
Related
I have a JPanel with Constraint's of Y_Axis so that whenever I add a new Component it will automatically be Added on a new Line.But the Problem is that the Label inside is not Aligned to Left or Right. It is displayed at some distance above the JTable. How can JLabel be displayed at desired Alginment.
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
Then I added a JLabel inside panel.
JLabel labelSemester = new JLabel("Semester 1: ",SwingConstants.LEFT);
panel.add(labelSemester);
After label, I added a new JTable inside panel,
// Column Names for the Table
Object[] col_names = {"ID", "Name", "CH", "Marks", "Grade"};
// row data for the table
Object[][] table_rows = {{"CS123","Introduction to Computing",3,80,"A-"}};// One row only
JTable table = new JTable(table_rows, col_names);
panel.add(new JScrollPane(table));
Then I added a JFrame and added the Panel to show in the frame
JFrame frame = new JFrame();
// frame Title
frame.setTitle("DMC");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// adding panel inside frame
frame.add(panel);
// displaying frame
frame.show()
Note:
I have added code for auto Adjustment of column width of JTable.
Output can be seen from attached Image
All components added to the BoxLayout need the same alignmentX, otherwise you can get some weird layouts:
//JLabel labelSemester = new JLabel("Semester 1: ",SwingConstants.LEFT);
JLabel labelSemester = new JLabel("Semester 1: ");
label.semester.setAlignmentX(JLabel.LEFT_ALIGNMENT);
panel.add(labelSemester);
...
JTable table = new JTable(table_rows, col_names);
//panel.add(new JScrollPane(table));
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
panel.add( scrollPane );
Read the section from the Swing BoxLayout tutorial on Fixing Alignment Problems for more information. Keep a link to the tutorial handy for all Swing basics.
I am creating a messaging program that has multiple chats. On the side of the chat window there is a JPanel containing a List Array of all the buttons to switch chats.I am having trouble getting all the buttons in the side panel to be the same width, no matter what they contain. But whatever I try doesn't seem to work and I am looking for some help. Please can you explain what the code does and how it can be used so I can learn it for next time. Sorry if the comments aren't the best it's a work in progress as I wait till code works before adding detailed comments otherwise I am constantly changing them. :(
This is what it looks like without any chats:
This is with multiple chats and you can see the width variation
Here is the code that is run when a new user is added:
public void newUser() {
JPanel dialogue = new JPanel();
dialogue.setLayout(new BoxLayout(dialogue, BoxLayout.Y_AXIS));
//Creating/adding dialogue components
JLabel Enter_ip = new JLabel("Enter the ip address");
JTextField Get_ip = new JTextField("");
dialogue.add(Enter_ip);
dialogue.add(Get_ip);
dialogue.add(Box.createHorizontalStrut(15));
JLabel Enter_name = new JLabel("Enter the user's name");
JTextField Get_name = new JTextField("");
dialogue.add(Enter_name);
dialogue.add(Get_name);
//Creating the dialogue box
JOptionPane.showConfirmDialog(null, dialogue, "New User", JOptionPane.OK_CANCEL_OPTION);
//Getting data from dialogue box
String ip = Get_ip.getText();
String name = Get_name.getText();
//Try connecting to other user here
//Adding user message data
int size = Users_Messages_Data.size();
Users_Messages_Data.add(new ArrayList());//New user
Users_Messages_Data.get(size).add(new ArrayList());//Messages
Users_Messages_Data.get(size).add(new ArrayList());//Details
Users_Messages_Data.get(size).get(1).add(name);
Users_Messages_Data.get(size).get(1).add(ip);
Users_Messages_Data.get(size).get(1).add("port number");
//adds new UserButton
int temp = users.size();
users.add(new JButton(Users_Messages_Data.get(size).get(1).get(0)));
users.get(temp).addActionListener(this);
users.get(temp).setSize(new Dimension(500, 500));
SelectUser.add(users.get(temp), gbc);
Messaging.revalidate();
pack();
}
and here is the initialisation method:
public void MessagingGUI() {
//Creates JFrame and pane
Messaging = new JFrame();
Container pane = getContentPane();
JLabel info = new JLabel("29/07/2016 15:36");
//Creates user chats panel
SelectUser = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
SelectUser.setLayout(new BoxLayout(SelectUser, BoxLayout.Y_AXIS));
SelectUser.setSize(new Dimension(500, 500));
//Adds different chats
users = new ArrayList<JButton>();
int x;
for (x = 0; x < Users_Messages_Data.size(); x++) {
users.add(new JButton(Users_Messages_Data.get(x).get(1).get(0)));
users.get(x).addActionListener(this);
SelectUser.add(users.get(x), gbc);
}
JButton newUser = new JButton("+");
newUser.addActionListener(this);
SelectUser.add(newUser);
JScrollPane UserScroll = new JScrollPane(SelectUser,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//Creates messages feed
JPanel Messages = new JPanel();
Messages.setLayout(new BoxLayout(Messages, BoxLayout.Y_AXIS));
AllMessages = new JTextArea(10, 30);
AllMessages.setBackground(Color.WHITE);
AllMessages.setEditable(false);
AllMessages.setBorder(BorderFactory.createLineBorder(Color.BLUE, 1));
JScrollPane MessageScroll = new JScrollPane(AllMessages,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//Creates user text entry box
UserText = new JTextArea(5, 30);
//UserText.setLineWrap(true);
//UserText.setWrapStyleWord(true);
UserText.setBorder(BorderFactory.createLineBorder(Color.CYAN, 1));
UserText.setText("Enter Message. Press enter to send");
UserText.setFocusable(true);
UserText.addKeyListener(this);
UserText.setPreferredSize(new Dimension(5, 20));
//Adds all components to pane
Messages.add(info);
Messages.add(MessageScroll);
Messages.add(UserText);
pane.add(UserScroll, BorderLayout.WEST);
pane.add(Messages, BorderLayout.CENTER);
//JFrame setup
Messaging.setTitle("Messaging");
Messaging.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Messaging.setContentPane(pane);
Messaging.setVisible(true);
Messaging.setSize(400, 350);
Load_User(current_user);
}
First of all, variable names should NOT start with an upper case character. Some of your variable names are correct, other are not. Be consistent and follow Java conventions!!!
.I am having trouble getting all the buttons in the side panel to be the same width,
Don't use a BoxLayout. It does not automatically resize on the opposite axis of the layout.
Instead you can use:
a GridLayout to make all the buttons the same size. The GridLayout will also fill the area vertically which is not what you want so you will need to nest panels. So create a parent panel using a BorderLayout. Add your panel using the GridLayout with the buttons to the BorderLayout.PAGE_START of this parent panel. Then add the BorderLayout panel to the scroll pane.
a GridBagLayout. You will need to use the "fill" contstraint to have the component fill the width of the cell.
Read the Swing tutorial on Layout Managers for more information and examples.
Or maybe a different approach is to use a JList to display the users.
I have the following code: the problem is that when i run the application, the JPanel containing those components stretches because of setLineWrap(true) I've inserted the JTextArea in a JScrollPane as suggested here
http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
but with no result
titolo=new JLabel("title");
text=new JTextArea("");
scrollPane = new JScrollPane(text);
text.setLineWrap(true);
griglia=new GridBagLayout();
gbc=new GridBagConstraints();
setLayout(griglia);
buildConstraints(gbc,0,0,1,1,100,1);
griglia.setConstraints(titolo,gbc);
buildConstraints(gbc,0,1,1,1,100,100);
griglia.setConstraints(scrollPane,gbc);
add(titolo);
add(scrollPane);
Check GridBagConstraint here in the fill - The initial fill value use GridBagConstraints.NONE.
I am using a JPanel as a Main panel to display information to my users.
I have created 3 other Jpanels using methods. titlePanel, verbiagePanel, closeButtonPanel. Each of these methods are assigned as a component and added to the main panel. I am using BoxLayout in the main panel as well as the other panels.
Component titlePanel = titlePanel();
Component verbiagePanel = verbiagePanel();
Component closeButtonPanel = closeButton();
this.setTitle("EDI - Help Page");
//this.setResizable( false );
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
centerPanel.setPreferredSize(new Dimension(700, 300));
centerPanel.add(titlePanel, BorderLayout.NORTH);
centerPanel.add(Box.createRigidArea(new Dimension(0, 10)));
centerPanel.add(verbiagePanel, BorderLayout.CENTER);
centerPanel.add(Box.createRigidArea(new Dimension(0, 2)));
centerPanel.add(closeButtonPanel, BorderLayout.SOUTH);
getContentPane().add(centerPanel);
this.pack();
Above it the main panel Method. When I compile and run the dialog, everything looks right except the verbiagePanel. It is only half the size of the parent panel and the other 2 panels.
Here is the code for my verbiagePanel
private JPanel verbiagePanel() {
String titleText = "<html><font size=4><b><center>How To Use This Application</b></center></font></html>";
String text = "<html>" +
" <P align=left><font size=3>" +
" 1. Add a data to the list of Selected Datasets.<br/>" +
" (see below for detailed instructions on adding datasets)<br/>" +
" 2. Select the project to send data to.<br/>" +
" 3. Adjust the list of selected 3D or 2D translators if desired.<br/>" +
" 4. Use the Send button to continue the EDI transaction." +
" </font></P>" +
" </html>";
JLabel titleLabel = new JLabel(titleText, JLabel.CENTER);
titleLabel.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel bodyLabel = new JLabel(text, JLabel.LEFT);
bodyLabel.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(titleLabel);
p.add(bodyLabel);
p.setBorder(BorderFactory.createLineBorder(Color.black));
return p;
}
The funny thing is, if I remove the BoxLayout from the Panel. The Panel will expand to match the other 2 panels. But the spacing of the labels are crazy. I will end up having at least 5 labels in the panel. Right now I am only showing 2 to make it more simple.
I ended up using GrigBagLayout model. It worked as needed.
I've written a code which displays search results which are images in JTable..
The main problem is that even after adding JScrollbar, the scorll bar does not appear even when its needed...
Here is a snapshot of my code..
this.queryName = qname;
JFrame frame = new JFrame(title);
frame.setLayout(new GridLayout(2, 1)); //.. UPPER FOR QUERY AND LOWER FOR RESULT
this.ijtable = new ImageJTable(result, Setting.getColumnCount());
ijtable.setVisible(true);
JScrollPane pane = new JScrollPane(ijtable);
JLabel query = new JLabel(new ImageIcon(ImageResize.resize(queryName, Setting.getQueryWidth(), Setting.getQueryWidth())));
query.setVisible(true);
frame.add(query);
frame.add(ijtable);
frame.add(pane);
frame.setSize(Setting.getFrameWidth(), Setting.getFrameHeight());
frame.setVisible(true);
It's probably because you are adding both ijtable and pane. Only add pane because that control has ijtable inside it.
frame.add(ijtable);
Try removing this line. By adding the table to the frame, you're removing it from the scroll pane.