Hi everyone reading this.
I am currently developing a program, that should run well displayed in different resolutions and thus has a scaling factor.
There is ne component, that I cannot find a solution for scaling for:
The JXDatePicker and its JXMonthView.
What I tried:
final JXDatePicker datePicker = new JXDatePicker(new Date());
final JXMonthView monthView = datePicker.getMonthView();
monthView.setBounds(hauptFrame.getSize().width / 2 - (100*ViewerDefaults.SZ_INCR), (165*ViewerDefaults.SZ_INCR), (200*ViewerDefaults.SZ_INCR), (200*ViewerDefaults.SZ_INCR));
monthView.setSize(monthView.getWidth() * ViewerDefaults.SZ_INCR, monthView.getHeight() * ViewerDefaults.SZ_INCR);
monthView.setPreferredColumnCount(1);
monthView.setPreferredRowCount(1);
monthView.setTraversable(true);
monthView.setZoomable(true);
datePicker.setSize(datePicker.getWidth() * 2, datePicker.getHeight() * 2);
ViewerDefaults.SZ_INCR is the scaling factor and would replace the 2 in the last line, if working.
I added the setPreferredColumnCount(1) and setPreferredRowCount(1) as I tried setting the size of the JXMonthview before, but I ended up having 4 months displayed next to each other, whereas I just wanted a single, larger displayed month.
Can you help and show me a way to enlarge the display of only on month?
EDIT:
I translated everything into using Layout Managers. The problematic behaviour remains: The month displayed is not scaled up, but simply displayed in the center. To give some more insight to the code I put the whole method here as follows(size is set earlier by Toolkit.getDefaultToolkit().getScreenSize();):
private static JPanel licBorrowPanel = null;
licBorrowPanel = new JPanel();
licBorrowPanel.setBounds(0, 20, size.width, size.height-20);
licBorrowPanel.setVisible(false);
licBorrowPanel.setBackground(Color.WHITE);
public static void licenceBorrowDialog() {
licBorrowPanel.setSize(new Dimension(hauptFrame.getSize().width, hauptFrame.getSize().height));
licBorrowPanel.setBackground(Color.WHITE);
licBorrowPanel.setLayout(new BorderLayout());
licBorrowPanel.setVisible(true);
//Create upper part of licBorrowPanel
JPanel licBorrowTop = new JPanel();
licBorrowTop.setLayout(new BoxLayout(licBorrowTop, BoxLayout.Y_AXIS));
// Label Titel
JLabel labelTitel = new JLabel("License borrwing");
labelTitel.setHorizontalAlignment(JLabel.CENTER);
labelTitel.setFont(ViewerDefaults.DEF_LABEL_FONT);
licBorrowTop.add(labelTitel);
// Header Calendar
JLabel calendarTitle = new JLabel("Please select a date", SwingConstants.LEFT);
calendarTitle.setHorizontalAlignment(JLabel.CENTER);
calendarTitle.setFont(ViewerDefaults.DEF_ROW_FONT);
licBorrowTop.add(calendarTitle);
licBorrowPanel.add(licBorrowTop, BorderLayout.PAGE_START);
//Create central part of licBorrowPanel
JPanel licBorrowCenter = new JPanel();
licBorrowCenter.setLayout(new BoxLayout(licBorrowCenter, BoxLayout.Y_AXIS));
// Label selectedDate
final JLabel labelSelectedDate = new JLabel("<HTML><BODY> </HTML></BODY>");
labelSelectedDate.setHorizontalAlignment(JLabel.CENTER);
labelSelectedDate.setFont(ViewerDefaults.DEF_LIC_FONT);
labelSelectedDate.setText("<HTML><BODY><b>Some Text</HTML></BODY>");
// Calendar
final JXDatePicker datePicker = new JXDatePicker(new Date());
final JXMonthView monthView = datePicker.getMonthView();
monthView.setPreferredColumnCount(1);
monthView.setPreferredRowCount(1);
monthView.setZoomable(true); //Removing this results in several Columns and Rows being displayed.
// Set selection to "in two days" as default
Date newDate = monthView.getSelectionDate();
newDate.setDate(newDate.getDate()+2);
datePicker.addActionListener(new ActionListener() {
//...
});
licBorrowCenter.add(monthView, BorderLayout.CENTER);
licBorrowCenter.add(labelSelectedDate, BorderLayout.CENTER);
// Footer Calendar
JLabel calendarSubTitle = new JLabel("<HTML><BODY><CENTER>Some other Text.</CENTER></HTML></BODY>", SwingConstants.LEFT);
calendarSubTitle.setFont(ViewerDefaults.DEF_FONT);
calendarSubTitle.setHorizontalAlignment(JLabel.CENTER);
calendarSubTitle.setFont(ViewerDefaults.DEF_ROW_FONT);
calendarSubTitle.setForeground(Color.RED);
licBorrowCenter.add(calendarSubTitle, BorderLayout.CENTER);
licBorrowPanel.add(licBorrowCenter);
//Create lower part of licBorrowPanel
JPanel licBorrowBottom = new JPanel();
licBorrowBottom.setLayout(new BorderLayout());
// Button OK
JButton buttonLicBorrowOK = new JButton("OK");
buttonLicBorrowOK.setFont(ViewerDefaults.DEF_LIC_FONT);
licBorrowBottom.add(buttonLicBorrowOK, BorderLayout.LINE_START);
// Button Return
JButton buttonLicReturn = new JButton("Return");
buttonLicReturn.setFont(ViewerDefaults.DEF_LIC_FONT);
licBorrowBottom.add(buttonLicReturn, BorderLayout.CENTER);
// Button Cancel
JButton buttonLicBorrowCancel = new JButton("Cancel");
buttonLicBorrowCancel.setFont(ViewerDefaults.DEF_LIC_FONT);
licBorrowBottom.add(buttonLicBorrowCancel, BorderLayout.LINE_END);
licBorrowPanel.add(licBorrowBottom, BorderLayout.PAGE_END);
// Update licBorrowPanel
licBorrowPanel.update(licBorrowPanel.getGraphics());
// several action listeners for buttons eluded..
}
"hauptframe" is the parent JFrame.
An additional problem occurred, but I think this will be solved once the JXMonthView is displayed as wanted: The licBorrowBottom is not displayed.
I hope this clarifies the problem and helps helping :)
Related
Following Java's official tutorial:(https://docs.oracle.com/javase/tutorial/uiswing/components/table.html)
However, there is no source code for this, picture:
So I did it myself. My stupid idea is that there are 4 areas in here. So BorderLayout does not work well for me. Because I already tried BorderLayout.PAGE_END. It's not working. So I make one panel consolidate all 3 panels except the first scroll pane. It's inefficient, but works.
But now the issue is when I drag(stretch) the frame, the last text-area not stretched, but the second last selection option is stretched.
How to make the last text area stretch when I resize the frame?
Below is my code:
JRadioButton mulintselRadioButton = new JRadioButton("Multiple Interval Selection");
JRadioButton singleselRadioButton = new JRadioButton("Single Selection");
JRadioButton singleIIntSelRadioButton = new JRadioButton("Single Interval Selection");
JCheckBox rowSelection = new JCheckBox("Row Selection");
JCheckBox columnSelection = new JCheckBox("Column Selection");
JCheckBox cellSelection = new JCheckBox("cell Selection");
ButtonGroup G = new ButtonGroup();
ButtonGroup GButton = new ButtonGroup();
GButton.add(rowSelection);
GButton.add(columnSelection);
GButton.add(cellSelection);
G.add(mulintselRadioButton);
G.add(singleIIntSelRadioButton);
G.add(singleselRadioButton);
JTable table = new JTable(data, columnNames);
TableColumn column = null;
table.setPreferredScrollableViewportSize(new Dimension(400,70));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
JPanel selectionMode = new JPanel(new GridLayout(4,1));
JPanel selectionOption = new JPanel(new GridLayout(4,1));
JPanel textAreaPanel = new JPanel(new GridLayout(1,1));
JPanel consolidatedPanel = new JPanel(new BorderLayout());
JLabel selcttionModeTitle = new JLabel("Selection Mode");
JLabel selcttionOptionTitle = new JLabel("Selection Options");
JTextArea textArea = new JTextArea("thsisaskjhkjk shial");
textAreaPanel.add(textArea);
selectionMode.add(selcttionModeTitle);
selectionMode.add(singleIIntSelRadioButton);
selectionMode.add(singleselRadioButton);
selectionMode.add(mulintselRadioButton);
selectionOption.add(selcttionOptionTitle);
selectionOption.add(rowSelection);
selectionOption.add(columnSelection);
selectionOption.add(cellSelection);
textArea.setText("hsknd hkcjshksdjl sldh RadioButton mulintselRadioButton = new JRadioButton(\"Multiple Interval Selection\");\n" +
" JRadioButton singleselRadioButton = new JRadioButton(\"Single Selection\");\n" +
" JRadioButton singleIIntSelRadioButton = new JRadioButton(\"Single Interval Selection\");\n" +
" JCheckBox rowSelection = new JCheckBox ");
add(scrollPane,BorderLayout.NORTH);
consolidatedPanel.add(selectionMode,BorderLayout.NORTH);
consolidatedPanel.add(selectionOption,BorderLayout.CENTER);
consolidatedPanel.add(textAreaPanel,BorderLayout.SOUTH);
add(consolidatedPanel);
Following the Java's official tutorial (the link of which you have posted in your question), one can read that it says that you can consult the example index... If you follow this link you can find a table which gives you the link to the file you are searching for. Specifically the code you are looking for is in the following link:
https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableSelectionDemoProject/src/components/TableSelectionDemo.java
As for your question, you can use a BoxLayout to achieve what you are asking, exactly as the TableSelectionDemo does. The result can strech the table and the text area, but not the middle section.
The following program segment generates the output within the red box as shown in the figure:
st = c.con.createStatement();
rs = st.executeQuery("SELECT itemName, itemMaxQty, itemImage FROM item");
while(rs.next()){
JPanel itemPanel = new JPanel();
itemPanel.setLayout(new BoxLayout(itemPanel, BoxLayout.PAGE_AXIS));
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel itemName = new JLabel(rs.getString(1));
ImageIcon itemImage = new ImageIcon(rs.getString(3));
Image scaleImage = itemImage.getImage().getScaledInstance(120, 120, Image.SCALE_SMOOTH);
JLabel imageHolder = new JLabel(new ImageIcon(scaleImage));
JSpinner quantityField = new JSpinner();
Dimension d = quantityField.getPreferredSize();
d.width = 60;
d.height = 30;
quantityField.setPreferredSize(d);
componentPanel.add(imageHolder);
componentPanel.add(quantityField);
itemPanel.add(componentPanel);
itemPanel.add(itemName);
add(itemPanel);
}
I know that probably some parts of the code are not the best way to do it, but that is what I can do for now in line with the knowledge that I have.
I actually have two problems here.
First, I don’t understand why the itemName's value (Cupcake Stand, chafers, etc) are centred.
1. How do I make it left centred such that it is aligned with its corresponding picture on top?
Second, as you can see, there is a large space in between the componentPanel (the picture and the JSpinner) and the itemName. I think it’s because the height allotted for itemName is the same as that for the componentPanel. So
2. How do I make itemName immediately below the componentPanel?
You can do that by changing the LayoutManager of itemPanel to BorderLayout (with that line itemPanel.setLayout(new BorderLayout());), and add the component to itemPanel in that way:
itemPanel.add(componentPanel, BorderLayout.CENTER);
itemPanel.add(itemName, BorderLayout.SOUTH);
I just began Swing. I'm trying to make a gallery app. I'm getting images that I manually imported and I display them. Depending on the amount of columns I put in parameters, the images' dimensions are calculated to be displayed properly. But, after a certain amount of rows, I want a scrollbar that could scroll and show the rest of images.
The images are displayed properly, like I wished but I tried to implement the scrollbar and it isn't appearing.
Could you tell me what's wrong in my code ?
GUI(String title, int width, int height, int columns) {
this.frame = new JFrame();
this.frameWidth = width;
this.columns = columns;
// set Frame's size
frame.setSize(width, height);
// set Frame's action on close button clicked
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set Frame's title
frame.setTitle(title);
frame.setResizable(false);
// set Frame's position at screen's center
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, (dim.height / 2 - frame.getSize().height / 2));
panel = new JPanel();
frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane();
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollBar, BorderLayout.EAST);
displayImages();
frame.setContentPane(panel);
}
displayImages() :
private void displayImages() {
for (File currentImage : getImagesList()) {
// 5 is flowlayout's default borders
// 2 because we got left and right borders
int totalBorders = (columns * 5) * 2;
int buttonWidth = (frameWidth - totalBorders) / columns;
ImageIcon image = new ImageIcon(new ImageIcon(currentImage.getAbsolutePath()).getImage().getScaledInstance(buttonWidth - 20, buttonWidth - 50, Image.SCALE_DEFAULT));
JButton button = new JButton(currentImage.getName());
button.setPreferredSize(new Dimension(buttonWidth, buttonWidth));
button.setIcon(image);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.addActionListener(e -> onImageClicked(currentImage.getName()));
panel.add(button);
}
}
Thanks, best regards
panel = new JPanel();
frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane();
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollBar, BorderLayout.EAST);
displayImages();
frame.setContentPane(panel);
The above code is mostly wrong. You need to:
set the layout of the panel and add the buttons to the panel
add the panel containing the buttons to the scroll pane
The basic code should be something like:
//panel = new JPanel( new GridLayout(0, 1) );
layout = new GridLayout(0, 1);
panel = new JPanel( layout );
displayImages();
//frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane(panel);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(scrollBar, BorderLayout.EAST);
//displayImages();
//frame.setContentPane(panel);
Also, there is no need to play with the sizes of each component on the panel. The GridLayout will make all the buttons the same size.
Edit:
When you want to increase the columns in the GridLayout you then just do:
layout.setColumns( layout.getColumns() + 1 );
panel.revalidate(); // this invokes the layout manager
//panel.repaint(); // sometimes needed to force repainting of panel.
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.
How do I change the font size of a JRadioButton (in Java)?
I just want to make the text 24px instead of the default so that it matches the label.
Here's a link to a picture of my window...
(I don't have enough reputation to post the image directly...)
http://i.stack.imgur.com/z60kN.png
And here's a snippet of my code...
// question 1: make the labels / radio buttons / buttons / rows
JLabel q1 = new JLabel("Question 1: 2 + 4");
q1.setFont (q1.getFont ().deriveFont (24.0f));
final JRadioButton q1a1 = new JRadioButton("5");
final JRadioButton q1a2 = new JRadioButton("6");
final JRadioButton q1a3 = new JRadioButton("7");
final JRadioButton q1a4 = new JRadioButton("8");
JButton q1go = new JButton("Go");
JButton q1exit = new JButton("Exit");
JPanel question = new JPanel();
JPanel answers = new JPanel();
JPanel buttons = new JPanel();
question.setLayout(new BoxLayout(question, BoxLayout.X_AXIS));
answers.setLayout(new BoxLayout(answers, BoxLayout.Y_AXIS));
buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
// add everything to the rows
question.add(q1);
answers.add(q1a1);
answers.add(q1a2);
answers.add(q1a3);
answers.add(q1a4);
buttons.add(q1go);
buttons.add(q1exit);
// add the rows
add(question);
add(answers);
add(answers);
add(answers);
add(answers);
add(buttons);
// group the radio buttons
ButtonGroup group = new ButtonGroup();
group.add(q1a1);
group.add(q1a2);
group.add(q1a3);
group.add(q1a4);
Thanks in advance!
-HewwoCraziness
You've already done it.
You want the label to have as same font size as Jlabel right. Then you can simply do that by
q1a1.setFont(q1.getFont()); //assign the label's font to radiobutton's font
or do the same way you've done it for label
q1a1.setFont(q1a1.getFont().deriveFont(24.0f));