I am trying to learn how to create user interfaces using Java Swing and I've been able to add combo boxs, text fields, labels etc but now i'm stuck.
I am trying to add a panel (or at least something that I can add graphics to such as circles or squares....anything) but when I run my program the graphics aren't showing.
How do i add a panel so that the graphics show. What i did get to show was a tiny little square when the background color was set to purple but nothing you can put anything onto.
I have tried creating a class to extend the JPanel but it doesn't work even thought it compiles.
This is just a test program to help me learn
Code:import javax.swing.*; import java.awt.*; import java.awt.geom.*; class SwingWindow extends JFrame { public SwingWindow() { super("Hello from Java Swing"); setSize(300, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); Container contentArea = getContentPane(); contentArea.setBackground(Color.white); FlowLayout flowManager = new FlowLayout(); contentArea.setLayout(flowManager); JComboBox islands = new JComboBox(); islands.addItem("Corfu"); islands.addItem("Kefalonia"); islands.addItem("Crete"); islands.addItem("Rhodes"); islands.addItem("Paxos"); islands.addItem("Mykonos"); contentArea.add(islands); JButton playButton = new JButton("Play"); contentArea.add(playButton); JButton pauseButton = new JButton("Pause"); contentArea.add(pauseButton); JButton stopButton = new JButton("Stop"); contentArea.add(stopButton); JLabel textLabel = new JLabel("Fun programming :"); contentArea.add(textLabel); JTextField text = new JTextField("", 15); contentArea.add(text); CustomPanel panel = new CustomPanel(); contentArea.add(panel); setContentPane(contentArea); } class CustomPanel extends JPanel { public void paintComponent(Graphics painter) { painter.setColor(Color.white); painter.fillRect(0,0,getSize().width, getSize().height); Font currentFont = new Font("Serif",Font.BOLD,24); painter.setFont(currentFont); Color customPurple = new Color(128,0,128); painter.setColor(customPurple); painter.drawString("A painted panel", 20, 40); } } } public class HelloSwing { public static void main(String[] args) { SwingWindow Hello = new SwingWindow(); } }


Reply With Quote


Bookmarks