I want to create a JTabbedPane, add a JPanel to everyone and then add something to the JPanel:
private void initTabbedPane(JTabbedPane tp)
{
System.out.println("FestplattenreinigerGraphicalUserInterface::initTabbedPane()");
// Init Tab-Names
Vector<String> tabNames = new Vector<String>();
tabNames.addElement("Startseite");
tabNames.addElement("Konfiguration");
tabNames.addElement("Hilfe");
// Init Tabs
tp = new JTabbedPane();
JPanel tmpPanel;
for(int i = 0; i < tabNames.size(); i++)
{
tmpPanel = new JPanel();
tp.addTab(tabNames.elementAt(i), tmpPanel);
}
tp.setFont(new Font("Calibri", Font.BOLD, 11));
initPanelsInTabbedPane(tp);
this.getContentPane().add(tp, BorderLayout.CENTER);
}
private void initPanelsInTabbedPane(JTabbedPane tp)
{
System.out.println("FestplattenreinigerGraphicalUserInterface::initPanelsInTabbedPane()");
tp.getComponentAt(0).add(new JButton("HELLOSTUPIDJAVAIHATEU"));
}
Well it says:
incompatible types
found : java.awt.Component
required: javax.swing.JPanel
JPanel p = tp.getComponentAt(0);
But my book says that with, Component getComponentAt(int index), i can access it's content and i remember that JButton is a Component right? So wth?
If you take a look at Javadoc, you'll see that, indeed, JTabbedPane#getComponentAt(index) returns a Component. However, if you're sure it's a JPanel (which is more or less the case when accessing tabs of a JTabbedPane), you can always cast it :
((JPanel) tp.getComponentAt(0)).add(new JButton("come on, Java is nice enough, no ?"));
Or, even better if you know some things about Swing
((JCompoonent) tp.getComponentAt(0)).add(new JButton("No, Java and Swing positively rock hard awesome !"));
indeed, JPanel is a subclass of JComponent, which is
the root class of all Swing components
an awt Container
Related
I have a JPanel. Inside Panel I have kept one JLabel and three JCheckBox.
I want to keep all the checkBox in one line after JLabel. Here is the sample code and some screenshots.
Output 1
Output 2
When i change to X_AXIS it is coming everything in one line and when i switch to Y_AXIS then it is coming new line means vertically.
But my requirement is all the checkbox should come next line means after JLabel.
JLabel should come in line and all the checkBox should come in one line.
public class CheckBoxWithJLabel {
public static void main(String[] args) {
JFrame f= new JFrame("CheckBox Example");
JPanel panel = new JPanel();
panel.setBounds(40,80,600,200);
JCheckBox chk_Embrodary=new JCheckBox("Embrodary");
JCheckBox chk_Cutting=new JCheckBox("Cutting");
JCheckBox cb_Sewing=new JCheckBox("Sewing");
panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.X_AXIS));
JLabel lblHeader=new JLabel("Job Work Process Selection");
panel.add(lblHeader);
panel.add(chk_Embrodary);
panel.add(chk_Cutting);
panel.add(cb_Sewing);
f.add(panel);
f.setSize(600,400);
f.setLayout(null);
f.setVisible(true);
}
}
I want this output like
this
How to solve this problem?
I would highly suggest you to have a look through the Java Swing Tutorial, especially the Laying Out Components Within a Container section, since it seems you lack some basic understanding of how Swing and its Layout Managers are supposed to be used.
Regarding your problem:
Currently, you are using a single BoxLayout, which " puts components in a single row or column". You only want that behavior for your JCheckBoxes though, and not for your JLabel. Keeping this in mind, the solution is to split up your components and to not put all of them in a single JPanel. Doing this will grant you more flexibility in how you design your GUI, since you can use multiple layouts in different nested panels.
You could do something like this (explanation in the code comments):
public static void main(String[] args) {
JFrame f = new JFrame("CheckBox Example");
// add a Y_AXIS boxlayout to the JFrames contentpane
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JCheckBox cbEmbrodary = new JCheckBox("Embrodary");
JCheckBox cbCutting = new JCheckBox("Cutting");
JCheckBox cbSewing = new JCheckBox("Sewing");
// no need to set the bounds, since the layoutmanagers will determine the size
JPanel labelPanel = new JPanel(); // default layout for JPanel is the FlowLayout
JLabel lblHeader = new JLabel("Job Work Process Selection");
labelPanel.add(lblHeader); // JPanel for the label done
// JPanel for the comboboxes with BoxLayout
JPanel cbPanel = new JPanel();
cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.X_AXIS));
cbPanel.add(cbEmbrodary);
cbPanel.add(cbCutting);
cbPanel.add(cbSewing);
f.add(labelPanel);
f.add(cbPanel);
// No need to set the size of the JFrame, since the layoutmanagers will
// determine the size after pack()
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
Output:
Sidenotes:
Don't set fixed sizes via setSize() or setBounds() to your components. Swing is designed to be used with appropariate LayoutManagers, and if you do that, calling pack() on the JFrame before setting it visible will layout the components and determine their appropriate size. (Also, don't use null-layout for the same reasons)
If you need the JLabel to not be centered but left aligned, like in your screenshot, then use the following:
FlowLayout layout = (FlowLayout) labelPanel.getLayout();
layout.setAlignment(FlowLayout.LEFT);
I'm trying to have painted into a JPanel (which is inside a ScrollPane), a bunch of labels and RadioButtons, dynamically. I receive an ArrayList with "Advice" objects, and I want to iterate over them to represent them in a way I have a label that describes them, and then, two radio buttons (to choose "Yes" or "No").
But at the moment, with this code at the JFrame's constructor, it's not properly working:
// My constructor
public CoachingFrame(AdvicesManager am) {
initComponents();
this.am = am;
// I set the layout for the inner panel (since ScrollPane doesn't allow BoxLayout)
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Iterate over the arraylist
for(int i=0;i<am.advices.size();i++){
//Add elements to the panel
panel.add(new JLabel( am.advices.get(i).getQuestion()));
ButtonGroup group = new ButtonGroup();
// Group the RadioButtons inside another panel, so I can use FlowLayout
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout());
JRadioButton rad1 = new JRadioButton();
JRadioButton rad2 = new JRadioButton();
group.add(rad1);
group.add(rad2);
buttonsPanel.add(rad1);
buttonsPanel.add(rad2);
// Add the radiobuttons' panel to the main one, and revalidate
panel.add(buttonsPanel);
panel.revalidate();
}
// Finally, add the panel to the ScrollPane.
questions.add(panel);
}
I receive the arraylist correctly; I already checked that. The problem seems to be when painting the components.
Since I always use the NetBeans GUI creator, I'm not very used to add components via code. Can someone help me? I guess I'm missing something here.
edit: Note that "questions" is the ScrollPane object!
edit 2: This "questions" panel should have all those components painted: http://i.imgur.com/tXxROfn.png
As Kiheru said, ScrollPane doesn't allow views (like my JPanel) to be added with .add(), instead, I had to use .setViewportView(Component). Now it's working perfectly, thank you!
i'm building a Java program. The core of this program is visualized in a JFrame with a JMenuBar and various JMenuItem and JMenu. The point is that I added a centralPanel to all the frame,but if I add something to the centralPanel it shows only if i resize the main frame, reducing it or enlarging it!
Here's the code:
This is the constructor:
public UserFrame(Sistema system)
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
storicoPanel = new JPanel();
carrelloPanel = new JPanel();
carrelloFrame = new JFrame();
pane = new JScrollPane(storicoArea);
close = new JButton("Chiudi");
this.sistema = system;
menu = new JMenuBar();
this.setJMenuBar(menu);
centralPanel = new JPanel();
add(centralPanel);
Here i added the centralPanel, and here, in an ActionListener, i try to add something to it, but it doesnt' work:
public ActionListener createVisualizzaStorico(final ArrayList<Acquisto> array)
{
class Visualize implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
storicoPanel.removeAll();
for(Acquisto a : array)
{
Articolo temp = a.getArticolo();
if(temp instanceof Vacanza)
storicoPanel.add(new VacanzaPanel((Vacanza)temp));
else if(temp instanceof BeneDiConsumo)
storicoPanel.add(new BeneDiConsumoPanel((BeneDiConsumo)temp));
else if(temp instanceof Cena)
storicoPanel.add(new CenaPanel((Cena)temp));
else
storicoPanel.add(new PrestazioniOperaPanel((PrestazioneOpera)temp));
}
centralPanel.add(storicoPanel);
centralPanel.repaint();
Could you please help me? Thanks!
Use a CardLayout instead of trying to add and remove component/panels. It's much cleaner and you don't have to worry about the things that may go wrong, like what you're facing here.
See this example to see how easy and cleaner it is. Also see How to Use CardLayout tutorial
Side Notes
A component can only have one parent container. Though I don't think this is causing a problem for you. It's good to know. First I see you trying to add storicoPanel to a JScrollPane, JScrollPane that you never add to the centerPanel. Then you later add the storicoPanel to the centerPanel. The JScrollPane will no longer be the parent after this.
I'm not sure what you're using this carrelloFrame = new JFrame(); for, but you're class is already a JFrame, why create another?
Just FYI, when adding components dynamically, you need to revalidate() and repaint(). Though, in your situation, I am totally against the adding and removing of components, because this looks like a perfect case for a CardLayout.
Try these..
centralPanel.updateUI(); // or
SwingUtilities.updateComponentTreeUI(getRootPane());
Execute your frame code in SwingUtilities.invokeLater()
Instead of repaint() call updateUI() or
SwingUtilities.updateComponentTreeUI(getRootPane()) to update the
user interface.
How can I create an interface similar like the following in Java (tweetie)?
I was thinking of using a JTable with one columns and customized cell that has an image in it...not sure how to do it though.
If you are only going to have one column, than you can just use JList and it will be a little easier. But to answer your question, you need to create a cell renderer that can be used to represent the object in the list. The renderer would have a method (getListCellRendererComponent) which would return a Component that can be used to represent each item.
The simplest way (I would do it) would be to use a Vertical BoxLayout on a JPanel. Each tweet would then be its own JPanel (TweetPanel extends JPanel) with a BorderLayout where the image is on the WEST, and the tweet text is in the CENTER.
The following is how I would go about laying out one of the restaurant panels.
public ResturantPanel extends JPanel {
public ResturantPanel(String name, String address, List<String> reviews, Icon icon){
setLayout(new BorderLayout());
JLabel iconLabel = new JLabel(theIcon);
JLabel nameLabel = new JLabel(name);
JLabel addressLabel = new JLabel(address);
JPanel southReviewPanel = new JPanel();
southReviewPanel.setLayout(new BoxLayout(southReviewPanel, BoxLayout.Y_AXIS);
for (String review: reviews) {
southReviewPanel.add(new JTextArea(review));
}
add(southReviewPanel);
add(iconLabel, BorderLayout.West);
JPanel northPane = new JPanel();
northPane.setLayout(new BoxLayout(northPane, BoxLayout.Y_AXIS));
northPane.add(nameLabel);
northPane.add(addressLabel);
add(northPane, BorderLayout.North);
}
}
Note, this was written entirely in this editor window. It will have some typos. Also, you will have to play with the sizing of the icon, the text areas added to the southReviewPanel, and southReviewPanel to get everything how you want it to look.
You would then place a bunch of these on a JPanel in a JScrollPane, and you are good to go.
I'm trying to add a JList to a GUI, but am wondering how to position it? I want it to appear on the right hand side of the TextArea for data that will be sent to the GUI for selection.
Can anyone suggest how to do this? Here is the code (note: very new to Java and GUI's)
protected static void createAndShowGUI() {
GUI predict = new GUI();
JFrame frame = new JFrame("Phone V1.0");
frame.setContentPane(predict.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setMinimumSize(new Dimension(300, 400));
frame.setVisible(true); // Otherwise invisible window
}
private JPanel createContentPane() {
JPanel pane = new JPanel();
TextArea = new JTextArea(5, 10);
TextArea.setEditable(false);
TextArea.setLineWrap(true);
TextArea.setWrapStyleWord(true);
TextArea.setWrapStyleWord(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
//Adds the buttons from Top to Bottom
String[] items = {"dsfsdfd"};
list = new JList(items);
JScrollPane scrollingList = new JScrollPane(list);
int orient = list.getLayoutOrientation();
JPanel window = new JPanel();
pane.add(window);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 3));
JButton[] buttons = new JButton[] {
new JButton("Yes"),
new JButton(""),
new JButton("Clr"),
new JButton("1"),
new JButton("2abc"),
new JButton("3def"),
new JButton("4ghi"),
new JButton("5jkl"),
new JButton("6mno"),
new JButton("7pqrs"),
new JButton("8tuv"),
new JButton("9wxyz"),
new JButton("*+"),
new JButton("0_"),
new JButton("^#")
}; // Array Initialiser
for (int i = 0; i < buttons.length; i++) {
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
pane.add(TextArea);
pane.add(list);
pane.add(buttonPanel);
return pane;
}
Read the section from the Swing tutorial on Using Layout Mananger. There is no need to only use a single layout manager. You can nest layout managers to get the desired effect.
Wrap your TextArea and list in a new panel with a BorderLayout manager. Basically the BorderLayout manager lets you arrange components using north, south, east, west and center coordinates. The components at the center takes all available space as the parent container has more space available to it.
private JPanel createContentPane() {
JPanel pane = new JPanel(); //this is your main panel
JPanel textAreaPanel = new JPanel(new BorderLayout()); //the wrapper
//Some more code...
//Then at the end
//Make your TextArea take the center
textAreaPanel.add(TextArea, BorderLayout.CENTER);
//And the list to the east
textAreaPanel.add(list, BorderLayout.EAST);
pane.add(textAreaPanel);
pane.add(buttonPanel);
return pane;
}
The cool thing is that you can nest panels inside other panels, adding them different layout managers to get your desired layout.
On an unrelated note, try to follow Java naming conventions. Instead of JTextArea TextArea use JTextArea textArea. It makes it easier for you and people reading your code to understand it.
You could use a layout manager like Mig Layout for that kind of positionning.
(source: miglayout.com)
I could recommend you FormLayout. Before I found this layout I had a real pain with GridBagLayout. FormLayout is more powerful and much more convenient to learn and use and it is free. Give it a chance.
As others suggested, familiarize yourself with the concept of layout managers. There are several that come with the standard Swing API and several good 3rd party ones out there.
In addition, you will want to add the JList to a scroll pane (JScrollPane). You may want to consider adding it to a split pane (JSplitPane). And by consider I don't mean "do it because some guy on the net said so" I mean "do it if it makes sense for your end users".